network.ha (1310B)
1 // SPDX-License-Identifier: MPL-2.0 2 // (c) Hare authors <https://harelang.org> 3 4 // Converts a u16 from host order to network order. 5 export fn htonu16(in: u16) u16 = { 6 if (host == &big) return in; 7 return in >> 8 | (in & 0xFF) << 8; 8 }; 9 10 // Converts a u32 from host order to network order. 11 export fn htonu32(in: u32) u32 = { 12 if (host == &big) return in; 13 return in >> 24 | in >> 8 & 0xFF00 | in << 8 & 0xFF0000 | in << 24; 14 }; 15 16 // Converts a u64 from host order to network order. 17 export fn htonu64(in: u64) u64 = { 18 if (host == &big) return in; 19 return (htonu32(in: u32): u64 << 32u64) | htonu32((in >> 32): u32): u64; 20 }; 21 22 @test fn hton() void = { 23 if (host == &big) return; 24 assert(htonu16(0xCAFE) == 0xFECA); 25 assert(htonu32(0xDEADBEEF) == 0xEFBEADDE); 26 assert(htonu64(0xCAFEBABEDEADBEEF) == 0xEFBEADDEBEBAFECA); 27 }; 28 29 // Converts a u16 from network order to host order. 30 export fn ntohu16(in: u16) u16 = htonu16(in); 31 32 // Converts a u32 from network order to host order. 33 export fn ntohu32(in: u32) u32 = htonu32(in); 34 35 // Converts a u64 from network order to host order. 36 export fn ntohu64(in: u64) u64 = htonu64(in); 37 38 @test fn ntoh() void = { 39 if (host == &big) return; 40 assert(htonu16(0xFECA) == 0xCAFE); 41 assert(htonu32(0xEFBEADDE) == 0xDEADBEEF); 42 assert(htonu64(0xEFBEADDEBEBAFECA) == 0xCAFEBABEDEADBEEF); 43 };