hare

The Hare programming language
git clone https://git.torresjrjr.com/hare.git
Log | Files | Refs | README | LICENSE

commit 5872ff742edb773beccd2856d92c5bf1b1327b38
parent ea2e9f1b20e531d79e79218c5f0561737c5a5f3b
Author: Drew DeVault <sir@cmpwn.com>
Date:   Fri, 26 Mar 2021 09:34:45 -0400

endian: complete earlier API expansions

Diffstat:
Mendian/endian.ha | 9+++++++++
Mendian/little.ha | 28++++++++++++++++++++++++++++
2 files changed, 37 insertions(+), 0 deletions(-)

diff --git a/endian/endian.ha b/endian/endian.ha @@ -1,17 +1,26 @@ // The set of functions used for endian-aware encoding. export type endian = struct { + getu16: *fn(buf: []u8) u16, + putu16: *fn(buf: []u8, in: u16) void, + getu32: *fn(buf: []u8) u32, putu32: *fn(buf: []u8, in: u32) void, putu64: *fn(buf: []u8, in: u64) void, }; // Big endian; MSB first. export const big: endian = endian { + getu16 = &begetu16, + putu16 = &beputu16, + getu32 = &begetu32, putu32 = &beputu32, putu64 = &beputu64, }; // Little endian; LSB first. export const little: endian = endian { + getu16 = &legetu16, + putu16 = &leputu16, + getu32 = &legetu32, putu32 = &leputu32, putu64 = &leputu64, }; diff --git a/endian/little.ha b/endian/little.ha @@ -1,3 +1,25 @@ +// Reads a u16 from a buffer in little-endian order. +export fn legetu16(buf: []u8) u16 = { + return + (buf[1] << 8u16) | + (buf[0] << 0); +}; + +// Writes a u16 into a buffer in little-endian order. +export fn leputu16(buf: []u8, in: u16) void = { + buf[0] = (in >> 0): u8; + buf[1] = (in >> 8): u8; +}; + +// Reads a u32 from a buffer in little-endian order. +export fn legetu32(buf: []u8) u32 = { + return + (buf[3] << 24u32) | + (buf[2] << 16u32) | + (buf[1] << 8u32) | + (buf[0] << 0); +}; + // Writes a u32 into a buffer in big-endian order. export fn leputu32(buf: []u8, in: u32) void = { buf[0] = (in): u8; @@ -20,9 +42,15 @@ export fn leputu64(buf: []u8, in: u64) void = { @test fn little() void = { let buf: [8]u8 = [0...]; + leputu16(buf, 0x1234); + assert(buf[0] == 0x34 && buf[1] == 0x12); + assert(legetu16(buf) == 0x1234); + leputu32(buf, 0x12345678); assert(buf[0] == 0x78 && buf[1] == 0x56 && buf[2] == 0x34 && buf[3] == 0x12); + assert(legetu32(buf) == 0x12345678); + leputu64(buf, 0x1234567887654321); assert(buf[0] == 0x21 && buf[1] == 0x43 && buf[2] == 0x65 && buf[3] == 0x87