Skip to main content

whisky_common/data/primitives/
list.rs

1use serde_json::{json, Value};
2
3use crate::{data::PlutusDataJson, WError};
4
5#[derive(Clone, Debug, PartialEq)]
6pub struct List<T>
7where
8    T: Clone + PlutusDataJson,
9{
10    pub items: Vec<T>,
11}
12
13impl<T> List<T>
14where
15    T: Clone + PlutusDataJson,
16{
17    pub fn new(items: &[T]) -> Self {
18        List {
19            items: items.to_vec(),
20        }
21    }
22}
23
24impl<T> PlutusDataJson for List<T>
25where
26    T: Clone + PlutusDataJson,
27{
28    fn to_json(&self) -> Value {
29        let items_json = self
30            .items
31            .iter()
32            .map(|item| item.to_json())
33            .collect::<Vec<Value>>();
34        list(items_json)
35    }
36
37    fn from_json(value: &Value) -> Result<Self, WError> {
38        let items_json = value
39            .get("list")
40            .ok_or_else(|| WError::new("List::from_json", "missing 'list' field"))?
41            .as_array()
42            .ok_or_else(|| WError::new("List::from_json", "invalid 'list' value"))?;
43
44        let items = items_json
45            .iter()
46            .enumerate()
47            .map(|(i, item)| {
48                T::from_json(item).map_err(WError::add_err_trace(
49                    Box::leak(format!("List::from_json[{}]", i).into_boxed_str())
50                ))
51            })
52            .collect::<Result<Vec<T>, WError>>()?;
53
54        Ok(List { items })
55    }
56}
57
58pub fn list<T: Into<Value>>(p_list: Vec<T>) -> Value {
59    let list: Vec<Value> = p_list.into_iter().map(|item| item.into()).collect();
60    json!({ "list": list })
61}