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
use std::str::FromStr;

use crate::{ID, id_from_hex_str, Instance, is_default, NatureError, Result, SEPARATOR_INS_KEY};

#[derive(Serialize, Deserialize, Debug, Default, Clone, PartialEq, Eq, Hash)]
pub struct FromInstance {
    pub id: ID,
    pub meta: String,
    #[serde(skip_serializing_if = "is_default")]
    #[serde(default)]
    pub para: String,
    #[serde(skip_serializing_if = "is_default")]
    #[serde(default)]
    pub state_version: i32,
}

impl FromInstance {
    pub fn from_key_no_state(key: &str) -> Result<Self> {
        let part: Vec<&str> = key.split(&*SEPARATOR_INS_KEY).collect();
        if part.len() != 3 {
            return Err(NatureError::VerifyError("format error".to_string()));
        }
        let rtn = FromInstance {
            id: id_from_hex_str(part[1])?,
            meta: part[0].to_string(),
            para: part[2].to_string(),
            state_version: 0,
        };
        Ok(rtn)
    }
}

impl From<&Instance> for FromInstance {
    fn from(from: &Instance) -> Self {
        FromInstance {
            id: from.id,
            meta: from.meta.to_string(),
            para: from.para.clone(),
            state_version: from.state_version,
        }
    }
}

impl FromStr for FromInstance {
    type Err = NatureError;

    fn from_str(s: &str) -> Result<Self> {
        let part: Vec<&str> = s.split(&*SEPARATOR_INS_KEY).collect();
        if part.len() != 4 {
            let msg = format!("FromInstance::from_str : error input [{}]", s);
            return Err(NatureError::VerifyError(msg));
        }
        let rtn = FromInstance {
            id: id_from_hex_str(part[1])?,
            meta: part[0].to_string(),
            para: part[2].to_string(),
            state_version: i32::from_str(part[3])?,
        };
        Ok(rtn)
    }
}

impl ToString for FromInstance {
    fn to_string(&self) -> String {
        let sep: &str = &*SEPARATOR_INS_KEY;
        format!("{}{}{:x}{}{}{}{}", self.meta, sep, self.id, sep, self.para, sep, self.state_version)
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn to_string_test() {
        let from = FromInstance::default();
        let string = from.to_string();
        assert_eq!(string, "|0||0");
        let rtn = FromInstance::from_str(&string).unwrap();
        assert_eq!(from, rtn);
    }
}