import Base
import ./u64.bend as U
# A decoder over a stream of 32-bit words, used for snapshots. Dec reads
# an A from the front of the stream and hands back the rest, or fails (None).
# Like Op, its bind needs no recursion, so `do Dec:` blocks pass Bend's
# termination check; loops take a Nat count.
type Dec<-A: Type> is Type:
Dec{run: +List -> Maybe<&1, A & +List>}
def Dec.pure(-A: Type, x: A) -> Dec:
Dec{ws => Some{(x, ws)}}
def Dec.fail(-A: Type) -> Dec:
Dec{ws => None{}}
def Dec.run(-A: Type, d: Dec, ws: +List) -> Maybe<&1, A & +List>:
match d:
case Dec{r}:
r(ws)
def Dec.bind.got(-A: Type, -B: Type, r: Maybe<&1, A & +List>, f: A -> Dec) -> Maybe<&1, B & +List>:
match r:
case None{}:
None{}
case Some{(x, rest)}:
Dec.run(B, f(x), rest)
def Dec.bind(-A: Type, -B: Type, m: Dec, f: A -> Dec) -> Dec:
Dec{ws => Dec.bind.got(A, B, Dec.run(A, m, ws), f)}
def Dec.u32.go(ws: +List) -> Maybe<&1, U32 & +List>:
match ws:
case Nil{}:
None{}
case Con{w, rest}:
Some{(w, rest)}
def Dec.u32() -> Dec:
Dec{ws => Dec.u32.go(ws)}
def Dec.u64() -> Dec:
do Dec:
h : U32 <- Dec.u32()
l : U32 <- Dec.u32()
return U.U64{h, l}
def Dec.bool.of(w: U32) -> Dec:
Dec.pure(Bool, U32.is_ne(w, 0))
def Dec.bool() -> Dec:
do Dec:
w : U32 <- Dec.u32()
Dec.bool.of(w)
# n words.
def Dec.words(n: Nat) -> Dec<+List>:
match n:
case 0n:
Dec.pure(+List, [])
case 1n+p:
do Dec<+List>:
w : U32 <- Dec.u32()
ws : +List <- Dec.words(p)
return w <> ws
# A length-prefixed list of words (bytes, in practice).
def Dec.bytes() -> Dec<+List>:
do Dec<+List>:
n : U32 <- Dec.u32()
Dec.words(U32.to_nat(n))
def Dec.chars(n: Nat) -> Dec:
match n:
case 0n:
Dec.pure(String, "")
case 1n+p:
do Dec:
c : U32 <- Dec.u32()
s : String <- Dec.chars(p)
return SCon{Char.from_u32(c), s}
# A length-prefixed string of character codes.
def Dec.string() -> Dec:
do Dec:
n : U32 <- Dec.u32()
Dec.chars(U32.to_nat(n))
# Encoders, the inverses: words in the same order.
def Enc.u64(a: U.U64) -> +List:
match a:
case U.U64{h, l}:
[h, l]
def Enc.bool(b: Bool) -> +List:
[Bool.to_u32(b)]
def Enc.bytes(+bs: +List) -> +List:
U32.from_nat(List.length(&2, U32, bs)) <> bs
def Enc.chars(s: String) -> +List:
match s:
case SNil{}:
[]
case SCon{c, rest}:
Char.to_u32(c) <> Enc.chars(rest)
def Enc.string(+s: String) -> +List:
U32.from_nat(String.length(s)) <> Enc.chars(s)