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
use crate::scenario_format::{
    interpret_trait::{InterpretableFrom, InterpreterContext, IntoRaw},
    serde_raw::ValueSubTree,
    value_interpreter::{interpret_string, interpret_subtree},
};

use num_bigint::BigUint;
use std::fmt;

#[derive(Debug, Clone)]
pub struct BigUintValue {
    pub value: BigUint,
    pub original: ValueSubTree,
}

impl InterpretableFrom<ValueSubTree> for BigUintValue {
    fn interpret_from(from: ValueSubTree, context: &InterpreterContext) -> Self {
        let bytes = interpret_subtree(&from, context);
        BigUintValue {
            value: BigUint::from_bytes_be(&bytes),
            original: from,
        }
    }
}

impl InterpretableFrom<&str> for BigUintValue {
    fn interpret_from(from: &str, context: &InterpreterContext) -> Self {
        let bytes = interpret_string(from, context);
        BigUintValue {
            value: BigUint::from_bytes_be(&bytes),
            original: ValueSubTree::Str(from.to_string()),
        }
    }
}

impl IntoRaw<ValueSubTree> for BigUintValue {
    fn into_raw(self) -> ValueSubTree {
        self.original
    }
}

impl BigUintValue {
    pub fn into_raw_opt(self) -> Option<ValueSubTree> {
        if self.value == 0u32.into() {
            None
        } else {
            Some(self.into_raw())
        }
    }
}

impl From<u32> for BigUintValue {
    fn from(from: u32) -> Self {
        BigUintValue {
            value: from.into(),
            original: ValueSubTree::Str(from.to_string()),
        }
    }
}

impl From<u64> for BigUintValue {
    fn from(from: u64) -> Self {
        BigUintValue {
            value: from.into(),
            original: ValueSubTree::Str(from.to_string()),
        }
    }
}

impl From<&str> for BigUintValue {
    fn from(from: &str) -> Self {
        BigUintValue::interpret_from(from, &InterpreterContext::default())
    }
}

impl fmt::Display for BigUintValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.original.fmt(f)
    }
}

impl Default for BigUintValue {
    fn default() -> Self {
        BigUintValue {
            original: ValueSubTree::default(),
            value: BigUint::from(0u32),
        }
    }
}