cosmic_space/config/
mechtron.rs

1use crate::point::Point;
2use crate::parse::mechtron_config;
3use crate::parse::model::MechtronScope;
4use crate::{Bin, SpaceErr};
5use core::str::FromStr;
6use serde::de::Unexpected::Option;
7use serde::{Deserialize, Serialize};
8
9#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
10pub struct MechtronConfig {
11    pub wasm: Point,
12    pub name: String,
13}
14
15impl MechtronConfig {
16    pub fn new(scopes: Vec<MechtronScope>) -> Result<Self, SpaceErr> {
17        let mut wasm = None;
18        let mut name = None;
19        for scope in scopes {
20            match scope {
21                MechtronScope::WasmScope(assigns) => {
22                    for assign in assigns {
23                        if assign.key.as_str() == "bin" {
24                            wasm.replace(Point::from_str(assign.value.as_str())?);
25                        } else if assign.key.as_str() == "name" {
26                            name.replace(assign.value);
27                        }
28                    }
29                }
30            }
31        }
32        if wasm.is_some() && name.is_some() {
33            Ok(Self {
34                wasm: wasm.unwrap(),
35                name: name.unwrap(),
36            })
37        } else {
38            Err("required `bin` and `name` in Wasm scope".into())
39        }
40    }
41}
42
43impl TryFrom<Vec<u8>> for MechtronConfig {
44    type Error = SpaceErr;
45
46    fn try_from(doc: Vec<u8>) -> Result<Self, Self::Error> {
47        let doc = String::from_utf8(doc)?;
48        mechtron_config(doc.as_str())
49    }
50}
51
52impl TryFrom<Bin> for MechtronConfig {
53    type Error = SpaceErr;
54
55    fn try_from(doc: Bin) -> Result<Self, Self::Error> {
56        let doc = String::from_utf8((*doc).clone())?;
57        mechtron_config(doc.as_str())
58    }
59}