]> gitweb.factorcode.org Git - factor.git/commitdiff
leb128: adding LEB128 encoding
authorJohn Benediktsson <mrjbq7@gmail.com>
Sat, 2 Sep 2023 17:18:57 +0000 (10:18 -0700)
committerJohn Benediktsson <mrjbq7@gmail.com>
Sat, 2 Sep 2023 17:19:15 +0000 (10:19 -0700)
extra/leb128/authors.txt [new file with mode: 0644]
extra/leb128/leb128-tests.factor [new file with mode: 0644]
extra/leb128/leb128.factor [new file with mode: 0644]
extra/leb128/summary.txt [new file with mode: 0644]

diff --git a/extra/leb128/authors.txt b/extra/leb128/authors.txt
new file mode 100644 (file)
index 0000000..e091bb8
--- /dev/null
@@ -0,0 +1 @@
+John Benediktsson
diff --git a/extra/leb128/leb128-tests.factor b/extra/leb128/leb128-tests.factor
new file mode 100644 (file)
index 0000000..c9b6d7d
--- /dev/null
@@ -0,0 +1,8 @@
+
+USING: leb128 tools.test ;
+
+{ B{ 0xe5 0x8e 0x26 } } [ 624485 >leb128 ] unit-test
+{ 624485 } [ B{ 0xe5 0x8e 0x26 } leb128> ] unit-test
+
+{ B{ 0xc0 0xbb 0x78 } } [ -123456 >leb128 ] unit-test
+{ -123456 } [ B{ 0xc0 0xbb 0x78 } leb128> ] unit-test
diff --git a/extra/leb128/leb128.factor b/extra/leb128/leb128.factor
new file mode 100644 (file)
index 0000000..b1381d2
--- /dev/null
@@ -0,0 +1,21 @@
+! Copyright (C) 2023 John Benediktsson
+! See https://factorcode.org/license.txt for BSD license
+
+USING: combinators.short-circuit kernel make math sequences ;
+
+IN: leb128
+
+:: >leb128 ( n -- byte-array )
+    [
+        n [
+            [ -7 shift dup ] [ 0x7f bitand ] bi :> ( i b )
+            {
+                [ i zero? b 6 bit? not and ]
+                [ i -1 = b 6 bit? and ]
+            } 0|| [ f b ] [ t b 0x80 bitor ] if ,
+        ] loop drop
+    ] B{ } make ;
+
+: leb128> ( byte-array -- n )
+    [ 0 [ [ 0x7f bitand ] [ 7 * shift ] bi* + ] reduce-index ] keep
+    dup last 6 bit? [ length 7 * 2^ neg bitor ] [ drop ] if ;
diff --git a/extra/leb128/summary.txt b/extra/leb128/summary.txt
new file mode 100644 (file)
index 0000000..ad9cdfd
--- /dev/null
@@ -0,0 +1 @@
+LEB128 (Little Endian Base 128) encoding support