use std::collections::BTreeMap;
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct PinRef {
pub refdes: String,
pub pin: String,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Component {
pub mpn: Option<String>,
pub pins: BTreeMap<String, String>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Board {
pub components: BTreeMap<String, Component>,
pub nets: BTreeMap<String, Vec<PinRef>>,
}
impl Board {
pub fn new() -> Self {
Self::default()
}
pub fn connect(&mut self, net: &str, refdes: &str, pin: &str) {
let component = self.components.entry(refdes.to_owned()).or_default();
component.pins.insert(pin.to_owned(), net.to_owned());
let pins = self.nets.entry(net.to_owned()).or_default();
let pin_ref = PinRef {
refdes: refdes.to_owned(),
pin: pin.to_owned(),
};
if !pins.contains(&pin_ref) {
pins.push(pin_ref);
}
}
pub fn rewire(&mut self, refdes: &str, pin: &str, net: &str) {
let old = self.net_of(refdes, pin).map(str::to_owned);
if let Some(old) = old
&& let Some(pins) = self.nets.get_mut(&old)
{
pins.retain(|p| !(p.refdes == refdes && p.pin == pin));
if pins.is_empty() {
self.nets.remove(&old);
}
}
self.connect(net, refdes, pin);
}
pub fn add_component(&mut self, refdes: &str) {
self.components.entry(refdes.to_owned()).or_default();
}
pub fn set_mpn(&mut self, refdes: &str, mpn: &str) {
let mpn = mpn.trim();
if !mpn.is_empty() {
self.components.entry(refdes.to_owned()).or_default().mpn = Some(mpn.to_owned());
}
}
pub fn net_of(&self, refdes: &str, pin: &str) -> Option<&str> {
self.components
.get(refdes)?
.pins
.get(pin)
.map(String::as_str)
}
pub fn pins_on(&self, net: &str) -> &[PinRef] {
self.nets.get(net).map_or(&[], Vec::as_slice)
}
pub fn is_resistor(&self, refdes: &str) -> bool {
let mut chars = refdes.chars();
chars.next() == Some('R')
&& chars.next().is_some_and(|c| c.is_ascii_digit())
&& self
.components
.get(refdes)
.is_some_and(|c| c.pins.len() == 2)
}
pub fn nets_via_resistor(&self, net: &str) -> Vec<&str> {
let mut out = Vec::new();
for pin_ref in self.pins_on(net) {
if !self.is_resistor(&pin_ref.refdes) {
continue;
}
if let Some(component) = self.components.get(&pin_ref.refdes) {
for (pin, other) in &component.pins {
if *pin != pin_ref.pin && other != net && !out.contains(&other.as_str()) {
out.push(other.as_str());
}
}
}
}
out
}
}