Skip to main content

codama_nodes/pda_seed_nodes/
constant_pda_seed_node.rs

1use crate::{ConstantPdaSeedNode, ConstantPdaSeedValue, TypeNode, ValueNode};
2
3impl ConstantPdaSeedNode {
4    pub fn new<T, U>(r#type: T, value: U) -> Self
5    where
6        T: Into<TypeNode>,
7        U: Into<ConstantPdaSeedValue>,
8    {
9        Self {
10            r#type: Box::new(r#type.into()),
11            value: Box::new(value.into()),
12        }
13    }
14}
15
16/// Bridge from the broader value-node union into a `constantPdaSeedNode`
17/// value. The spec union `constantPdaSeedValue` is `programIdValueNode |
18/// valueNode`, so every `ValueNode` cleanly maps to its same-named
19/// `ConstantPdaSeedValue` variant.
20impl From<ValueNode> for ConstantPdaSeedValue {
21    fn from(value: ValueNode) -> Self {
22        match value {
23            ValueNode::Array(n) => Self::Array(n),
24            ValueNode::Boolean(n) => Self::Boolean(n),
25            ValueNode::Bytes(n) => Self::Bytes(n),
26            ValueNode::Constant(n) => Self::Constant(n),
27            ValueNode::Enum(n) => Self::Enum(n),
28            ValueNode::Map(n) => Self::Map(n),
29            ValueNode::None(n) => Self::None(n),
30            ValueNode::Number(n) => Self::Number(n),
31            ValueNode::PublicKey(n) => Self::PublicKey(n),
32            ValueNode::Set(n) => Self::Set(n),
33            ValueNode::Some(n) => Self::Some(n),
34            ValueNode::String(n) => Self::String(n),
35            ValueNode::Struct(n) => Self::Struct(n),
36            ValueNode::Tuple(n) => Self::Tuple(n),
37        }
38    }
39}
40
41#[cfg(test)]
42mod tests {
43    use super::*;
44    use crate::{NumberTypeNode, NumberValueNode, U64};
45
46    #[test]
47    fn new() {
48        let node = ConstantPdaSeedNode::new(NumberTypeNode::le(U64), NumberValueNode::new(42u64));
49        assert_eq!(*node.r#type, TypeNode::Number(NumberTypeNode::le(U64)));
50        assert_eq!(
51            *node.value,
52            ConstantPdaSeedValue::Number(NumberValueNode::new(42u64))
53        );
54    }
55
56    #[test]
57    fn to_json() {
58        let node = ConstantPdaSeedNode::new(NumberTypeNode::le(U64), NumberValueNode::new(42u64));
59        let json = serde_json::to_string(&node).unwrap();
60        assert_eq!(
61            json,
62            r#"{"kind":"constantPdaSeedNode","type":{"kind":"numberTypeNode","format":"u64","endian":"le"},"value":{"kind":"numberValueNode","number":42}}"#
63        );
64    }
65
66    #[test]
67    fn from_json() {
68        let json = r#"{"kind":"constantPdaSeedNode","type":{"kind":"numberTypeNode","format":"u64","endian":"le"},"value":{"kind":"numberValueNode","number":42}}"#;
69        let node: ConstantPdaSeedNode = serde_json::from_str(json).unwrap();
70        assert_eq!(
71            node,
72            ConstantPdaSeedNode::new(NumberTypeNode::le(U64), NumberValueNode::new(42u64))
73        );
74    }
75}