sputnikvm_bigint/
lib.rs

1mod algorithms;
2extern crate sputnikvm_rlp as rlp;
3
4mod m256;
5mod mi256;
6mod u256;
7mod u512;
8
9pub use self::m256::M256;
10pub use self::u256::U256;
11pub use self::mi256::MI256;
12pub use self::u512::U512;
13
14#[derive(Eq, PartialEq, Debug, Copy, Clone, Hash)]
15/// Sign of an integer.
16pub enum Sign {
17    Minus,
18    NoSign,
19    Plus,
20}
21
22#[derive(Debug)]
23/// Errors exhibited from `read_hex`.
24pub enum ParseHexError {
25    InvalidCharacter,
26    TooLong,
27    TooShort,
28    Other
29}
30
31/// Parses a given hex string and return a list of bytes if
32/// succeeded. The string can optionally start by `0x`, which
33/// indicates that it is a hex representation.
34pub fn read_hex(s: &str) -> Result<Vec<u8>, ParseHexError> {
35    if s.starts_with("0x") {
36        return read_hex(&s[2..s.len()]);
37    }
38
39    if s.len() & 1 == 1 {
40        let mut new_s = "0".to_string();
41        new_s.push_str(s);
42        return read_hex(&new_s);
43    }
44
45    let mut res = Vec::<u8>::new();
46
47    let mut cur = 0;
48    let mut len = 0;
49    for c in s.chars() {
50        len += 1;
51        let v_option = c.to_digit(16);
52        if v_option.is_none() {
53            return Err(ParseHexError::InvalidCharacter);
54        }
55        let v = v_option.unwrap();
56        if len == 1 {
57            cur += v * 16;
58        } else { // len == 2
59            cur += v;
60        }
61        if len == 2 {
62            res.push(cur as u8);
63            cur = 0;
64            len = 0;
65        }
66    }
67
68    return Ok(res);
69}