ifc_step/codec.rs
1//! The STEP codec: format detection, parse policy, and model I/O.
2//!
3//! Two types rather than one configurable type. [`StepCodec`] is the strict
4//! reader and stays zero-sized, so it can be named as a value wherever a codec
5//! is needed. [`StepReader`] carries an explicit [`ParseOptions`] for consumers
6//! that opt into malformed-record recovery. Both implement [`Codec`], so either
7//! can be stored in a `Box<dyn Codec>` alongside the other formats.
8//!
9//! # Lazy loading
10//!
11//! A strict read validates every record and then decodes each entity on
12//! first access (see `lazy.rs`): opening a file costs a syntax pass instead of
13//! building every value, and memory holds the source plus what was touched.
14//! The model keeps its source, so [`Codec::read_bytes`] copies the input once;
15//! [`Codec::read_owned`] and [`Codec::read_path`] hand over or read a buffer
16//! without that copy. [`StepReader::eager`] restores decode-everything-now.
17
18use crate::lazy::{self, Bytes};
19use crate::{parser, writer, ReadFailure};
20use ifc_model::{Codec, Model, ModelError};
21use openbim_step::{is_step_file, OnMalformed, ParseOptions};
22use std::io::Write;
23use std::path::Path;
24
25/// The STEP physical file codec.
26///
27/// Strict: a record this codec cannot read is an error, because an authoring
28/// tool that silently drops entities corrupts the file it edits.
29///
30/// A consumer that would rather load a damaged export uses
31/// [`StepCodec::lenient`] and reads [`Model::diagnostics`] to see what was
32/// dropped.
33///
34/// ```
35/// use ifc_model::Codec;
36/// use ifc_step::StepCodec;
37///
38/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
39/// # let bytes = b"ISO-10303-21;\nHEADER;\nFILE_DESCRIPTION((''),'2;1');\n\
40/// # FILE_NAME('n','t',(''),(''),'p','o','a');\nFILE_SCHEMA(('IFC4'));\nENDSEC;\n\
41/// # DATA;\n#1= IFCPERSON($,$,'a',$,$,$,$,$);\n#2\nENDSEC;\nEND-ISO-10303-21;\n";
42/// // A damaged export: strict reading refuses it.
43/// assert!(StepCodec.read_bytes(bytes).is_err());
44///
45/// // A viewer opts into recovery and reports what was lost.
46/// let model = StepCodec::lenient().read_bytes(bytes)?;
47/// assert_eq!(model.len(), 1);
48/// assert_eq!(model.diagnostics().len(), 1);
49/// # Ok(())
50/// # }
51/// ```
52#[derive(Debug, Clone, Copy, Default)]
53pub struct StepCodec;
54
55impl StepCodec {
56 /// A reader that skips unreadable data records and reports each one as a
57 /// [`Model`] diagnostic, and reads a REAL written without its decimal
58 /// point (`1E-05`) as the REAL it spells, with a diagnostic
59 /// ([`ParseOptions::lenient`]).
60 ///
61 /// Header structure and the physical-file marker remain fatal: a file
62 /// whose identity cannot be established is not partially readable.
63 #[must_use]
64 pub const fn lenient() -> StepReader {
65 StepReader::new(ParseOptions::lenient())
66 }
67
68 /// A reader with an explicit malformed-record policy.
69 #[must_use]
70 pub const fn with_options(options: ParseOptions) -> StepReader {
71 StepReader::new(options)
72 }
73}
74
75/// A STEP codec carrying an explicit parse policy.
76#[derive(Debug, Clone, Copy, Default)]
77pub struct StepReader {
78 options: ParseOptions,
79 /// Decode every entity during the read instead of on first access.
80 eager: bool,
81}
82
83impl StepReader {
84 /// A reader applying `options`.
85 #[must_use]
86 pub const fn new(options: ParseOptions) -> Self {
87 Self {
88 options,
89 eager: false,
90 }
91 }
92
93 /// Decodes every entity during the read, as before lazy loading.
94 ///
95 /// For a consumer that will touch nearly every entity anyway and wants
96 /// the source released after the read. Recovery and reference-check
97 /// options always read eagerly.
98 #[must_use]
99 pub const fn eager(mut self) -> Self {
100 self.eager = true;
101 self
102 }
103
104 /// Reads a memory-mapped file.
105 ///
106 /// Avoids copying the file: pages are loaded from the page cache as
107 /// they are touched and are not part of the process's own heap. A lazily
108 /// loaded model keeps the mapping and decodes from it for as long as it
109 /// lives.
110 ///
111 /// # Safety
112 ///
113 /// The file must not be modified or truncated while the returned model
114 /// -- or any clone of it -- is alive. Truncation can end the process
115 /// with `SIGBUS` when an entity is decoded; a rewrite makes decoding
116 /// panic or, if the new bytes still parse, read other content. Prefer
117 /// [`Codec::read_path`], which owns its copy, unless the file is known
118 /// to stay put.
119 ///
120 /// # Errors
121 ///
122 /// As [`Codec::read_path`].
123 pub unsafe fn read_path_mapped(&self, path: &Path) -> Result<Model, ModelError> {
124 let file = std::fs::File::open(path).map_err(|e| ModelError::Io(e.to_string()))?;
125 // SAFETY: the caller guarantees the file stays unchanged while the
126 // mapping lives, which is the model's lifetime when it keeps it.
127 let map =
128 unsafe { memmap2::Mmap::map(&file) }.map_err(|e| ModelError::Io(e.to_string()))?;
129 if !is_step_file(&map) {
130 return Err(wrong_format());
131 }
132 if self.is_lazy() {
133 return lazy::read(Bytes::Mapped(map), self.options).map_err(Into::into);
134 }
135 parser::parse(&map, self.options).map_err(Into::into)
136 }
137
138 /// Reads `bytes` like [`Codec::read_owned`] and, when the read fails,
139 /// hands the buffer back with the error.
140 ///
141 /// The buffer is not copied either way: a failed read returns the very
142 /// allocation that was passed in, so the caller can locate the error in
143 /// it ([`ReadFailure::location`]) or read it again under another policy.
144 ///
145 /// # Errors
146 ///
147 /// As [`Codec::read_owned`], in a [`ReadFailure`].
148 pub fn try_read_owned(&self, bytes: Vec<u8>) -> Result<Model, ReadFailure> {
149 let fail = |error: ModelError, bytes| ReadFailure { error, bytes };
150 if !is_step_file(&bytes) {
151 return Err(fail(wrong_format(), bytes));
152 }
153 if self.is_lazy() {
154 return lazy::read_or_return(Bytes::Owned(bytes), self.options)
155 .map_err(|(error, bytes)| fail(error.into(), bytes.into_vec()));
156 }
157 parser::parse(&bytes, self.options).map_err(|error| fail(error.into(), bytes))
158 }
159
160 /// Whether [`Codec::read_bytes`] accepts `bytes`, and its error when it
161 /// does not, without building a model.
162 ///
163 /// Exact, not a heuristic: the error is the one `read_bytes` returns for
164 /// the same input under the same options, and `Ok` means `read_bytes`
165 /// succeeds. Locate a syntax error with [`SyntaxLocation::locate`](crate::SyntaxLocation::locate).
166 ///
167 /// A strict check keeps the id of every record it accepts, to refuse a
168 /// repeated one, so its memory grows with the number of records (8 bytes
169 /// and a hash slot each).
170 ///
171 /// # Errors
172 ///
173 /// The error `read_bytes` would return.
174 pub fn check(&self, bytes: &[u8]) -> Result<(), ModelError> {
175 if !is_step_file(bytes) {
176 return Err(wrong_format());
177 }
178 parser::check_input(bytes, self.options).map_err(Into::into)
179 }
180
181 fn is_lazy(&self) -> bool {
182 !self.eager && lazy::is_lazy(self.options)
183 }
184
185 /// Sets the malformed-record policy.
186 #[must_use]
187 pub const fn on_malformed_record(mut self, policy: OnMalformed) -> Self {
188 self.options = self.options.on_malformed_record(policy);
189 self
190 }
191
192 /// The policy this reader applies.
193 #[must_use]
194 pub const fn options(&self) -> ParseOptions {
195 self.options
196 }
197}
198
199impl StepCodec {
200 /// As [`StepReader::try_read_owned`], strict.
201 ///
202 /// # Errors
203 ///
204 /// As [`Codec::read_owned`], in a [`ReadFailure`].
205 pub fn try_read_owned(&self, bytes: Vec<u8>) -> Result<Model, ReadFailure> {
206 StepReader::new(ParseOptions::strict()).try_read_owned(bytes)
207 }
208}
209
210impl Codec for StepCodec {
211 fn name(&self) -> &'static str {
212 StepReader::new(ParseOptions::strict()).name()
213 }
214
215 fn extensions(&self) -> &'static [&'static str] {
216 StepReader::new(ParseOptions::strict()).extensions()
217 }
218
219 fn detect(&self, bytes: &[u8]) -> bool {
220 is_step_file(bytes)
221 }
222
223 fn read_bytes(&self, bytes: &[u8]) -> Result<Model, ModelError> {
224 StepReader::new(ParseOptions::strict()).read_bytes(bytes)
225 }
226
227 fn read_owned(&self, bytes: Vec<u8>) -> Result<Model, ModelError> {
228 StepReader::new(ParseOptions::strict()).read_owned(bytes)
229 }
230
231 fn write(&self, model: &Model, out: &mut dyn Write) -> Result<(), ModelError> {
232 writer::write(model, out).map_err(|e| ModelError::Write(e.to_string()))
233 }
234
235 fn read_path(&self, path: &Path) -> Result<Model, ModelError> {
236 StepReader::new(ParseOptions::strict()).read_path(path)
237 }
238}
239
240fn wrong_format() -> ModelError {
241 ModelError::WrongFormat {
242 expected: "STEP",
243 detail: "missing ISO-10303-21 magic".into(),
244 }
245}
246
247impl Codec for StepReader {
248 fn name(&self) -> &'static str {
249 "STEP"
250 }
251
252 fn extensions(&self) -> &'static [&'static str] {
253 &["ifc", "step", "stp"]
254 }
255
256 fn detect(&self, bytes: &[u8]) -> bool {
257 is_step_file(bytes)
258 }
259
260 fn read_bytes(&self, bytes: &[u8]) -> Result<Model, ModelError> {
261 if !is_step_file(bytes) {
262 return Err(wrong_format());
263 }
264 if self.is_lazy() {
265 // The model keeps its source, so the borrowed input is copied.
266 return lazy::read(Bytes::Owned(bytes.to_vec()), self.options).map_err(Into::into);
267 }
268 parser::parse(bytes, self.options).map_err(Into::into)
269 }
270
271 fn read_owned(&self, bytes: Vec<u8>) -> Result<Model, ModelError> {
272 if !is_step_file(&bytes) {
273 return Err(wrong_format());
274 }
275 if self.is_lazy() {
276 return lazy::read(Bytes::Owned(bytes), self.options).map_err(Into::into);
277 }
278 parser::parse(&bytes, self.options).map_err(Into::into)
279 }
280
281 fn write(&self, model: &Model, out: &mut dyn Write) -> Result<(), ModelError> {
282 writer::write(model, out).map_err(|e| ModelError::Write(e.to_string()))
283 }
284
285 /// Reads the file into a buffer the model owns.
286 ///
287 /// Not memory-mapped: a lazily loaded model decodes from its source for
288 /// as long as it lives, and a mapping of a file that another process
289 /// changes in that time is undefined behaviour. The mapped read is
290 /// [`StepReader::read_path_mapped`], an `unsafe` opt-in.
291 fn read_path(&self, path: &Path) -> Result<Model, ModelError> {
292 let bytes = std::fs::read(path).map_err(|e| ModelError::Io(e.to_string()))?;
293 self.read_owned(bytes)
294 }
295}