commit e63c77aef85640f815606ba5a71ea0a1d1f247de
parent ab15ef5930b0fdccd3323b2bb80e72d8087ac877
Author: Drew DeVault <sir@cmpwn.com>
Date: Sun, 21 Mar 2021 13:52:35 -0400
endian: add hton, ntoh
Diffstat:
3 files changed, 43 insertions(+), 0 deletions(-)
diff --git a/endian/network.ha b/endian/network.ha
@@ -0,0 +1,40 @@
+// Converts a u16 from host order to network order.
+export fn htonu16(in: u16) u16 = {
+ if (host == &big) return in;
+ return in >> 8 | (in & 0xFF) << 8;
+};
+
+// Converts a u32 from host order to network order.
+export fn htonu32(in: u32) u32 = {
+ if (host == &big) return in;
+ return in >> 24 | in >> 8 & 0xFF00 | in << 8 & 0xFF0000 | in << 24;
+};
+
+// Converts a u64 from host order to network order.
+export fn htonu64(in: u64) u64 = {
+ if (host == &big) return in;
+ return (htonu32(in: u32): u64 << 32u64) | htonu32((in >> 32): u32): u64;
+};
+
+@test fn hton() void = {
+ if (host == &big) return;
+ assert(htonu16(0xCAFE) == 0xFECA);
+ assert(htonu32(0xDEADBEEF) == 0xEFBEADDE);
+ assert(htonu64(0xCAFEBABEDEADBEEF) == 0xEFBEADDEBEBAFECA);
+};
+
+// Converts a u16 from network order to host order.
+export fn ntohu16(in: u16) u16 = htonu16(in);
+
+// Converts a u32 from network order to host order.
+export fn ntohu32(in: u32) u32 = htonu32(in);
+
+// Converts a u64 from network order to host order.
+export fn ntohu64(in: u64) u64 = htonu64(in);
+
+@test fn ntoh() void = {
+ if (host == &big) return;
+ assert(htonu16(0xFECA) == 0xCAFE);
+ assert(htonu32(0xEFBEADDE) == 0xDEADBEEF);
+ assert(htonu64(0xEFBEADDEBEBAFECA) == 0xCAFEBABEDEADBEEF);
+};
diff --git a/scripts/gen-stdlib b/scripts/gen-stdlib
@@ -203,6 +203,7 @@ endian() {
printf '# endian\n'
gen_srcs endian \
big.ha \
+ network.ha \
little.ha \
endian.ha \
'host$(ARCH).ha'
diff --git a/stdlib.mk b/stdlib.mk
@@ -293,6 +293,7 @@ $(HARECACHE)/encoding/utf8/encoding_utf8.ssa: $(stdlib_encoding_utf8_srcs) $(std
# endian
stdlib_endian_srcs= \
$(STDLIB)/endian/big.ha \
+ $(STDLIB)/endian/network.ha \
$(STDLIB)/endian/little.ha \
$(STDLIB)/endian/endian.ha \
$(STDLIB)/endian/host$(ARCH).ha
@@ -915,6 +916,7 @@ $(TESTCACHE)/encoding/utf8/encoding_utf8.ssa: $(testlib_encoding_utf8_srcs) $(te
# endian
testlib_endian_srcs= \
$(STDLIB)/endian/big.ha \
+ $(STDLIB)/endian/network.ha \
$(STDLIB)/endian/little.ha \
$(STDLIB)/endian/endian.ha \
$(STDLIB)/endian/host$(ARCH).ha