codama_nodes/link_nodes/
instruction_link_node.rs

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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
use crate::{CamelCaseString, ProgramLinkNode};
use codama_nodes_derive::node;

#[node]
pub struct InstructionLinkNode {
    // Data.
    pub name: CamelCaseString,

    // Children.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub program: Option<ProgramLinkNode>,
}

impl From<InstructionLinkNode> for crate::Node {
    fn from(val: InstructionLinkNode) -> Self {
        crate::Node::Link(val.into())
    }
}

impl InstructionLinkNode {
    pub fn new<T>(name: T) -> Self
    where
        T: Into<CamelCaseString>,
    {
        Self {
            name: name.into(),
            program: None,
        }
    }

    pub fn new_from_program<T>(name: T, program: ProgramLinkNode) -> Self
    where
        T: Into<CamelCaseString>,
    {
        Self {
            name: name.into(),
            program: Some(program),
        }
    }
}

impl From<String> for InstructionLinkNode {
    fn from(name: String) -> Self {
        Self::new(name)
    }
}

impl From<&str> for InstructionLinkNode {
    fn from(name: &str) -> Self {
        Self::new(name)
    }
}

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

    #[test]
    fn new() {
        let node = InstructionLinkNode::new("my_instruction");
        assert_eq!(node.name, CamelCaseString::new("myInstruction"));
    }

    #[test]
    fn new_from_program() {
        let node = InstructionLinkNode::new_from_program(
            "my_instruction",
            ProgramLinkNode::new("my_program"),
        );
        assert_eq!(node.name, CamelCaseString::new("myInstruction"));
        assert_eq!(node.program, Some(ProgramLinkNode::new("myProgram")));
    }

    #[test]
    fn from_string() {
        let node: InstructionLinkNode = String::from("my_instruction").into();
        assert_eq!(node.name, CamelCaseString::new("myInstruction"));
        assert_eq!(node.program, None);
    }

    #[test]
    fn from_str() {
        let node: InstructionLinkNode = "my_instruction".into();
        assert_eq!(node.name, CamelCaseString::new("myInstruction"));
        assert_eq!(node.program, None);
    }

    #[test]
    fn to_json() {
        let node = InstructionLinkNode::new("myInstruction");
        let json = serde_json::to_string(&node).unwrap();
        assert_eq!(
            json,
            r#"{"kind":"instructionLinkNode","name":"myInstruction"}"#
        );
    }

    #[test]
    fn from_json() {
        let json = r#"{"kind":"instructionLinkNode","name":"myInstruction"}"#;
        let node: InstructionLinkNode = serde_json::from_str(json).unwrap();
        assert_eq!(node, InstructionLinkNode::new("myInstruction"));
    }
}