]> gitweb.factorcode.org Git - factor.git/blob - extra/leb128/leb128.factor
leb128: adding LEB128 encoding
[factor.git] / extra / leb128 / leb128.factor
1 ! Copyright (C) 2023 John Benediktsson
2 ! See https://factorcode.org/license.txt for BSD license
3
4 USING: combinators.short-circuit kernel make math sequences ;
5
6 IN: leb128
7
8 :: >leb128 ( n -- byte-array )
9     [
10         n [
11             [ -7 shift dup ] [ 0x7f bitand ] bi :> ( i b )
12             {
13                 [ i zero? b 6 bit? not and ]
14                 [ i -1 = b 6 bit? and ]
15             } 0|| [ f b ] [ t b 0x80 bitor ] if ,
16         ] loop drop
17     ] B{ } make ;
18
19 : leb128> ( byte-array -- n )
20     [ 0 [ [ 0x7f bitand ] [ 7 * shift ] bi* + ] reduce-index ] keep
21     dup last 6 bit? [ length 7 * 2^ neg bitor ] [ drop ] if ;