af_utilities/types/
i256.rs

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
use std::cmp::Ordering;
use std::ops::{
    Add,
    AddAssign,
    Div,
    DivAssign,
    Mul,
    MulAssign,
    Neg,
    Rem,
    RemAssign,
    Sub,
    SubAssign,
};

use af_sui_types::u256::U256;
use num_traits::{One, Zero};
use serde::{Deserialize, Serialize};

use super::errors::Error;
use super::onchain;

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Deserialize, Serialize)]
pub struct I256(U256);

impl std::fmt::Display for I256 {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if self.is_neg() {
            write!(f, "-{}", self.uabs())
        } else {
            write!(f, "{}", self.0)
        }
    }
}

macro_rules! impl_from_uint {
    ($($int:ty)*) => {
        $(
            impl From<$int> for I256 {
                fn from(value: $int) -> Self {
                    Self(U256::from(value))
                }
            }
        )*
    };
}

impl_from_uint!(u8 u16 u32 u64 u128);

macro_rules! impl_from_int {
    ($($int:ty)*) => {
        $(
            impl From<$int> for I256 {
                fn from(value: $int) -> Self {
                    let is_neg = value.is_negative();
                    let abs = Self::from(value.unsigned_abs());
                    match is_neg {
                        true => abs.neg(),
                        false => abs,
                    }
                }
            }
        )*
    };
}

impl_from_int!(i8 i16 i32 i64 i128);

macro_rules! impl_try_into_int {
    ($($bridge:ty => $int:ty),*) => {
        $(
            impl TryFrom<I256> for $int {
                type Error = Error;

                fn try_from(value: I256) -> Result<Self, Self::Error> {
                    let is_neg = value.is_neg();
                    let bridge: $bridge = value.uabs().try_into().map_err(|_| Error::Overflow)?;
                    let self_: Self = bridge.try_into().map_err(|_| Error::Overflow)?;
                    Ok(match is_neg {
                        true => -self_,
                        false => self_,
                    })
                }
            }
        )*
    };
}

impl_try_into_int!(u8 => i8, u16 => i16, u32 => i32, u64 => i64, u128 => i128);

macro_rules! impl_try_into_uint {
    ($($int:ty)*) => {
        $(
            impl TryFrom<I256> for $int {
                type Error = Error;

                fn try_from(value: I256) -> Result<Self, Self::Error> {
                    if value.is_neg() {
                        return Err(Error::Underflow);
                    }
                    value.uabs().try_into().map_err(|_| Error::Overflow)
                }
            }
        )*
    };
}

impl_try_into_uint!(u8 u16 u32 u64 u128);

impl TryFrom<U256> for I256 {
    type Error = Error;

    fn try_from(value: U256) -> Result<Self, Self::Error> {
        if value <= onchain::max_i256() {
            Ok(Self(value))
        } else {
            Err(Error::Overflow)
        }
    }
}

impl TryFrom<I256> for U256 {
    type Error = Error;

    fn try_from(value: I256) -> Result<Self, Self::Error> {
        if value.is_neg() {
            return Err(Error::Underflow);
        }
        Ok(value.0)
    }
}

impl Add for I256 {
    type Output = Self;

    fn add(self, rhs: Self) -> Self::Output {
        let Self(x) = self;
        let Self(y) = rhs;
        let greatest_bit = Self::greatest_bit();
        let not_greatest_bit = Self::not_greatest_bit();

        // First, compute sum of x and y except the greatest bit.
        let w = (x & not_greatest_bit) + (y & not_greatest_bit);
        Self(if x ^ y < greatest_bit {
            // The signs of x and y are the same, so the result sign must also be the same
            // for no overflow.
            // assert!(x ^ w < greatest_bit, overflow_error);
            w
        } else {
            // Overflow cannot happen if the signs are different because sum will be closer
            // to 0 than an input.
            w ^ greatest_bit
        })
    }
}

impl Sub for I256 {
    type Output = Self;

    fn sub(self, rhs: Self) -> Self::Output {
        let Self(x) = self;
        let Self(y) = rhs;
        // First, compute wrapping difference of x and y.
        let w = if x >= y {
            x - y
        } else {
            ((y - x) ^ Self::neg_one().0) + U256::one()
        };
        // assert!(x ^ y < GREATEST_BIT || x ^ w < GREATEST_BIT, OVERFLOW_ERROR);
        Self(w)
    }
}

impl Mul for I256 {
    type Output = Self;

    fn mul(self, rhs: Self) -> Self::Output {
        let z = self.uabs() * rhs.uabs();
        let (Self(x), Self(y)) = (self, rhs);
        let greatest_bit = Self::greatest_bit();

        Self(if x ^ y < greatest_bit {
            // assert!(z < greatest_bit, overflow_error);
            z
        } else {
            // assert!(z <= greatest_bit, overflow_error);
            (greatest_bit - z) ^ greatest_bit
        })
    }
}

impl Div for I256 {
    type Output = Self;

    fn div(self, rhs: Self) -> Self::Output {
        let z = self.uabs() / rhs.uabs();
        let (Self(x), Self(y)) = (self, rhs);
        let greatest_bit = Self::greatest_bit();

        Self(if x ^ y < greatest_bit {
            // assert!(z < greatest_bit, overflow_error);
            z
        } else {
            (greatest_bit - z) ^ greatest_bit
        })
    }
}

impl Rem for I256 {
    type Output = Self;

    fn rem(self, rhs: Self) -> Self::Output {
        let is_neg = self.is_neg();
        let abs_rem = Self(self.uabs() % rhs.uabs());
        match is_neg {
            true => abs_rem.neg(),
            false => abs_rem,
        }
    }
}

super::reuse_op_for_assign!(I256 {
    AddAssign add_assign +,
    SubAssign sub_assign -,
    MulAssign mul_assign *,
    DivAssign div_assign /,
    RemAssign rem_assign %,
});

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 {
        let Self(x) = self;
        let Self(y) = other;

        if x == y {
            Ordering::Equal
        } else if *x ^ Self::greatest_bit() < *y ^ Self::greatest_bit() {
            Ordering::Less
        } else {
            Ordering::Greater
        }
    }
}

impl Neg for I256 {
    type Output = Self;

    fn neg(self) -> Self::Output {
        Self(((self.0 ^ Self::not_greatest_bit()) + U256::one()) ^ Self::greatest_bit())
    }
}

impl One for I256 {
    fn one() -> Self {
        Self::one()
    }
}

impl Zero for I256 {
    fn zero() -> Self {
        Self(U256::zero())
    }

    fn is_zero(&self) -> bool {
        self.0 == U256::zero()
    }
}

impl I256 {
    fn greatest_bit() -> U256 {
        U256::one() << 255_u8
    }

    fn not_greatest_bit() -> U256 {
        (U256::one() << 255_u8) - U256::one()
    }

    pub const fn neg_one() -> Self {
        Self(U256::max_value())
    }

    pub const fn into_inner(self) -> U256 {
        self.0
    }

    pub const fn from_inner(inner: U256) -> Self {
        Self(inner)
    }

    pub const fn one() -> Self {
        Self(U256::one())
    }

    pub const fn zero() -> Self {
        Self(U256::zero())
    }

    pub fn is_neg(&self) -> bool {
        self.0 >= Self::greatest_bit()
    }

    /// Absolute value of a number.
    /// Can be thought as function from i256 to u256, so doesn't abort.
    pub fn uabs(&self) -> U256 {
        let Self(x) = self;
        if *x >= Self::greatest_bit() {
            (*x ^ Self::neg_one().0) + U256::one()
        } else {
            *x
        }
    }

    pub fn abs(self) -> Self {
        let Self(x) = self;
        let greatest_bit = Self::greatest_bit();
        let not_greatest_bit = Self::not_greatest_bit();
        Self(if x >= greatest_bit {
            ((x ^ not_greatest_bit) + U256::one()) ^ greatest_bit
        } else {
            x
        })
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::*;

    #[test]
    fn from_u128_max_doesnt_overflow() {
        assert!(!I256::from(u128::MAX).is_neg())
    }

    #[test]
    fn from_i128_min_doesnt_underflow() {
        assert!(I256::from(i128::MIN).is_neg())
    }
}