-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbytes.knot
More file actions
56 lines (44 loc) · 2.33 KB
/
Copy pathbytes.knot
File metadata and controls
56 lines (44 loc) · 2.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
-- ByteString example
with { raw (b"hello") } (do
-- Byte string literals
base.println (base.bytesLength raw) -- 5
-- Convert text -> bytes (always succeeds)
with { encoded (base.textToBytes "world") } (do
base.println (base.bytesLength encoded) -- 5
-- Convert bytes -> text — Maybe, returns Nothing on invalid UTF-8
case base.bytesToText encoded of
Maybe.Just { value t } -> base.println t -- world
Maybe.Nothing {} -> base.println "<invalid utf-8>"
-- Hex encoding always succeeds
with { hex (base.bytesToHex raw) } (do
base.println hex -- 68656c6c6f
-- Hex decoding is Maybe — returns Nothing on odd-length / non-hex input
case base.bytesFromHex hex of
Maybe.Just { value decoded } -> case base.bytesToText decoded of
Maybe.Just { value t } -> base.println t -- hello
Maybe.Nothing {} -> base.println "<invalid utf-8>"
Maybe.Nothing {} -> base.println "<invalid hex>"
-- Concatenation
with { combined (base.bytesConcat raw encoded) } (do
base.println (base.bytesLength combined) -- 10
-- Slicing
with { slice (base.bytesSlice 0 5 combined) } (do
case base.bytesToText slice of
Maybe.Just { value t } -> base.println t -- hello
Maybe.Nothing {} -> base.println "<invalid utf-8>"
-- Byte access is Maybe — Nothing when the index is out of bounds
case base.bytesGet 0 raw of
Maybe.Just { value byte } -> base.println byte -- 104 (ascii 'h')
Maybe.Nothing {} -> base.println "<out of bounds>"
case base.bytesGet 10 raw of
Maybe.Just { value byte } -> base.println byte
Maybe.Nothing {} -> base.println "<out of bounds>" -- raw has only 5 bytes
-- Hex escapes in literals
with { withHex (b"\x48\x49") } (do
case base.bytesToText withHex of
Maybe.Just { value t } -> base.println t -- HI
Maybe.Nothing {} -> base.println "<invalid utf-8>"
-- JSON encoding wraps bytes so they round-trip through parseJson.
base.println (base.toJson raw) -- {"__knot_bytes":"aGVsbG8="}
base.println (base.toJson { payload raw }) -- {"payload":{"__knot_bytes":"aGVsbG8="}}
yield {}))))))