Skip to main content
← Back to kicad-monkey Rust Docs kicad-monkey Rust Crate API Reference

kicad_monkey_core/
schematic_bundle_indexes.rs

1use crate::{
2    SchematicDefinition, SchematicLibrarySymbol, SchematicPlacedSymbol, SourceBundleError,
3    SourceBundleErrorKind,
4};
5use std::collections::HashMap;
6
7impl SchematicDefinition {
8    pub fn library_symbol_for_placement(
9        &self,
10        symbol: &SchematicPlacedSymbol,
11    ) -> Option<&SchematicLibrarySymbol> {
12        self.library_symbol_index_for_key(&symbol.lib_name)
13            .or_else(|| self.library_symbol_index_for_key(&symbol.lib_id))
14            .map(|index| &self.library_symbols[index])
15    }
16
17    pub fn library_pin_symbol_for_placement(
18        &self,
19        symbol: &SchematicPlacedSymbol,
20    ) -> Option<&SchematicLibrarySymbol> {
21        let index = self
22            .library_symbol_index_for_key(&symbol.lib_name)
23            .or_else(|| self.library_symbol_index_for_key(&symbol.lib_id))?;
24        self.library_pin_owner_by_symbol[index]
25            .map(|owner_index| &self.library_symbols[owner_index])
26    }
27
28    fn library_symbol_index_for_key(&self, key: &str) -> Option<usize> {
29        library_symbol_index_for_key(&self.library_symbol_by_key, key)
30    }
31}
32
33/// Resolve the effective pin-bearing symbol for every library symbol once.
34///
35/// The inheritance graph is functional (each symbol has at most one `extends`
36/// edge), so a three-state walk resolves every edge at most once. A symbol
37/// with no units and no parent to inherit from (a properties-only symbol, a
38/// missing parent or an inheritance cycle) owns itself: it has no body and no
39/// pins, and KiCad draws only its visible fields.
40pub(crate) fn resolve_library_pin_owners(
41    symbols: &[SchematicLibrarySymbol],
42    index: &HashMap<String, usize>,
43) -> Vec<Option<usize>> {
44    let mut owners = vec![None; symbols.len()];
45    let mut states = vec![0_u8; symbols.len()];
46    for start in 0..symbols.len() {
47        if states[start] == 2 {
48            continue;
49        }
50        let mut path = Vec::new();
51        let mut current = start;
52        let owner = loop {
53            if states[current] == 2 {
54                break owners[current];
55            }
56            if states[current] == 1 {
57                break Some(start);
58            }
59            states[current] = 1;
60            path.push(current);
61            let symbol = &symbols[current];
62            if !symbol.subsymbols.is_empty() {
63                break Some(current);
64            }
65            let Some(parent) = symbol
66                .extends
67                .as_deref()
68                .and_then(|key| library_symbol_index_for_key(index, key))
69            else {
70                break Some(current);
71            };
72            current = parent;
73        };
74        for symbol_index in path.into_iter().rev() {
75            owners[symbol_index] = owner;
76            states[symbol_index] = 2;
77        }
78    }
79    owners
80}
81
82pub(crate) fn library_symbol_index_for_key(
83    index: &HashMap<String, usize>,
84    key: &str,
85) -> Option<usize> {
86    if key.is_empty() {
87        return None;
88    }
89    let direct = index.get(key).copied();
90    let basename = key
91        .rsplit_once(':')
92        .and_then(|(_, basename)| index.get(basename).copied());
93    direct.or(basename)
94}
95
96pub(crate) fn index_bundle_legacy_instances(
97    definitions: &[SchematicDefinition],
98) -> HashMap<String, (usize, usize)> {
99    let mut index = HashMap::new();
100    for (definition_index, definition) in definitions.iter().enumerate() {
101        for (instance_index, instance) in definition.legacy_symbol_instances.iter().enumerate() {
102            let path = instance.path.trim_end_matches('/');
103            if !path.is_empty() {
104                index
105                    .entry(path.to_owned())
106                    .or_insert((definition_index, instance_index));
107            }
108        }
109    }
110    index
111}
112
113pub(crate) fn index_library_symbols(
114    symbols: &[SchematicLibrarySymbol],
115    source_path: &str,
116    _max_key_bytes: usize,
117) -> Result<HashMap<String, usize>, SourceBundleError> {
118    index_library_symbol_names(
119        &symbols
120            .iter()
121            .map(|symbol| symbol.name.as_str())
122            .collect::<Vec<_>>(),
123        source_path,
124    )
125}
126
127/// Exact names win over aliases regardless of declaration order. An alias may
128/// only fill a name no authored definition already owns.
129pub(crate) fn index_library_symbol_names(
130    names: &[&str],
131    source_path: &str,
132) -> Result<HashMap<String, usize>, SourceBundleError> {
133    let mut index = HashMap::new();
134    let mut retained_bytes = 0_usize;
135    for (symbol_index, name) in names.iter().enumerate() {
136        index.entry((*name).to_owned()).or_insert(symbol_index);
137    }
138    for (symbol_index, name) in names.iter().enumerate() {
139        let mut keys = std::iter::once(*name).chain(
140            name.char_indices()
141                .filter(|(_, character)| *character == ':')
142                .map(|(offset, _)| &name[offset + 1..]),
143        );
144        keys.try_for_each(|key| {
145            retained_bytes = retained_bytes
146                .checked_add(key.len())
147                .ok_or_else(|| limit_error(source_path, "library lookup key bytes overflow"))?;
148            index.entry(key.to_owned()).or_insert(symbol_index);
149            Ok(())
150        })?;
151    }
152    Ok(index)
153}
154
155pub(crate) fn portable_file_stem(path: &str) -> String {
156    let filename = path.rsplit('/').next().unwrap_or(path);
157    let suffix = ".kicad_pro";
158    filename
159        .get(..filename.len().saturating_sub(suffix.len()))
160        .filter(|_| {
161            filename
162                .get(filename.len().saturating_sub(suffix.len())..)
163                .is_some_and(|value| value.eq_ignore_ascii_case(suffix))
164        })
165        .unwrap_or(filename)
166        .to_owned()
167}
168
169fn limit_error(source_path: &str, message: &str) -> SourceBundleError {
170    SourceBundleError::new(
171        SourceBundleErrorKind::ResourceLimit,
172        Some(source_path),
173        message,
174    )
175}