src/body.bend
emerging-ezhttp@0.21.0.0 · 68 lines · 11 definitions
1
2
3
4
5import Base
6import bend-kit-bytes@0.3.2.0/bytes.bend as Bytes
7
8
9type Body is Type:
10 Empty{}
11 Plain{text: String}
12 Octets{bytes: Bytes.Bytes}
13
14
15
16type Shape is Data:
17 ShapeText{text: String}
18 ShapeOctets{n: U32}
19
20
21def body.sized(r: Bytes.Bytes & U32) -> Shape & Bytes.Bytes:
22 (b, +n) = r
23 (ShapeOctets{n}, b)
24
25
26
27def body.shape(b: Body) -> Shape & Bytes.Bytes:
28 match b:
29 case Empty{}:
30 (ShapeText{""}, Bytes.new(0))
31 case Plain{text}:
32 (ShapeText{text}, Bytes.new(0))
33 case Octets{bytes}:
34 body.sized(Bytes.length(bytes))
35
36
37def octets.chars(bs: List<&2, U32>) -> String:
38 match bs:
39 case []:
40 ""
41 case h <> t:
42 SCon{Char.from_u32(h), octets.chars(t)}
43
44
45def body.empty() -> Body:
46 Empty{}
47
48
49def body.text(s: String) -> Body:
50 Plain{s}
51
52
53def body.octets(bytes: Bytes.Bytes) -> Body:
54 Octets{bytes}
55
56
57
58def body.list(bs: List<&2, U32>) -> Body:
59 Octets{Bytes.from_string(octets.chars(bs))}
60
61
62def body.encode(~A: Data, ~to_text: A -> String, value: A) -> Body:
63 Plain{to_text(value)}
64
65
66def body.decode(~A: Data, ~from_text: String -> Maybe<&2, A>, s: String)
67 -> Maybe<&2, A>:
68 from_text(s)