netlist/saver/
mod.rs

1use crate::{model::{PinDirection,PortList}, NResult, NetList};
2use std::{fs::File, io::Write, path::Path};
3use serde::Serialize;
4impl<W: Default, N: Default, G: Default, B: Default, P: Default, S: Default> NetList<W, N, G, B, P, S> {
5    pub fn netlist2verilog<Pth: AsRef<Path>>(&self, file: Pth) -> NResult<()> {
6        let mut f = File::create(file)?;
7        writeln!(f, "module {}", self.name)?;
8        writeln!(
9            f,
10            "({});",
11            self.pin_map
12                .keys()
13                .map(|x| x.to_string())
14                .collect::<Vec<String>>()
15                .join(" , ")
16        )?;
17        for p in &self.pins {
18            match p.direction {
19                PinDirection::Input => {
20                    if p.bitwidth == 1 {
21                        writeln!(f, "input {};", p.name)?;
22                    } else {
23                        writeln!(f, "input [{}:0] {};", p.bitwidth - 1, p.name)?;
24                    }
25                }
26                PinDirection::Output => {
27                    if p.bitwidth == 1 {
28                        writeln!(f, "output {};", p.name)?;
29                    } else {
30                        writeln!(f, "output [{}:0] {};", p.bitwidth - 1, p.name)?;
31                    }
32                }
33            }
34        }
35        let mut p2n_list = Vec::new();
36        for g in &self.gates {
37            // insert first node
38            let node = &self.nodes[g.first_node];
39            p2n_list.push((&node.name, &self.nets[node.connection].name));
40            // insert second node and so on
41            for node_idx in self.get_gate_node(&g.name)? {
42                let node = &self.nodes[node_idx];
43                p2n_list.push((&node.name, &self.nets[node.connection].name));
44            }
45            writeln!(
46                f,
47                "{} {} ({});",
48                g.model,
49                g.name,
50                p2n_list
51                    .iter()
52                    .map(|d| format!(".{} ( {} )", d.0, d.1))
53                    .collect::<Vec<String>>()
54                    .join(" , ")
55            )?;
56            p2n_list.clear();
57        }
58
59        writeln!(f, "endmodule")?;
60        Ok(())
61    }
62}
63
64impl<P: Default + Serialize> PortList<P> {
65    pub fn portlist2xml<Pth: AsRef<Path>>(&self, file: Pth) -> NResult<()> {
66        let mut f = File::create(file)?;
67        let buff = serde_xml_rs::to_string(&self)?;
68        write!(f,"{}",&buff)?;
69        Ok(())
70    }
71}