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
#[cfg(feature = "serialize")]
use crate::{Cell, Context, Control, IdList, PortParent, RRC};
#[cfg(feature = "serialize")]
use calyx_utils::GetName;
#[cfg(feature = "serialize")]
use serde::{
    ser::{SerializeSeq, SerializeStruct},
    Serialize, Serializer,
};
#[cfg(feature = "serialize")]
use serde_with::SerializeAs;

#[cfg(feature = "serialize")]
impl Serialize for Context {
    fn serialize<S>(&self, ser: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut ctx = ser.serialize_struct("Context", 2)?;
        ctx.serialize_field("components", &self.components)?;
        ctx.serialize_field("entrypoint", &self.entrypoint)?;
        ctx.end()
    }
}

#[cfg(feature = "serialize")]
pub struct SerCellRef;
#[cfg(feature = "serialize")]
impl SerializeAs<RRC<Cell>> for SerCellRef {
    fn serialize_as<S>(
        value: &RRC<Cell>,
        serializer: S,
    ) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        value.borrow().name().serialize(serializer)
    }
}

#[cfg(feature = "serialize")]
impl SerializeAs<RRC<Control>> for Control {
    fn serialize_as<S>(
        value: &RRC<Control>,
        serializer: S,
    ) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        value.borrow().serialize(serializer)
    }
}

#[cfg(feature = "serialize")]
impl<T: GetName + Serialize> Serialize for IdList<T> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut seq = serializer.serialize_seq(Some(self.len()))?;
        for obj in self.iter() {
            seq.serialize_element(obj)?;
        }
        seq.end()
    }
}

#[cfg(feature = "serialize")]
impl Serialize for PortParent {
    fn serialize<S>(&self, ser: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match &self {
            PortParent::Cell(weak_cell_ref) => {
                weak_cell_ref.upgrade().borrow().name().serialize(ser)
            }
            PortParent::Group(weak_group_ref) => {
                weak_group_ref.upgrade().borrow().name().serialize(ser)
            }
            PortParent::StaticGroup(weak_sgroup_ref) => {
                weak_sgroup_ref.upgrade().borrow().name().serialize(ser)
            }
        }
    }
}