hare

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

little.ha (1895B)


      1 // SPDX-License-Identifier: MPL-2.0
      2 // (c) Hare authors <https://harelang.org>
      3 
      4 // Reads a u16 from a buffer in little-endian order.
      5 export fn legetu16(buf: []u8) u16 = {
      6 	return
      7 		(buf[1] << 8u16) |
      8 		(buf[0] << 0);
      9 };
     10 
     11 // Writes a u16 into a buffer in little-endian order.
     12 export fn leputu16(buf: []u8, in: u16) void = {
     13 	buf[0] = (in >> 0): u8;
     14 	buf[1] = (in >> 8): u8;
     15 };
     16 
     17 // Reads a u32 from a buffer in little-endian order.
     18 export fn legetu32(buf: []u8) u32 = {
     19 	return
     20 		(buf[3] << 24u32) |
     21 		(buf[2] << 16u32) |
     22 		(buf[1] << 8u32) |
     23 		(buf[0] << 0);
     24 };
     25 
     26 // Writes a u32 into a buffer in little-endian order.
     27 export fn leputu32(buf: []u8, in: u32) void = {
     28 	buf[0] = (in): u8;
     29 	buf[1] = (in >> 8): u8;
     30 	buf[2] = (in >> 16): u8;
     31 	buf[3] = (in >> 24): u8;
     32 };
     33 
     34 // Reads a u64 from a buffer in little-endian order.
     35 export fn legetu64(buf: []u8) u64 = {
     36 	return
     37 		(buf[7] << 56u64) |
     38 		(buf[6] << 48u64) |
     39 		(buf[5] << 40u64) |
     40 		(buf[4] << 32u64) |
     41 		(buf[3] << 24u64) |
     42 		(buf[2] << 16u64) |
     43 		(buf[1] << 8u64) |
     44 		(buf[0] << 0);
     45 };
     46 
     47 // Writes a u64 into a buffer in little-endian order.
     48 export fn leputu64(buf: []u8, in: u64) void = {
     49 	buf[0] = (in >> 0): u8;
     50 	buf[1] = (in >> 8): u8;
     51 	buf[2] = (in >> 16): u8;
     52 	buf[3] = (in >> 24): u8;
     53 	buf[4] = (in >> 32): u8;
     54 	buf[5] = (in >> 40): u8;
     55 	buf[6] = (in >> 48): u8;
     56 	buf[7] = (in >> 56): u8;
     57 };
     58 
     59 @test fn little() void = {
     60 	let buf: [8]u8 = [0...];
     61 	leputu16(buf, 0x1234);
     62 	assert(buf[0] == 0x34 && buf[1] == 0x12);
     63 	assert(legetu16(buf) == 0x1234);
     64 
     65 	leputu32(buf, 0x12345678);
     66 	assert(buf[0] == 0x78 && buf[1] == 0x56
     67 		&& buf[2] == 0x34 && buf[3] == 0x12);
     68 	assert(legetu32(buf) == 0x12345678);
     69 
     70 	leputu64(buf, 0x1234567887654321);
     71 	assert(buf[0] == 0x21 && buf[1] == 0x43
     72 		&& buf[2] == 0x65 && buf[3] == 0x87
     73 		&& buf[4] == 0x78 && buf[5] == 0x56
     74 		&& buf[6] == 0x34 && buf[7] == 0x12);
     75 	assert(legetu64(buf) == 0x1234567887654321);
     76 };