codama_nodes/discriminator_nodes/
field_discriminator_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
use crate::CamelCaseString;
use codama_nodes_derive::node;

#[node]
pub struct FieldDiscriminatorNode {
    // Data.
    pub name: CamelCaseString,
    pub offset: usize,
}

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

impl FieldDiscriminatorNode {
    pub fn new<T>(name: T, offset: usize) -> Self
    where
        T: Into<CamelCaseString>,
    {
        Self {
            name: name.into(),
            offset,
        }
    }
}

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

    #[test]
    fn new() {
        let node = FieldDiscriminatorNode::new("my_field", 0);
        assert_eq!(node.name, CamelCaseString::new("myField"));
        assert_eq!(node.offset, 0);
    }

    #[test]
    fn to_json() {
        let node = FieldDiscriminatorNode::new("myField", 0);
        let json = serde_json::to_string(&node).unwrap();
        assert_eq!(
            json,
            r#"{"kind":"fieldDiscriminatorNode","name":"myField","offset":0}"#
        );
    }

    #[test]
    fn from_json() {
        let json = r#"{"kind":"fieldDiscriminatorNode","name":"myField","offset":0}"#;
        let node: FieldDiscriminatorNode = serde_json::from_str(json).unwrap();
        assert_eq!(node, FieldDiscriminatorNode::new("myField", 0));
    }
}