powerio_dist/
terminal_index.rs1use std::collections::BTreeMap;
8
9use crate::model::MulticonductorNetwork;
10
11#[derive(Debug, Clone, PartialEq, Eq)]
13#[non_exhaustive]
14pub enum TerminalIndexError {
15 DuplicateBus { bus: String },
17 DuplicateTerminal { bus: String, terminal: String },
19}
20
21impl std::fmt::Display for TerminalIndexError {
22 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
23 match self {
24 Self::DuplicateBus { bus } => {
25 write!(f, "bus identity `{bus}` is duplicated case-insensitively")
26 }
27 Self::DuplicateTerminal { bus, terminal } => {
28 write!(f, "bus `{bus}` repeats terminal `{terminal}`")
29 }
30 }
31 }
32}
33
34impl std::error::Error for TerminalIndexError {}
35
36#[derive(Debug, Clone, Default, PartialEq, Eq)]
38pub struct MulticonductorTerminalIndex {
39 terminals: Vec<(String, String)>,
41 positions: BTreeMap<String, BTreeMap<String, usize>>,
43}
44
45impl MulticonductorTerminalIndex {
46 pub fn build(network: &MulticonductorNetwork) -> Result<Self, TerminalIndexError> {
54 let mut index = Self::default();
55 for bus in network.buses() {
56 let key = bus.id.to_ascii_lowercase();
57 if index.positions.contains_key(&key) {
58 return Err(TerminalIndexError::DuplicateBus {
59 bus: bus.id.clone(),
60 });
61 }
62 let terminals = index.positions.entry(key).or_default();
63 for terminal in &bus.terminals {
64 if terminals
65 .insert(terminal.clone(), index.terminals.len())
66 .is_some()
67 {
68 return Err(TerminalIndexError::DuplicateTerminal {
69 bus: bus.id.clone(),
70 terminal: terminal.clone(),
71 });
72 }
73 index.terminals.push((bus.id.clone(), terminal.clone()));
74 }
75 }
76 Ok(index)
77 }
78
79 #[must_use]
81 pub fn terminals(&self) -> &[(String, String)] {
82 &self.terminals
83 }
84
85 #[must_use]
87 pub fn len(&self) -> usize {
88 self.terminals.len()
89 }
90
91 #[must_use]
93 pub fn is_empty(&self) -> bool {
94 self.terminals.is_empty()
95 }
96
97 #[must_use]
100 pub fn resolve(&self, bus: &str, terminal: &str) -> Option<usize> {
101 self.bus(bus)?.get(terminal).copied()
102 }
103
104 #[must_use]
107 pub fn bus_terminals(&self, bus: &str) -> Vec<usize> {
108 let mut positions: Vec<usize> = self
109 .bus(bus)
110 .map(|terminals| terminals.values().copied().collect())
111 .unwrap_or_default();
112 positions.sort_unstable();
113 positions
114 }
115
116 fn bus(&self, bus: &str) -> Option<&BTreeMap<String, usize>> {
117 self.positions
118 .get(bus)
119 .or_else(|| self.positions.get(&bus.to_ascii_lowercase()))
120 }
121}
122
123#[cfg(test)]
124mod tests {
125 use super::*;
126 use crate::model::DistBus;
127
128 #[test]
129 fn terminals_index_flat_with_case_insensitive_buses() {
130 let mut network = MulticonductorNetwork::default();
131 network
132 .buses_mut()
133 .push(DistBus::new("Src", vec!["1".into(), "2".into()]));
134 network
135 .buses_mut()
136 .push(DistBus::new("load", vec!["1".into(), "0".into()]));
137 let index = MulticonductorTerminalIndex::build(&network).unwrap();
138 assert_eq!(index.len(), 4);
139 assert_eq!(index.resolve("src", "2"), Some(1));
140 assert_eq!(index.resolve("SRC", "2"), Some(1));
141 assert_eq!(index.resolve("load", "0"), Some(3));
142 assert_eq!(index.resolve("load", "3"), None);
143 assert_eq!(index.bus_terminals("LOAD"), vec![2, 3]);
144 network
145 .buses_mut()
146 .push(DistBus::new("LOAD", vec!["1".into()]));
147 assert!(matches!(
148 MulticonductorTerminalIndex::build(&network),
149 Err(TerminalIndexError::DuplicateBus { .. })
150 ));
151 }
152}