aboutsummaryrefslogtreecommitdiff
path: root/elymas/lib/bin.ey
blob: 093e372441b6918ad85dd284e1e6279359f55c45 (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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# The idea of bin is to define manipulation routines for strings used
# as binary data structures

<
  {
    { 8 uw } /u64 deffd
    { 4 uw } /u32 deffd
    { 2 uw } /u16 deffd
    { 1 uw } /u8 deffd
    { 8 sw } /s64 deffd
    { 4 sw } /s32 deffd
    { 2 sw } /s16 deffd
    { 1 sw } /s8 deffd
    { 8 unw } /un64 deffd
    { 4 unw } /un32 deffd
    { 2 unw } /un16 deffd
    { 1 unw } /un8 deffd
    { 8 snw } /sn64 deffd
    { 4 snw } /sn32 deffd
    { 2 snw } /sn16 deffd
    { 1 snw } /sn8 deffd
  }" /defBitVariants deffd

  <
    # 0 -> number of bytes to combine into unsigned int
    # 1 -> string
    # 0 <- first w bytes of string interpreted as unsigned int
    # 1 <- string from (w+1)th byte onwards
    { ==w ==s
      w s str .postfix
      [ 0 w range s each ] 256 math .unbase
    } /uw deffst

    # network byte order (i.e. big endian)
    { ==w ==s
      w s str .postfix
      [ 0 w range reverse s each ] 256 math .unbase
    } /unw deffst

    # TODO: signed parsing missing

    defBitVariants
  > /scan defvd

  <
    # 0 -> number of bytes to produce
    # 1 -> int to convert to bytes
    # 0 <- string enlengthened by binary encoded integer
    { ==w ==i
      w str .alloc ==s
      0 w range { 0 -01 s =[] }" each
      i 256 math .base _ dom { -101*0 s =[] }" each --
      s
    } /uw deffst

    # network byte order (i.e. big endian)
    { ==w ==i
      w str .alloc ==s
      0 w range { 0 -01 s =[] }" each
      i 256 math .base _ dom { -101*0 w 1 sub -01 sub s =[] }" each --
      s
    } /unw deffst

    # signed integers
    { ==w _ 0 lt { 1 w { 256 mul } rep add } rep
            w
    } _ |uw  ; /sw deffst
        |unw ; /snw deffst
    
    defBitVariants
  > /produce defvd

  <
    { produce .uw cat } /uw deffst
    { produce .unw cat } /unw deffst
    { produce .sw cat } /sw deffst
    { produce .snw cat } /snw deffst
    defBitVariants
  > /print defvd
> /bin defvd

# vim: syn=elymas