aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/lux/host/jvm/encoding.lux
blob: 08213e26895e8c0f4bea8b659347fe410a86610d (plain)
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
(.module:
  [lux #*
   [control
    [equivalence (#+ Equivalence)]
    ["." parser ("#;." functor)]]
   [data
    [number
     ["." i64]]
    [format
     ["." binary (#+ Format)]]]
   [type
    abstract]])

(do-template [<bytes> <name> <size> <to> <from> <equivalence>]
  [(abstract: #export <name>
     {}

     (I64 Any)

     (def: #export <size> Nat <bytes>)

     (def: #export <to>
       (-> (I64 Any) <name>)
       (let [mask (|> <bytes>
                      (n/* i64.bits-per-byte)
                      i64.mask)]
         (|>> (i64.and mask) :abstraction)))

     (def: #export <from>
       (-> <name> (I64 Any))
       (|>> :representation))

     (structure: #export <equivalence> (Equivalence <name>)
       (def: (= reference sample)
         ("lux i64 =" (:representation reference) (:representation sample))))
     )]

  [1 U1 u1-bytes to-u1 from-u1 u1-equivalence]
  [2 U2 u2-bytes to-u2 from-u2 u2-equivalence]
  [4 U4 u4-bytes to-u4 from-u4 u4-equivalence]
  )

(do-template [<name> <type> <format> <pre-write> <post-read>]
  [(def: #export <name>
     (Format <type>)
     (binary.adapt <post-read> <pre-write> <format>))]

  [u1-format U1 binary.bits/8  ..from-u1 ..to-u1]
  [u2-format U2 binary.bits/16 ..from-u2 ..to-u2]
  [u4-format U4 binary.bits/32 ..from-u4 ..to-u4]
  )