sui_graphql_rpc/types/
big_int.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
// Copyright (c) Mysten Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

use std::str::FromStr;

use async_graphql::*;
use move_core_types::u256::U256;
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
#[serde(transparent)]
pub(crate) struct BigInt(String);

#[derive(thiserror::Error, Debug, PartialEq, Eq)]
#[error("The provided string is not a number")]
pub(crate) struct NotANumber;

#[Scalar(use_type_description = true)]
impl ScalarType for BigInt {
    fn parse(value: Value) -> InputValueResult<Self> {
        match value {
            Value::String(s) => BigInt::from_str(&s)
                .map_err(|_| InputValueError::custom("Not a number".to_string())),
            _ => Err(InputValueError::expected_type(value)),
        }
    }

    fn to_value(&self) -> Value {
        Value::String(self.0.clone())
    }
}

impl Description for BigInt {
    fn description() -> &'static str {
        "String representation of an arbitrary width, possibly signed integer."
    }
}

impl FromStr for BigInt {
    type Err = NotANumber;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut r = s;
        let mut signed = false;
        // check that all are digits and first can start with -
        if let Some(suffix) = s.strip_prefix('-') {
            r = suffix;
            signed = true;
        }
        r = r.trim_start_matches('0');

        if r.is_empty() {
            Ok(BigInt("0".to_string()))
        } else if r.chars().all(|c| c.is_ascii_digit()) {
            Ok(BigInt(format!("{}{}", if signed { "-" } else { "" }, r)))
        } else {
            Err(NotANumber)
        }
    }
}

macro_rules! impl_From {
    ($($t:ident),*) => {
        $(impl From<$t> for BigInt {
            fn from(value: $t) -> Self {
                BigInt(value.to_string())
            }
        })*
    }
}

impl_From!(u8, u16, u32, i64, u64, i128, u128, U256);

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

    #[test]
    fn from_value() {
        assert_eq!(BigInt::from_str("123").unwrap(), BigInt("123".to_string()));
        assert_eq!(
            BigInt::from_str("-123").unwrap(),
            BigInt("-123".to_string())
        );
        assert_eq!(
            BigInt::from_str("00233").unwrap(),
            BigInt("233".to_string())
        );
        assert_eq!(BigInt::from_str("0").unwrap(), BigInt("0".to_string()));
        assert_eq!(BigInt::from_str("-0").unwrap(), BigInt("0".to_string()));
        assert_eq!(BigInt::from_str("000").unwrap(), BigInt("0".to_string()));
        assert_eq!(BigInt::from_str("-000").unwrap(), BigInt("0".to_string()));

        assert!(BigInt::from_str("123a").is_err());
        assert!(BigInt::from_str("a123").is_err());
        assert!(BigInt::from_str("123-").is_err());
        assert!(BigInt::from_str(" 123").is_err());
    }

    #[test]
    fn from_primitives() {
        assert_eq!(BigInt::from(123u8), BigInt("123".to_string()));

        assert_eq!(BigInt::from(12_345u16), BigInt("12345".to_string()));

        assert_eq!(BigInt::from(123_456u32), BigInt("123456".to_string()));

        assert_eq!(
            BigInt::from(-12_345_678_901i64),
            BigInt("-12345678901".to_string()),
        );

        assert_eq!(
            BigInt::from(12_345_678_901u64),
            BigInt("12345678901".to_string()),
        );

        assert_eq!(
            BigInt::from(-123_456_789_012_345_678_901i128),
            BigInt("-123456789012345678901".to_string()),
        );

        assert_eq!(
            BigInt::from(123_456_789_012_345_678_901u128),
            BigInt("123456789012345678901".to_string()),
        );

        assert_eq!(
            BigInt::from(U256::from_str("12345678901234567890123456789012345678901").unwrap()),
            BigInt("12345678901234567890123456789012345678901".to_string())
        );

        assert_eq!(BigInt::from(1000i64 - 1200i64), BigInt("-200".to_string()));
        assert_eq!(BigInt::from(-1200i64), BigInt("-1200".to_string()));
    }
}