commit 66f0ce613a90556b4f87e203cb2c301159859553
parent c3e4eea048bf5a419dd33c258744aeb19b04d74e
Author: Virgil Dupras <hsoft@hardcoded.net>
Date: Fri, 7 Apr 2023 21:33:16 -0400
lib/endian: new unit
See doc/lib/endian.
Diffstat:
4 files changed, 79 insertions(+), 0 deletions(-)
diff --git a/fs/doc/lib/endian.txt b/fs/doc/lib/endian.txt
@@ -0,0 +1,26 @@
+# Endian-ness management
+
+This unit provides words to read and write numbers in an endian-ness that isn't
+the native one (or simply alias to the native ones if it is).
+
+At the moment, two endian-ness are supported, little-endian (LE) and big endian
+(BE). Let's consider this memory arrangement:
+
+A+0 A+1 A+2 A+3
+$12 $34 $56 $78
+
+When this memory is read as little endian, that is, the least significant byte
+first, it reads as $78563412. When it's read as big endian, that is, the most
+significant byte first, it reads as $12345678.
+
+Words provided:
+
+le@ a -- n Little-endian fetch
+le! n a -- Little-endian store
+be@ a -- n Big-endian fetch
+be! n a -- Big-endian store
+
+Each of these words have a 16-bit variant, so they can be called with a "16b"
+modulator. They don't have a "8b" one because it makes no sense.
+
+These words are implemented in HAL, so they're fast.
diff --git a/fs/lib/endian.fs b/fs/lib/endian.fs
@@ -0,0 +1,32 @@
+\ Endian-ness convenience words
+?f<< /asm/hal.fs
+
+$1234 here ! here c@ $34 = const LITTLE_ENDIAN?
+
+alias @ le@ :16b 16b @ ;
+alias ! le! :16b 16b ! ;
+LITTLE_ENDIAN? not [if] abort" TODO" [then]
+
+alias @ be@ :16b 16b @ ;
+alias ! be! :16b 16b ! ;
+LITTLE_ENDIAN? [if]
+ code be@ ( a -- n )
+ W>A, A) 8b) @, 8 i) <<,
+ A) 1 +) 8b) |, 8 i) <<,
+ A) 2 +) 8b) |, 8 i) <<,
+ A) 3 +) 8b) |, exit,
+
+ code16b
+ W>A, A) 8b) @, 8 i) <<,
+ A) 1 +) 8b) |, exit,
+
+ code be! ( n a -- )
+ W>A, drop, A) 3 +) 8b) !, 8 i) >>,
+ A) 2 +) 8b) !, 8 i) >>,
+ A) 1 +) 8b) !, 8 i) >>,
+ A) 8b) !, drop, exit,
+
+ code16b
+ W>A, drop, A) 1 +) 8b) !, 8 i) >>,
+ A) 8b) !, drop, exit,
+[then]
+\ No newline at end of file
diff --git a/fs/tests/lib/all.fs b/fs/tests/lib/all.fs
@@ -15,3 +15,4 @@ f<< /tests/lib/stack.fs
f<< /tests/lib/tree.fs
f<< /tests/lib/fmt.fs
f<< /tests/lib/crc.fs
+f<< /tests/lib/endian.fs
diff --git a/fs/tests/lib/endian.fs b/fs/tests/lib/endian.fs
@@ -0,0 +1,18 @@
+?f<< /tests/harness.fs
+?f<< /lib/endian.fs
+testbegin
+\ Endian-ness tests
+create mynum 4 nc, $12 $34 $56 $78
+mynum le@ $78563412 #eq
+mynum 16b le@ $3412 #eq
+mynum be@ $12345678 #eq
+mynum 16b be@ $1234 #eq
+$23456789 mynum le!
+mynum be@ $89674523 #eq
+0 mynum ! $2345 mynum 16b le!
+mynum be@ $45230000 #eq
+$23456789 mynum be!
+mynum le@ $89674523 #eq
+0 mynum ! $2345 mynum 16b be!
+mynum le@ $4523 #eq
+testend
+\ No newline at end of file