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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
use num::BigInt;
use std::cmp::Ordering;
#[allow(non_camel_case_types)]
#[derive(Copy, Clone, Default, Eq, PartialEq, Hash)]
pub struct i256 {
low: u128,
high: i128,
}
impl std::fmt::Debug for i256 {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self)
}
}
impl std::fmt::Display for i256 {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", BigInt::from_signed_bytes_le(&self.to_le_bytes()))
}
}
impl PartialOrd for i256 {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for i256 {
fn cmp(&self, other: &Self) -> Ordering {
self.high.cmp(&other.high).then(self.low.cmp(&other.low))
}
}
impl i256 {
pub const ZERO: Self = i256 { low: 0, high: 0 };
pub const ONE: Self = i256 { low: 1, high: 0 };
pub const MINUS_ONE: Self = i256 {
low: u128::MAX,
high: -1,
};
pub const MAX: Self = i256 {
low: u128::MAX,
high: i128::MAX,
};
pub const MIN: Self = i256 {
low: u128::MIN,
high: i128::MIN,
};
#[inline]
pub fn from_le_bytes(b: [u8; 32]) -> Self {
Self {
high: i128::from_le_bytes(b[16..32].try_into().unwrap()),
low: u128::from_le_bytes(b[0..16].try_into().unwrap()),
}
}
pub fn from_i128(v: i128) -> Self {
let mut bytes = if num::Signed::is_negative(&v) {
[255_u8; 32]
} else {
[0; 32]
};
bytes[0..16].copy_from_slice(&v.to_le_bytes());
Self::from_le_bytes(bytes)
}
#[inline]
pub fn from_parts(low: u128, high: i128) -> Self {
Self { low, high }
}
pub fn to_parts(self) -> (u128, i128) {
(self.low, self.high)
}
pub fn to_i128(self) -> Option<i128> {
let as_i128 = self.low as i128;
let high_negative = self.high < 0;
let low_negative = as_i128 < 0;
let high_valid = self.high == -1 || self.high == 0;
(high_negative == low_negative && high_valid).then_some(self.low as i128)
}
#[inline]
pub fn to_le_bytes(self) -> [u8; 32] {
let mut t = [0; 32];
let t_low: &mut [u8; 16] = (&mut t[0..16]).try_into().unwrap();
*t_low = self.low.to_le_bytes();
let t_high: &mut [u8; 16] = (&mut t[16..32]).try_into().unwrap();
*t_high = self.high.to_le_bytes();
t
}
fn from_bigint_with_overflow(v: BigInt) -> (Self, bool) {
let v_bytes = v.to_signed_bytes_le();
match v_bytes.len().cmp(&32) {
Ordering::Less => {
let mut bytes = if num::Signed::is_negative(&v) {
[255_u8; 32]
} else {
[0; 32]
};
bytes[0..v_bytes.len()].copy_from_slice(&v_bytes[..v_bytes.len()]);
(Self::from_le_bytes(bytes), false)
}
Ordering::Equal => (Self::from_le_bytes(v_bytes.try_into().unwrap()), false),
Ordering::Greater => {
(Self::from_le_bytes(v_bytes[..32].try_into().unwrap()), true)
}
}
}
#[inline]
pub fn wrapping_abs(self) -> Self {
let sa = self.high >> 127;
let sa = Self::from_parts(sa as u128, sa);
Self::from_parts(self.low ^ sa.low, self.high ^ sa.high).wrapping_sub(sa)
}
#[inline]
pub fn checked_abs(self) -> Option<Self> {
(self != Self::MIN).then(|| self.wrapping_abs())
}
#[inline]
pub fn wrapping_add(self, other: Self) -> Self {
let (low, carry) = self.low.overflowing_add(other.low);
let high = self.high.wrapping_add(other.high).wrapping_add(carry as _);
Self { low, high }
}
#[inline]
pub fn checked_add(self, other: Self) -> Option<Self> {
let (low, carry) = self.low.overflowing_add(other.low);
let high = self.high.checked_add(other.high)?.checked_add(carry as _)?;
Some(Self { low, high })
}
#[inline]
pub fn wrapping_sub(self, other: Self) -> Self {
let (low, carry) = self.low.overflowing_sub(other.low);
let high = self.high.wrapping_sub(other.high).wrapping_sub(carry as _);
Self { low, high }
}
#[inline]
pub fn checked_sub(self, other: Self) -> Option<Self> {
let (low, carry) = self.low.overflowing_sub(other.low);
let high = self.high.checked_sub(other.high)?.checked_sub(carry as _)?;
Some(Self { low, high })
}
#[inline]
pub fn wrapping_mul(self, other: Self) -> Self {
let (low, high) = mulx(self.low, other.low);
let hl = self.high.wrapping_mul(other.low as i128);
let lh = (self.low as i128).wrapping_mul(other.high);
Self {
low,
high: (high as i128).wrapping_add(hl).wrapping_add(lh),
}
}
#[inline]
pub fn checked_mul(self, other: Self) -> Option<Self> {
let l_sa = self.high >> 127;
let r_sa = other.high >> 127;
let out_sa = l_sa ^ r_sa;
let l_abs = self.wrapping_abs();
let r_abs = other.wrapping_abs();
if l_abs.high != 0 && r_abs.high != 0 {
return None;
}
let (low, high) = mulx(l_abs.low, r_abs.low);
let hl = (l_abs.high as u128).checked_mul(r_abs.low)?;
let lh = l_abs.low.checked_mul(r_abs.high as u128)?;
let high: i128 = high.checked_add(hl)?.checked_add(lh)?.try_into().ok()?;
let (low, c) = (low ^ out_sa as u128).overflowing_sub(out_sa as u128);
let high = (high ^ out_sa).wrapping_sub(out_sa).wrapping_sub(c as i128);
Some(Self { low, high })
}
#[inline]
pub fn wrapping_div(self, other: Self) -> Self {
let l = BigInt::from_signed_bytes_le(&self.to_le_bytes());
let r = BigInt::from_signed_bytes_le(&other.to_le_bytes());
Self::from_bigint_with_overflow(l / r).0
}
#[inline]
pub fn checked_div(self, other: Self) -> Option<Self> {
let l = BigInt::from_signed_bytes_le(&self.to_le_bytes());
let r = BigInt::from_signed_bytes_le(&other.to_le_bytes());
let (val, overflow) = Self::from_bigint_with_overflow(l / r);
(!overflow).then_some(val)
}
#[inline]
pub fn wrapping_rem(self, other: Self) -> Self {
let l = BigInt::from_signed_bytes_le(&self.to_le_bytes());
let r = BigInt::from_signed_bytes_le(&other.to_le_bytes());
Self::from_bigint_with_overflow(l % r).0
}
#[inline]
pub fn checked_rem(self, other: Self) -> Option<Self> {
if other == Self::ZERO {
return None;
}
let l = BigInt::from_signed_bytes_le(&self.to_le_bytes());
let r = BigInt::from_signed_bytes_le(&other.to_le_bytes());
let (val, overflow) = Self::from_bigint_with_overflow(l % r);
(!overflow).then_some(val)
}
}
#[inline]
fn mulx(a: u128, b: u128) -> (u128, u128) {
let split = |a: u128| (a & (u64::MAX as u128), a >> 64);
const MASK: u128 = u64::MAX as _;
let (a_low, a_high) = split(a);
let (b_low, b_high) = split(b);
let (mut low, mut carry) = split(a_low * b_low);
carry += a_high * b_low;
low += carry << 64;
let mut high = carry >> 64;
carry = low >> 64;
low &= MASK;
carry += b_high * a_low;
low += carry << 64;
high += carry >> 64;
high += a_high * b_high;
(low, high)
}
#[cfg(test)]
mod tests {
use super::*;
use num::{BigInt, FromPrimitive, Signed, ToPrimitive};
use rand::{thread_rng, Rng};
#[test]
fn test_signed_cmp() {
let a = i256::from_parts(i128::MAX as u128, 12);
let b = i256::from_parts(i128::MIN as u128, 12);
assert!(a < b);
let a = i256::from_parts(i128::MAX as u128, 12);
let b = i256::from_parts(i128::MIN as u128, -12);
assert!(a > b);
}
#[test]
fn test_to_i128() {
let vals = [
BigInt::from_i128(-1).unwrap(),
BigInt::from_i128(i128::MAX).unwrap(),
BigInt::from_i128(i128::MIN).unwrap(),
BigInt::from_u128(u128::MIN).unwrap(),
BigInt::from_u128(u128::MAX).unwrap(),
];
for v in vals {
let (t, overflow) = i256::from_bigint_with_overflow(v.clone());
assert!(!overflow);
assert_eq!(t.to_i128(), v.to_i128(), "{} vs {}", v, t);
}
}
fn test_ops(il: i256, ir: i256) {
let bl = BigInt::from_signed_bytes_le(&il.to_le_bytes());
let br = BigInt::from_signed_bytes_le(&ir.to_le_bytes());
assert_eq!(il.cmp(&ir), bl.cmp(&br), "{} cmp {}", bl, br);
assert_eq!(il.to_i128(), bl.to_i128(), "{}", bl);
assert_eq!(ir.to_i128(), br.to_i128(), "{}", br);
let (abs, overflow) = i256::from_bigint_with_overflow(bl.abs());
assert_eq!(il.wrapping_abs(), abs);
assert_eq!(il.checked_abs().is_none(), overflow);
let (abs, overflow) = i256::from_bigint_with_overflow(br.abs());
assert_eq!(ir.wrapping_abs(), abs);
assert_eq!(ir.checked_abs().is_none(), overflow);
let actual = il.wrapping_add(ir);
let (expected, overflow) =
i256::from_bigint_with_overflow(bl.clone() + br.clone());
assert_eq!(actual, expected);
let checked = il.checked_add(ir);
match overflow {
true => assert!(checked.is_none()),
false => assert_eq!(checked.unwrap(), actual),
}
let actual = il.wrapping_sub(ir);
let (expected, overflow) =
i256::from_bigint_with_overflow(bl.clone() - br.clone());
assert_eq!(actual.to_string(), expected.to_string());
let checked = il.checked_sub(ir);
match overflow {
true => assert!(checked.is_none()),
false => assert_eq!(checked.unwrap(), actual),
}
let actual = il.wrapping_mul(ir);
let (expected, overflow) =
i256::from_bigint_with_overflow(bl.clone() * br.clone());
assert_eq!(actual.to_string(), expected.to_string());
let checked = il.checked_mul(ir);
match overflow {
true => assert!(
checked.is_none(),
"{} * {} = {} vs {} * {} = {}",
il,
ir,
actual,
bl,
br,
expected
),
false => assert_eq!(
checked.unwrap(),
actual,
"{} * {} = {} vs {} * {} = {}",
il,
ir,
actual,
bl,
br,
expected
),
}
}
#[test]
fn test_i256() {
let candidates = [
i256::from_parts(0, 0),
i256::from_parts(0, 1),
i256::from_parts(0, -1),
i256::from_parts(u128::MAX, 1),
i256::from_parts(u128::MAX, -1),
i256::from_parts(0, 1),
i256::from_parts(0, -1),
i256::from_parts(100, 32),
];
for il in candidates {
for ir in candidates {
test_ops(il, ir)
}
}
}
#[test]
#[cfg_attr(miri, ignore)]
fn test_i256_fuzz() {
let mut rng = thread_rng();
for _ in 0..1000 {
let mut l = [0_u8; 32];
let len = rng.gen_range(0..32);
l.iter_mut().take(len).for_each(|x| *x = rng.gen());
let mut r = [0_u8; 32];
let len = rng.gen_range(0..32);
r.iter_mut().take(len).for_each(|x| *x = rng.gen());
test_ops(i256::from_le_bytes(l), i256::from_le_bytes(r))
}
}
}