aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/lux/data/bit.lux
blob: b0b31d2ddc85124c7245dc74bed822780ee32b0e (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
(;module: [lux #- and or not])

(def: #export width Nat +64)

## [Values]
(do-template [<short-name> <op> <doc> <type>]
  [(def: #export (<short-name> param subject)
     {#;doc <doc>}
     (-> Nat <type> <type>)
     (<op> subject param))]

  [and "lux bit and" "Bitwise and." Nat]
  [or "lux bit or" "Bitwise or." Nat]
  [xor "lux bit xor" "Bitwise xor." Nat]
  [shift-left "lux bit shift-left" "Bitwise shift-left." Nat]
  [shift-right "lux bit unsigned-shift-right" "Unsigned bitwise shift-right." Nat]
  [signed-shift-right "lux bit shift-right" "Signed bitwise shift-right." Int]
  )

(def: #export (count subject)
  {#;doc "Count the number of 1s in a bit-map."}
  (-> Nat Nat)
  ("lux bit count" subject))

(def: #export not
  {#;doc "Bitwise negation."}
  (-> Nat Nat)
  (let [mask (int-to-nat -1)]
    (xor mask)))

(def: #export (clear idx input)
  {#;doc "Clear bit at given index."}
  (-> Nat Nat Nat)
  (;;and (;;not (shift-left idx +1))
         input))

(do-template [<name> <op> <doc>]
  [(def: #export (<name> idx input)
     {#;doc <doc>}
     (-> Nat Nat Nat)
     (<op> (shift-left idx +1) input))]

  [set  ;;or  "Set bit at given index."]
  [flip ;;xor "Flip bit at given index."]
  )

(def: #export (set? idx input)
  (-> Nat Nat Bool)
  (|> input (;;and (shift-left idx +1)) (n/= +0) ;not))

(do-template [<name> <main> <comp>]
  [(def: #export (<name> distance input)
     (-> Nat Nat Nat)
     (;;or (<main> distance input)
           (<comp> (n/- (n/% width distance)
                        width)
                   input)))]

  [rotate-left  shift-left  shift-right]
  [rotate-right shift-right shift-left]
  )