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

kicad_monkey_core/pcb/
document.rs

1//! Owned PCB source with reparsing source-preserving mutations.
2
3use super::*;
4use crate::sexpr::utf8_text;
5use std::io::{Read, Write};
6
7/// An owned KiCad board document.
8///
9/// The document owns only source text and limits. Each [`PcbDocument::view`]
10/// borrows that text and builds the bounded structural index, avoiding a
11/// self-referential object and keeping unknown forms byte-preserved.
12#[derive(Clone, Debug)]
13pub struct PcbDocument {
14    source: String,
15    limits: PcbLimits,
16}
17
18impl PcbDocument {
19    /// Validate and own one UTF-8 `kicad_pcb` source buffer.
20    pub fn parse(source: String, limits: PcbLimits) -> Result<Self, Error> {
21        PcbView::parse(&source, limits)?;
22        Ok(Self { source, limits })
23    }
24
25    /// Read at most the configured source ceiling plus one sentinel byte.
26    pub fn from_reader(mut reader: impl Read, limits: PcbLimits) -> Result<Self, Error> {
27        // The default ceiling is `usize::MAX` (#612), so the sentinel saturates.
28        let read_limit = limits.max_source_bytes.saturating_add(1);
29        let mut bytes = Vec::new();
30        reader
31            .by_ref()
32            .take(read_limit as u64)
33            .read_to_end(&mut bytes)
34            .map_err(io_error)?;
35        if bytes.len() > limits.max_source_bytes {
36            return Err(limit_error());
37        }
38        let source = utf8_text(&bytes)?.to_owned();
39        Self::parse(source, limits)
40    }
41
42    pub fn source(&self) -> &str {
43        &self.source
44    }
45
46    pub fn into_source(self) -> String {
47        self.source
48    }
49
50    pub fn limits(&self) -> PcbLimits {
51        self.limits
52    }
53
54    /// Build a fresh source-backed view over the current owned text.
55    pub fn view(&self) -> Result<PcbView<'_>, Error> {
56        PcbView::parse(&self.source, self.limits)
57    }
58
59    /// Build a dependency-aware selected view over the current source.
60    pub fn view_selected(&self, selection: PcbSelection) -> Result<PcbView<'_>, Error> {
61        PcbView::parse_selected(&self.source, self.limits, selection)
62    }
63
64    /// Write the current source verbatim after checking the output ceiling.
65    pub fn write_to(&self, mut writer: impl Write) -> Result<(), Error> {
66        if self.source.len() > self.limits.max_output_bytes {
67            return Err(output_limit_error());
68        }
69        writer.write_all(self.source.as_bytes()).map_err(io_error)
70    }
71
72    /// Replace one unambiguous board property and reparse before committing.
73    pub fn set_property(&mut self, name: &str, value: &str) -> Result<bool, Error> {
74        let edit = self.view()?.set_property(name, value)?;
75        self.commit(edit)
76    }
77
78    /// Update or create one board property and reparse before committing.
79    pub fn upsert_property(&mut self, name: &str, value: &str) -> Result<bool, Error> {
80        let edit = self.view()?.upsert_property(name, value)?;
81        self.commit(edit)
82    }
83
84    /// Remove one board property and reparse before committing.
85    pub fn remove_property(&mut self, name: &str) -> Result<bool, Error> {
86        let edit = self.view()?.remove_property(name)?;
87        self.commit(edit)
88    }
89
90    /// Remove one unambiguous identified top-level form and reparse before committing.
91    pub fn remove_top_level_by_id(&mut self, identifier: &str) -> Result<bool, Error> {
92        let edit = self.view()?.remove_top_level_by_id(identifier)?;
93        self.commit(edit)
94    }
95
96    /// Replace one identified top-level object's singular layer field.
97    pub fn set_top_level_layer_by_id(
98        &mut self,
99        identifier: &str,
100        layer: &str,
101    ) -> Result<bool, Error> {
102        let edit = self.view()?.set_top_level_layer_by_id(identifier, layer)?;
103        self.commit(edit)
104    }
105
106    fn commit(&mut self, edit: PcbEdit) -> Result<bool, Error> {
107        if !edit.changed {
108            return Ok(false);
109        }
110        PcbView::parse(&edit.source, self.limits)?;
111        self.source = edit.source;
112        Ok(true)
113    }
114}
115
116fn io_error(error: std::io::Error) -> Error {
117    Error::build(ErrorKind::Io, format!("PCB source I/O failed: {error}"))
118}