commit 37a484635f9ba6467d10750a2c6293184f544dcb
parent 746d22523c60dfb97497db86545f0afe3b9d6287
Author: Drew DeVault <sir@cmpwn.com>
Date: Fri, 26 Feb 2021 17:50:57 -0500
endian: add little endian, host endian
Diffstat:
4 files changed, 52 insertions(+), 0 deletions(-)
diff --git a/endian/endian.ha b/endian/endian.ha
@@ -0,0 +1,17 @@
+// The set of functions used for endian-aware encoding.
+export type endian = struct {
+ putu32: *fn(buf: []u8, in: u32) void,
+ putu64: *fn(buf: []u8, in: u64) void,
+};
+
+// Big endian; MSB first.
+export const big: endian = endian {
+ putu32 = &beputu32,
+ putu64 = &beputu64,
+};
+
+// Little endian; LSB first.
+export const little: endian = endian {
+ putu32 = &leputu32,
+ putu64 = &leputu64,
+};
diff --git a/endian/host+aarch64.ha b/endian/host+aarch64.ha
@@ -0,0 +1,2 @@
+// The [endian] functions which map to the host architecture.
+export const host = &little;
diff --git a/endian/host+x86_64.ha b/endian/host+x86_64.ha
@@ -0,0 +1,2 @@
+// The [endian] functions which map to the host architecture.
+export const host = &little;
diff --git a/endian/little.ha b/endian/little.ha
@@ -0,0 +1,31 @@
+// Writes a u32 into a buffer in big-endian order.
+export fn leputu32(buf: []u8, in: u32) void = {
+ buf[0] = (in): u8;
+ buf[1] = (in >> 8): u8;
+ buf[2] = (in >> 16): u8;
+ buf[3] = (in >> 24): u8;
+};
+
+// Writes a u64 into a buffer in big-endian order.
+export fn leputu64(buf: []u8, in: u64) void = {
+ buf[0] = (in >> 0): u8;
+ buf[1] = (in >> 8): u8;
+ buf[2] = (in >> 16): u8;
+ buf[3] = (in >> 24): u8;
+ buf[4] = (in >> 32): u8;
+ buf[5] = (in >> 40): u8;
+ buf[6] = (in >> 48): u8;
+ buf[7] = (in >> 56): u8;
+};
+
+@test fn little() void = {
+ let buf: [8]u8 = [0...];
+ leputu32(buf, 0x12345678);
+ assert(buf[0] == 0x78 && buf[1] == 0x56
+ && buf[2] == 0x34 && buf[3] == 0x12);
+ leputu64(buf, 0x1234567887654321);
+ assert(buf[0] == 0x21 && buf[1] == 0x43
+ && buf[2] == 0x65 && buf[3] == 0x87
+ && buf[4] == 0x78 && buf[5] == 0x56
+ && buf[6] == 0x34 && buf[7] == 0x12);
+};