Skip to main content

whisky_common/data/primitives/
integer.rs

1use serde_json::{json, Value};
2
3use crate::{data::PlutusDataJson, WError};
4
5#[derive(Clone, Debug, PartialEq)]
6pub struct Int {
7    pub int: i128,
8}
9
10impl Int {
11    pub fn new(int: i128) -> Self {
12        Int { int }
13    }
14}
15
16impl PlutusDataJson for Int {
17    fn to_json(&self) -> Value {
18        integer(self.int)
19    }
20
21    fn from_json(value: &Value) -> Result<Self, WError> {
22        let int = value
23            .get("int")
24            .ok_or_else(|| WError::new("Int::from_json", "missing 'int' field"))?
25            .as_i64()
26            .map(|v| v as i128)
27            .or_else(|| {
28                // Try to parse as string for large numbers
29                value.get("int").and_then(|v| {
30                    v.as_str()
31                        .and_then(|s| s.parse::<i128>().ok())
32                        .or_else(|| v.as_u64().map(|u| u as i128))
33                })
34            })
35            .ok_or_else(|| WError::new("Int::from_json", "invalid 'int' value"))?;
36        Ok(Int { int })
37    }
38}
39
40pub fn integer(int: i128) -> Value {
41    json!({ "int": int })
42}
43
44pub fn posix_time(posix_time: i128) -> Value {
45    integer(posix_time)
46}