std:Word

lib/Word.omg

lib/Word.omg62 lines
1-- Native finite words. Widths are ordinary Natural indices, so a function
2-- can work at any width and the type checker prevents mixing widths.
3let Word8 = Word 8
4
5let Word64 = Word 64
6
7let Word256 = Word 256
8
9let zero : forall {bits : Natural} -> Word bits = \{bits} -> Word/fromNatural bits 0
10
11let one : forall {bits : Natural} -> Word bits = \{bits} -> Word/fromNatural bits 1
12
13-- Resize by keeping the low bits; widening zero-extends.
14let resize
15    : forall {from : Natural} (bits : Natural) -> Word from -> Word bits
16    = \{from} (bits : Natural) (x : Word from) -> Word/fromNatural bits (Word/toNatural x)
17
18-- Sign extension when widening, truncation when narrowing.
19let resizeSigned
20    : forall {from : Natural} (bits : Natural) -> Word from -> Word bits
21    = \{from} (bits : Natural) (x : Word from) -> Word/fromInteger bits (Word/toInteger x)
22
23-- The policy fixes the result type before either operand is supplied.
24-- A wrapping operation ignores its guard; a checked one cannot return a
25-- wrapped value as a success. Neither interpretation knows about contracts.
26let Policy = exists (F : Type -> Type) * forall (A : Type) -> Bool -> A -> F A
27let wrapping : Policy = (\(A : Type) -> A, \A fits value -> value)
28let checked : Policy = (Optional, \A fits value -> if fits then Some value else None A)
29
30-- Does x*y fit within a caller's remaining room? Test by division rather
31-- than multiplying first: the mathematical product may not fit in a word.
32let productFits =
33      \{bits : Natural} (room x y : Word bits) ->
34        Word/isZero x || std:Bool.not (Word/lt (Word/div room x) y)
35let arithmetic =
36      \(policy : Policy) (bits : Natural) ->
37        let U = Word bits
38        let finish = policy.2 U
39        let maximum = Word/not (Word/fromNatural bits 0)
40        in  { add =
41                \(x y : U) -> let sum = Word/add x y in finish (std:Bool.not (Word/lt sum x)) sum
42            , sub = \(x y : U) -> finish (std:Bool.not (Word/lt x y)) (Word/sub x y)
43            , mul = \(x y : U) -> finish (productFits @bits maximum x y) (Word/mul x y)
44            , addProduct =
45                \(base x y : U) ->
46                  finish
47                    (productFits @bits (Word/sub maximum base) x y)
48                    (Word/add base (Word/mul x y))
49            }
50in  { Word8
51    , Word64
52    , Word256
53    , zero
54    , one
55    , resize
56    , resizeSigned
57    , Policy
58    , checked
59    , wrapping
60    , arithmetic
61    , productFits
62    }
Your result
Complete file: lib/Word.omg · with imports