Skip to main content

brep_ecad_core/
pin_functions.rs

1//! A pin's alternate functions ([`Pin::alternates`]) and the one each placed
2//! part shows ([`Component::pin_functions`]). Documentary only: nets, ERC and
3//! the netlist bind by number and read the main name and type.
4use crate::{Component, Document, Pin};
5use uuid::Uuid;
6
7impl Component {
8    /// The name this component's `pin` goes by: the function chosen for it
9    /// ([`Component::pin_functions`]) while its symbol still offers that
10    /// function, else the pin's main name.
11    pub fn pin_label<'a>(&'a self, pin: &'a Pin) -> &'a str {
12        self.pin_functions
13            .get(&pin.number)
14            .filter(|chosen| pin.alternates.contains(chosen))
15            .map_or(pin.name.as_str(), String::as_str)
16    }
17}
18
19impl Document {
20    /// Choose which function component `id`'s pin `number` goes by: one of the
21    /// pin's [`Pin::alternates`], or its main name (`None`, or the main name
22    /// itself), which clears the choice. Documentary only; see
23    /// [`Pin::alternates`]. Returns whether anything changed.
24    pub fn set_pin_function(&mut self, id: Uuid, number: &str, function: Option<&str>) -> Result<bool, String> {
25        let c = self
26            .components
27            .iter_mut()
28            .find(|c| c.id == id)
29            .ok_or("Component no longer exists")?;
30        let pin = c
31            .symbol
32            .pins
33            .iter()
34            .find(|p| p.number == number)
35            .ok_or_else(|| format!("{} has no pin {number}", c.reference))?;
36        let chosen = match function {
37            None => None,
38            Some(name) if name == pin.name => None,
39            Some(name) if pin.alternates.iter().any(|a| a == name) => Some(name.to_owned()),
40            Some(name) => {
41                return Err(format!(
42                    "Pin {number} of {} has no function {name}; it offers {}",
43                    c.reference,
44                    std::iter::once(pin.name.as_str())
45                        .chain(pin.alternates.iter().map(String::as_str))
46                        .collect::<Vec<_>>()
47                        .join(", ")
48                ));
49            }
50        };
51        let before = c.pin_functions.get(number).cloned();
52        match &chosen {
53            Some(name) => {
54                c.pin_functions.insert(number.to_owned(), name.clone());
55            }
56            None => {
57                c.pin_functions.remove(number);
58            }
59        }
60        Ok(before != chosen)
61    }
62}