shrub/lib/bip158.hoon

69 lines
1.3 KiB
Plaintext
Raw Normal View History

2021-01-11 12:27:40 +03:00
|%
+$ bits [wid=@ dat=@ub]
++ params
|%
++ p 19
--
2021-01-11 13:12:14 +03:00
:: +str: bit streams
2021-01-11 15:08:05 +03:00
:: read is from the front
:: write appends to the back
2021-01-11 12:27:40 +03:00
::
2021-01-11 13:12:14 +03:00
++ str
2021-01-11 12:27:40 +03:00
|%
++ read-bit
|= s=bits
^- [bit=@ub rest=bits]
?> (gth wid.s 0)
:* ?:((gth wid.s (met 0 dat.s)) 0b0 0b1)
[(dec wid.s) (end [0 (dec wid.s)] dat.s)]
==
::
2021-01-11 13:12:14 +03:00
++ read-bits
|= [n=@ s=bits]
^- [bits rest=bits]
=| bs=bits
|-
?: =(n 0) [bs s]
=^ b s (read-bit s)
2021-01-11 15:08:05 +03:00
$(n (dec n), bs (write-bits bs [1 b]))
2021-01-11 13:12:14 +03:00
::
2021-01-11 15:08:05 +03:00
++ write-bits
|= [s1=bits s2=bits]
2021-01-11 12:27:40 +03:00
^- bits
2021-01-11 15:08:05 +03:00
[(add wid.s1 wid.s2) (can 0 ~[s2 s1])]
2021-01-11 12:27:40 +03:00
--
:: +gol: Golomb-Rice encoding/decoding
::
++ gol
|%
2021-01-11 15:08:05 +03:00
:: +en: encode x and append to end of s
::
2021-01-11 12:27:40 +03:00
++ en
2021-01-11 15:08:05 +03:00
|= [s=bits x=@ p=@]
^- bits
=+ q=(rsh [0 p] x)
=+ unary=[+(q) (lsh [0 1] (dec (bex q)))]
=+ r=[p (end [0 p] x)]
%+ write-bits:str s
(write-bits:str unary r)
2021-01-11 12:27:40 +03:00
::
++ de
2021-01-11 13:12:14 +03:00
|= [s=bits p=@]
^- [delta=@ rest=bits]
2021-01-11 15:08:05 +03:00
|^ ?> (gth wid.s 0)
2021-01-11 13:12:14 +03:00
=^ q s (get-q s)
=^ r s (read-bits:str p s)
[(add dat.r (lsh [0 p] q)) s]
::
++ get-q
|= s=bits
=| q=@
=^ first-bit s (read-bit:str s)
|-
?: =(0 first-bit) [q s]
=^ b s (read-bit:str s)
$(first-bit b, q +(q))
--
2021-01-11 12:27:40 +03:00
--
--