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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
use crate::allocator::{Allocator, NodePtr};
use crate::reduction::EvalErr;

use num_bigint::BigInt;
pub type Number = BigInt;

// This low-level conversion function is meant to be used by the Allocator, for
// logic interacting with the KLVM heap/allocator, use new_number() and number()
// instead.
pub fn node_from_number(allocator: &mut Allocator, item: &Number) -> Result<NodePtr, EvalErr> {
    let bytes: Vec<u8> = item.to_signed_bytes_be();
    let mut slice = bytes.as_slice();

    // make number minimal by removing leading zeros
    while (!slice.is_empty()) && (slice[0] == 0) {
        if slice.len() > 1 && (slice[1] & 0x80 == 0x80) {
            break;
        }
        slice = &slice[1..];
    }
    allocator.new_atom(slice)
}

// This low-level conversion function is meant to be used by the Allocator, for
// logic interacting with the KLVM heap/allocator, use new_number() and number()
// instead.
pub fn number_from_u8(v: &[u8]) -> Number {
    let len = v.len();
    if len == 0 {
        0.into()
    } else {
        Number::from_signed_bytes_be(v)
    }
}

#[test]
fn test_node_from_number() {
    let mut a = Allocator::new();

    // 0 is encoded as an empty string
    let num = number_from_u8(&[0]);
    let ptr = node_from_number(&mut a, &num).unwrap();
    assert_eq!(format!("{}", num), "0");
    assert_eq!(a.atom(ptr).len(), 0);

    let num = number_from_u8(&[1]);
    let ptr = node_from_number(&mut a, &num).unwrap();
    assert_eq!(format!("{}", num), "1");
    assert_eq!(&[1], &a.atom(ptr));

    // leading zeroes are redundant
    let num = number_from_u8(&[0, 0, 0, 1]);
    let ptr = node_from_number(&mut a, &num).unwrap();
    assert_eq!(format!("{}", num), "1");
    assert_eq!(&[1], &a.atom(ptr));

    let num = number_from_u8(&[0x00, 0x00, 0x80]);
    let ptr = node_from_number(&mut a, &num).unwrap();
    assert_eq!(format!("{}", num), "128");
    assert_eq!(&[0x00, 0x80], &a.atom(ptr));

    // A leading zero is necessary to encode a positive number with the
    // penultimate byte's most significant bit set
    let num = number_from_u8(&[0x00, 0xff]);
    let ptr = node_from_number(&mut a, &num).unwrap();
    assert_eq!(format!("{}", num), "255");
    assert_eq!(&[0x00, 0xff], &a.atom(ptr));

    let num = number_from_u8(&[0x7f, 0xff]);
    let ptr = node_from_number(&mut a, &num).unwrap();
    assert_eq!(format!("{}", num), "32767");
    assert_eq!(&[0x7f, 0xff], &a.atom(ptr));

    // the first byte is redundant, it's still -1
    let num = number_from_u8(&[0xff, 0xff]);
    let ptr = node_from_number(&mut a, &num).unwrap();
    assert_eq!(format!("{}", num), "-1");
    assert_eq!(&[0xff], &a.atom(ptr));

    let num = number_from_u8(&[0xff]);
    let ptr = node_from_number(&mut a, &num).unwrap();
    assert_eq!(format!("{}", num), "-1");
    assert_eq!(&[0xff], &a.atom(ptr));

    let num = number_from_u8(&[0x00, 0x80, 0x00]);
    assert_eq!(format!("{}", num), "32768");
    let ptr = node_from_number(&mut a, &num).unwrap();
    assert_eq!(&[0x00, 0x80, 0x00], &a.atom(ptr));

    let num = number_from_u8(&[0x00, 0x40, 0x00]);
    assert_eq!(format!("{}", num), "16384");
    let ptr = node_from_number(&mut a, &num).unwrap();
    assert_eq!(&[0x40, 0x00], &a.atom(ptr));
}

#[cfg(test)]
use num_bigint::{BigUint, Sign};

#[cfg(test)]
use std::convert::TryFrom;

#[cfg(test)]
fn roundtrip_bytes(b: &[u8]) {
    let negative = !b.is_empty() && (b[0] & 0x80) != 0;
    let zero = b.is_empty() || (b.len() == 1 && b[0] == 0);

    {
        let num = Number::from_signed_bytes_be(b);

        if negative {
            assert!(num.sign() == Sign::Minus);
        } else if zero {
            assert!(num.sign() == Sign::NoSign);
        } else {
            assert!(num.sign() == Sign::Plus);
        }

        let round_trip = num.to_signed_bytes_be();
        // num-bigin produces a single 0 byte for the value 0. We expect an
        // empty array
        let round_trip = if round_trip == [0] {
            &round_trip[1..]
        } else {
            &round_trip
        };

        assert_eq!(round_trip, b);

        // test to_bytes_le()
        let (sign, mut buf_le) = num.to_bytes_le();

        // there's a special case for empty input buffers, which will result in
        // a single 0 byte here
        if b.is_empty() {
            assert_eq!(buf_le, &[0]);
            buf_le.remove(0);
        }
        assert!(sign == num.sign());

        // the buffer we get from to_bytes_le() is unsigned (since the sign is
        // returned separately). This means it doesn't ever need to prepend a 0
        // byte when the MSB is set. When we're comparing this against the input
        // buffer, we need to add such 0 byte to buf_le to make them compare
        // equal.
        // the 0 prefix has to be added to the end though, since it's little
        // endian
        if !buf_le.is_empty() && (buf_le.last().unwrap() & 0x80) != 0 {
            buf_le.push(0);
        }

        if sign != Sign::Minus {
            assert!(buf_le.iter().eq(b.iter().rev()));
        } else {
            let negated = -num;
            let magnitude = negated.to_signed_bytes_be();
            assert!(buf_le.iter().eq(magnitude.iter().rev()));
        }
    }

    // test parsing unsigned bytes
    {
        let unsigned_num: Number = BigUint::from_bytes_be(b).into();
        assert!(unsigned_num.sign() != Sign::Minus);
        let unsigned_round_trip = unsigned_num.to_signed_bytes_be();
        let unsigned_round_trip = if unsigned_round_trip == [0] {
            &unsigned_round_trip[1..]
        } else {
            &unsigned_round_trip
        };
        if !b.is_empty() && (b[0] & 0x80) != 0 {
            // we expect a new leading zero here, to keep the value positive
            assert!(unsigned_round_trip[0] == 0);
            assert_eq!(&unsigned_round_trip[1..], b);
        } else {
            assert_eq!(unsigned_round_trip, b);
        }
    }
}

#[test]
fn test_number_round_trip_bytes() {
    roundtrip_bytes(&[]);

    for i in 1..=255 {
        roundtrip_bytes(&[i]);
    }

    for i in 0..=127 {
        roundtrip_bytes(&[0xff, i]);
    }

    for i in 128..=255 {
        roundtrip_bytes(&[0, i]);
    }

    for i in 0..=127 {
        roundtrip_bytes(&[
            0xff, i, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
        ]);
    }

    for i in 128..=255 {
        roundtrip_bytes(&[
            0, i, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
        ]);
    }

    for i in 0..=127 {
        roundtrip_bytes(&[0xff, i, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
    }

    for i in 128..=255 {
        roundtrip_bytes(&[0, i, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
    }
}

#[cfg(test)]
fn roundtrip_u64(v: u64) {
    let num: Number = v.into();
    assert!(num.sign() != Sign::Minus);

    assert!(num.bits() <= 64);

    let round_trip: u64 = TryFrom::try_from(num).unwrap();
    assert_eq!(round_trip, v);
}

#[test]
fn test_round_trip_u64() {
    for v in 0..=0x100 {
        roundtrip_u64(v);
    }

    for v in 0x7ffe..=0x8001 {
        roundtrip_u64(v);
    }

    for v in 0xfffe..=0x10000 {
        roundtrip_u64(v);
    }

    for v in 0x7ffffffe..=0x80000001 {
        roundtrip_u64(v);
    }
    for v in 0xfffffffe..=0x100000000 {
        roundtrip_u64(v);
    }

    for v in 0x7ffffffffffffffe..=0x8000000000000001 {
        roundtrip_u64(v);
    }

    for v in 0xfffffffffffffffe..=0xffffffffffffffff {
        roundtrip_u64(v);
    }
}

#[cfg(test)]
fn roundtrip_i64(v: i64) {
    use std::cmp::Ordering;

    let num: Number = v.into();

    match v.cmp(&0) {
        Ordering::Equal => assert!(num.sign() == Sign::NoSign),
        Ordering::Less => assert!(num.sign() == Sign::Minus),
        Ordering::Greater => assert!(num.sign() == Sign::Plus),
    }

    assert!(num.bits() <= 64);

    let round_trip: i64 = TryFrom::try_from(num).unwrap();
    assert_eq!(round_trip, v);
}

#[test]
fn test_round_trip_i64() {
    for v in -0x100..=0x100 {
        roundtrip_i64(v);
    }

    for v in 0x7ffe..=0x8001 {
        roundtrip_i64(v);
    }

    for v in -0x8001..-0x7ffe {
        roundtrip_i64(v);
    }

    for v in 0xfffe..=0x10000 {
        roundtrip_i64(v);
    }

    for v in -0x10000..-0xfffe {
        roundtrip_i64(v);
    }

    for v in 0x7ffffffe..=0x80000001 {
        roundtrip_i64(v);
    }

    for v in -0x80000001..-0x7ffffffe {
        roundtrip_i64(v);
    }

    for v in 0xfffffffe..=0x100000000 {
        roundtrip_i64(v);
    }

    for v in -0x100000000..-0xfffffffe {
        roundtrip_i64(v);
    }

    for v in 0x7ffffffffffffffe..=0x7fffffffffffffff {
        roundtrip_i64(v);
    }

    for v in -0x8000000000000000..-0x7ffffffffffffffe {
        roundtrip_i64(v);
    }
}

#[cfg(test)]
fn bits(b: &[u8]) -> u64 {
    Number::from_signed_bytes_be(b).bits()
}

#[test]
fn test_bits() {
    assert_eq!(bits(&[]), 0);
    assert_eq!(bits(&[0]), 0);
    assert_eq!(bits(&[0b01111111]), 7);
    assert_eq!(bits(&[0b00111111]), 6);
    assert_eq!(bits(&[0b00011111]), 5);
    assert_eq!(bits(&[0b00001111]), 4);
    assert_eq!(bits(&[0b00000111]), 3);
    assert_eq!(bits(&[0b00000011]), 2);
    assert_eq!(bits(&[0b00000001]), 1);
    assert_eq!(bits(&[0b00000000]), 0);

    assert_eq!(bits(&[0b01111111, 0xff]), 15);
    assert_eq!(bits(&[0b00111111, 0xff]), 14);
    assert_eq!(bits(&[0b00011111, 0xff]), 13);
    assert_eq!(bits(&[0b00001111, 0xff]), 12);
    assert_eq!(bits(&[0b00000111, 0xff]), 11);
    assert_eq!(bits(&[0b00000011, 0xff]), 10);
    assert_eq!(bits(&[0b00000001, 0xff]), 9);
    assert_eq!(bits(&[0b00000000, 0xff]), 8);

    assert_eq!(bits(&[0b11111111]), 1);
    assert_eq!(bits(&[0b11111110]), 2);
    assert_eq!(bits(&[0b11111100]), 3);
    assert_eq!(bits(&[0b11111000]), 4);
    assert_eq!(bits(&[0b11110000]), 5);
    assert_eq!(bits(&[0b11100000]), 6);
    assert_eq!(bits(&[0b11000000]), 7);
    assert_eq!(bits(&[0b10000000]), 8);

    assert_eq!(bits(&[0b11111111, 0]), 9);
    assert_eq!(bits(&[0b11111110, 0]), 10);
    assert_eq!(bits(&[0b11111100, 0]), 11);
    assert_eq!(bits(&[0b11111000, 0]), 12);
    assert_eq!(bits(&[0b11110000, 0]), 13);
    assert_eq!(bits(&[0b11100000, 0]), 14);
    assert_eq!(bits(&[0b11000000, 0]), 15);
    assert_eq!(bits(&[0b10000000, 0]), 16);
}