prjunnamed_netlist/cell/
instance.rs

1use std::{collections::BTreeMap, ops::Range};
2
3use crate::{IoValue, Net, ParamValue, Value};
4
5#[derive(Debug, Clone, PartialEq, Eq, Hash)]
6pub struct Instance {
7    pub kind: String,
8    pub params: BTreeMap<String, ParamValue>,
9    pub inputs: BTreeMap<String, Value>,
10    pub outputs: BTreeMap<String, Range<usize>>,
11    pub ios: BTreeMap<String, IoValue>,
12}
13
14impl Instance {
15    pub fn new(kind: impl Into<String>) -> Self {
16        Instance {
17            kind: kind.into(),
18            params: Default::default(),
19            inputs: Default::default(),
20            outputs: Default::default(),
21            ios: Default::default(),
22        }
23    }
24
25    pub fn output_len(&self) -> usize {
26        self.outputs.values().map(|range| range.len()).sum()
27    }
28
29    pub fn get_param_string(&self, name: &str) -> Option<&str> {
30        let val = self.params.get(name)?;
31        if let ParamValue::String(val) = val {
32            Some(val)
33        } else {
34            None
35        }
36    }
37
38    pub fn add_param(&mut self, name: impl Into<String>, value: impl Into<ParamValue>) {
39        self.params.insert(name.into(), value.into());
40    }
41
42    pub fn rename_param(&mut self, name_from: impl AsRef<str>, name_to: impl Into<String>) {
43        if let Some(param) = self.params.remove(name_from.as_ref()) {
44            assert!(self.params.insert(name_to.into(), param).is_none());
45        }
46    }
47
48    pub fn rename_input(&mut self, name_from: impl AsRef<str>, name_to: impl Into<String>) {
49        if let Some(input) = self.inputs.remove(name_from.as_ref()) {
50            assert!(self.inputs.insert(name_to.into(), input).is_none());
51        }
52    }
53
54    pub fn rename_output(&mut self, name_from: impl AsRef<str>, name_to: impl Into<String>) {
55        if let Some(output) = self.outputs.remove(name_from.as_ref()) {
56            assert!(self.outputs.insert(name_to.into(), output).is_none());
57        }
58    }
59
60    pub fn rename_io(&mut self, name_from: impl AsRef<str>, name_to: impl Into<String>) {
61        if let Some(io) = self.ios.remove(name_from.as_ref()) {
62            assert!(self.ios.insert(name_to.into(), io).is_none());
63        }
64    }
65
66    pub fn visit(&self, mut f: impl FnMut(Net)) {
67        for val in self.inputs.values() {
68            val.visit(&mut f);
69        }
70    }
71
72    pub fn visit_mut(&mut self, mut f: impl FnMut(&mut Net)) {
73        for val in self.inputs.values_mut() {
74            val.visit_mut(&mut f);
75        }
76    }
77}