1use super::*;
4use std::collections::BTreeMap;
5
6const DEFAULT_VERSION: i64 = 20_260_206;
7const DEFAULT_GENERATOR: &str = "pcbnew";
8const DEFAULT_GENERATOR_VERSION: &str = "10.0";
9const DEFAULT_PAPER: &str = "A4";
10const DEFAULT_THICKNESS: f64 = 1.6;
11
12#[derive(Clone, Debug)]
13pub(super) struct IndexedTable {
14 span: FormSpan,
15 cell_range: Range<usize>,
16}
17
18#[derive(Clone, Debug, PartialEq)]
19pub struct PcbBoardMetadata {
20 pub version: i64,
21 pub generator: String,
22 pub generator_version: String,
23 pub paper: String,
24 pub thickness: f64,
25 pub legacy_teardrops: bool,
26 pub embedded_fonts: bool,
27 pub pad_to_mask_clearance: f64,
28 pub pad_to_paste_clearance: f64,
29 pub pad_to_paste_clearance_ratio: f64,
30}
31
32#[derive(Clone, Debug, Eq, PartialEq)]
33pub struct PcbBoardVariant {
34 pub name: String,
35 pub description: Option<String>,
36 pub source_range: Range<usize>,
37}
38
39#[derive(Clone, Debug, PartialEq)]
40pub struct PcbImage {
41 pub at: PcbPoint,
42 pub scale: f64,
43 pub layer: String,
44 pub locked: bool,
45 pub encoded_data_bytes: usize,
46 pub uuid: Option<String>,
47 pub source_range: Range<usize>,
48}
49
50#[derive(Clone, Debug, PartialEq)]
51pub struct PcbBarcode {
52 pub at: PcbPoint,
53 pub angle: f64,
54 pub layer: String,
55 pub width: f64,
56 pub height: f64,
57 pub text: String,
58 pub text_height: f64,
59 pub kind: String,
60 pub ecc_level: Option<String>,
61 pub locked: bool,
62 pub show_text: bool,
63 pub knockout: bool,
64 pub margins: PcbPoint,
65 pub uuid: Option<String>,
66 pub source_range: Range<usize>,
67}
68
69#[derive(Clone, Debug, PartialEq)]
70pub struct PcbTable {
71 pub column_count: i64,
72 pub layer: String,
73 pub border_external: bool,
74 pub border_header: bool,
75 pub separator_rows: bool,
76 pub separator_columns: bool,
77 pub column_widths: Vec<f64>,
78 pub row_heights: Vec<f64>,
79 pub cell_count: usize,
80 pub uuid: Option<String>,
81 pub source_range: Range<usize>,
82}
83
84#[derive(Clone, Debug, PartialEq)]
85pub struct PcbTableCell {
86 pub table_index: usize,
87 pub text: String,
88 pub start: PcbPoint,
89 pub end: PcbPoint,
90 pub margins: [f64; 4],
91 pub column_span: i64,
92 pub row_span: i64,
93 pub angle: f64,
94 pub layer: String,
95 pub locked: bool,
96 pub uuid: Option<String>,
97 pub source_range: Range<usize>,
98}
99
100impl<'a> PcbView<'a> {
101 pub fn paper(&self) -> Result<KiCadPaper, Error> {
104 let Some(span) = self.first_top_level("paper") else {
105 return Ok(KiCadPaper {
106 size: DEFAULT_PAPER.to_owned(),
107 width: None,
108 height: None,
109 portrait: false,
110 source_range: None,
111 });
112 };
113 let values = bounded_scalar_values(self.source, span, 4)?;
114 let size = values
115 .first()
116 .map(token_string)
117 .unwrap_or_else(|| DEFAULT_PAPER.to_owned());
118 let mut numeric = values
119 .iter()
120 .skip(1)
121 .filter(|value| token_string(value) != "portrait");
122 let width = numeric
123 .next()
124 .map(|value| parse_f64(value, span))
125 .transpose()?;
126 let height = numeric
127 .next()
128 .map(|value| parse_f64(value, span))
129 .transpose()?;
130 Ok(KiCadPaper {
131 size,
132 width,
133 height,
134 portrait: values.iter().any(|value| token_string(value) == "portrait"),
135 source_range: Some(span.range.clone()),
136 })
137 }
138
139 pub fn title_block(&self) -> Result<Option<KiCadTitleBlock>, Error> {
142 self.first_top_level("title_block")
143 .map(|span| title_block_from_span(self.source, span, self.limits))
144 .transpose()
145 }
146
147 pub fn declared_board_thickness(&self) -> Result<Option<f64>, Error> {
149 let Some(general) = self.first_top_level("general") else {
150 return Ok(None);
151 };
152 let children = direct_children(
153 self.source,
154 general,
155 self.limits.max_object_children,
156 self.limits,
157 )?;
158 let Some(declaration) = child(&children, "thickness") else {
159 return Ok(None);
160 };
161 let [value] = exact_finite_values(
162 self.source,
163 declaration,
164 self.limits,
165 "thickness requires exactly one finite numeric value",
166 )?;
167 Ok(Some(value))
168 }
169
170 pub fn metadata(&self) -> Result<PcbBoardMetadata, Error> {
171 let general = self.first_top_level("general");
172 let setup = self.first_top_level("setup");
173 Ok(PcbBoardMetadata {
174 version: self.top_level_i64("version")?.unwrap_or(DEFAULT_VERSION),
175 generator: self
176 .top_level_string("generator")?
177 .unwrap_or_else(|| DEFAULT_GENERATOR.to_owned()),
178 generator_version: self
179 .top_level_string("generator_version")?
180 .unwrap_or_else(|| DEFAULT_GENERATOR_VERSION.to_owned()),
181 paper: self.paper()?.size,
182 thickness: nested_f64(self.source, general, "thickness", self.limits)?
183 .unwrap_or(DEFAULT_THICKNESS),
184 legacy_teardrops: nested_bool(self.source, general, "legacy_teardrops", self.limits)?,
185 embedded_fonts: self
186 .top_level_string("embedded_fonts")?
187 .is_some_and(|value| value == "yes"),
188 pad_to_mask_clearance: nested_f64(
189 self.source,
190 setup,
191 "pad_to_mask_clearance",
192 self.limits,
193 )?
194 .unwrap_or(0.0),
195 pad_to_paste_clearance: nested_f64(
196 self.source,
197 setup,
198 "pad_to_paste_clearance",
199 self.limits,
200 )?
201 .unwrap_or(0.0),
202 pad_to_paste_clearance_ratio: nested_f64(
203 self.source,
204 setup,
205 "pad_to_paste_clearance_ratio",
206 self.limits,
207 )?
208 .unwrap_or(0.0),
209 })
210 }
211
212 pub fn variants(&self) -> impl Iterator<Item = Result<PcbBoardVariant, Error>> + '_ {
213 self.variants
214 .iter()
215 .filter(move |_| self.selection.contains(PcbFamily::Variants))
216 .map(|span| board_variant_from_span(self.source, span, self.limits))
217 }
218
219 pub fn images(&self) -> impl Iterator<Item = Result<PcbImage, Error>> + '_ {
220 self.images
221 .iter()
222 .filter(move |_| self.selection.contains(PcbFamily::Images))
223 .map(|span| image_from_span(self.source, span, self.limits))
224 }
225
226 pub(crate) fn image_data(&self, image: &PcbImage, maximum: usize) -> Result<String, Error> {
228 let span = self
229 .images
230 .iter()
231 .find(|span| span.range == image.source_range)
232 .ok_or_else(|| {
233 Error::at(
234 ErrorPhase::Tree,
235 ErrorKind::InvalidBuildValue,
236 "PCB image does not belong to this view",
237 Position::START,
238 )
239 })?;
240 let children = direct_children(
241 self.source,
242 span,
243 self.limits.max_object_children,
244 self.limits,
245 )?;
246 let Some(data) = child(&children, "data") else {
247 return Ok(String::new());
248 };
249 let values = bounded_scalar_values(self.source, data, self.limits.max_image_data_parts)?;
250 let mut output = String::new();
251 for token in values {
252 let remaining = maximum
253 .checked_sub(output.len())
254 .ok_or_else(image_limit_error)?;
255 let part = if token.kind == TokenKind::QuotedString {
256 decode_quoted_with_limit(token.lexeme, remaining).ok_or_else(image_limit_error)?
257 } else {
258 if token.lexeme.len() > remaining {
259 return Err(image_limit_error());
260 }
261 token.lexeme.to_owned()
262 };
263 output.push_str(&part);
264 }
265 Ok(output)
266 }
267
268 pub fn barcodes(&self) -> impl Iterator<Item = Result<PcbBarcode, Error>> + '_ {
269 self.barcodes
270 .iter()
271 .filter(move |_| self.selection.contains(PcbFamily::Barcodes))
272 .map(|span| barcode_from_span(self.source, span, self.limits))
273 }
274
275 pub fn tables(&self) -> impl Iterator<Item = Result<PcbTable, Error>> + '_ {
276 self.tables
277 .iter()
278 .filter(move |_| self.selection.contains(PcbFamily::Tables))
279 .map(|table| table_from_span(self.source, table, self.limits))
280 }
281
282 pub fn table_cells(&self) -> impl Iterator<Item = Result<PcbTableCell, Error>> + '_ {
283 self.table_cells
284 .iter()
285 .filter(move |_| self.selection.contains(PcbFamily::Tables))
286 .map(|indexed| table_cell_from_span(self.source, indexed, self.limits))
287 }
288
289 pub fn set_top_level_layer_by_id(
291 &self,
292 identifier: &str,
293 layer: &str,
294 ) -> Result<PcbEdit, Error> {
295 if self.source.len() > self.limits.max_output_bytes {
296 return Err(output_limit_error());
297 }
298 if identifier.is_empty() {
299 return Err(source_error(
300 "PCB object identifier cannot be empty",
301 self.root.start,
302 ));
303 }
304 let matches = self
305 .top_level
306 .iter()
307 .map(|span| Ok((span, top_level_identifier(self.source, span, self.limits)?)))
308 .filter_map(|result| match result {
309 Ok((span, Some(found))) if found == identifier => Some(Ok(span)),
310 Ok(_) => None,
311 Err(error) => Some(Err(error)),
312 })
313 .collect::<Result<Vec<_>, Error>>()?;
314 let [target] = matches.as_slice() else {
315 return Err(source_error(
316 if matches.is_empty() {
317 "PCB object identifier was not found"
318 } else {
319 "PCB object identifier is ambiguous"
320 },
321 self.root.start,
322 ));
323 };
324 let children = direct_children(
325 self.source,
326 target,
327 self.limits.max_object_children,
328 self.limits,
329 )?;
330 let layers: Vec<_> = children
331 .iter()
332 .filter(|child| child.head.as_deref() == Some("layer"))
333 .collect();
334 let [layer_span] = layers.as_slice() else {
335 return Err(source_error(
336 if layers.is_empty() {
337 "PCB object has no layer field"
338 } else {
339 "PCB object layer field is ambiguous"
340 },
341 target.start,
342 ));
343 };
344 let tokens = scalar_values(self.source, layer_span)?;
345 let token = tokens
346 .first()
347 .ok_or_else(|| source_error("PCB object layer has no value", layer_span.end))?;
348 if token_string(token) == layer {
349 return Ok(PcbEdit {
350 source: self.source.to_owned(),
351 changed: false,
352 });
353 }
354 let replacement = build_with_limit(
355 &Sexp::Quoted(layer.to_owned()),
356 self.limits.max_output_bytes,
357 )?;
358 Ok(PcbEdit {
359 source: apply_patches_with_limit(
360 self.source,
361 &[Patch::new(
362 layer_span.range.start + token.position.offset,
363 layer_span.range.start + token.position.offset + token.lexeme.len(),
364 replacement,
365 )],
366 self.limits.max_output_bytes,
367 )?,
368 changed: true,
369 })
370 }
371
372 pub(super) fn first_top_level(&self, head: &str) -> Option<&FormSpan> {
373 self.top_level
374 .iter()
375 .find(|span| span.head.as_deref() == Some(head))
376 }
377
378 fn top_level_string(&self, head: &str) -> Result<Option<String>, Error> {
379 self.first_top_level(head)
380 .map(|span| first_string(self.source, span))
381 .transpose()
382 .map(Option::flatten)
383 }
384
385 fn top_level_i64(&self, head: &str) -> Result<Option<i64>, Error> {
386 let Some(span) = self.first_top_level(head) else {
387 return Ok(None);
388 };
389 let values = scalar_values(self.source, span)?;
390 values
391 .first()
392 .map(|token| parse_i64(token, span))
393 .transpose()
394 }
395}
396
397fn title_block_from_span(
398 source: &str,
399 span: &FormSpan,
400 limits: PcbLimits,
401) -> Result<KiCadTitleBlock, Error> {
402 let children = direct_children(source, span, limits.max_title_block_children, limits)?;
403 let mut comments = BTreeMap::new();
404 for comment in children
405 .iter()
406 .filter(|child| child.head.as_deref() == Some("comment"))
407 {
408 let values = bounded_scalar_values(source, comment, 2)?;
409 if values.len() < 2 {
410 continue;
411 }
412 let number = parse_i64(&values[0], comment)?;
413 if !comments.contains_key(&number) && comments.len() >= limits.max_title_block_comments {
414 return Err(limit_error());
415 }
416 comments.insert(number, token_string(&values[1]));
417 }
418 Ok(KiCadTitleBlock {
419 title: optional_child_string(source, &children, "title")?.unwrap_or_default(),
420 date: optional_child_string(source, &children, "date")?.unwrap_or_default(),
421 revision: optional_child_string(source, &children, "rev")?.unwrap_or_default(),
422 company: optional_child_string(source, &children, "company")?.unwrap_or_default(),
423 comments,
424 source_range: span.range.clone(),
425 })
426}
427
428pub(super) fn index_variants(
429 source: &str,
430 span: &FormSpan,
431 limits: PcbLimits,
432 index: &mut PcbIndex,
433) -> Result<(), Error> {
434 let children = direct_children(source, span, limits.max_variants, limits)?;
435 for child in children
436 .into_iter()
437 .filter(|child| child.head.as_deref() == Some("variant"))
438 {
439 bounded_push(&mut index.variants, child, limits.max_variants)?;
440 }
441 index.counts.variants = index.variants.len();
442 Ok(())
443}
444
445pub(super) fn index_table(
446 source: &str,
447 span: &FormSpan,
448 limits: PcbLimits,
449 index: &mut PcbIndex,
450) -> Result<(), Error> {
451 if index.tables.len() >= limits.max_tables {
452 return Err(limit_error());
453 }
454 let table_index = index.tables.len();
455 let cell_start = index.table_cells.len();
456 let children = direct_children(source, span, limits.max_object_children, limits)?;
457 let Some(cells) = child(&children, "cells") else {
458 bounded_push(
459 &mut index.tables,
460 IndexedTable {
461 span: span.clone(),
462 cell_range: cell_start..cell_start,
463 },
464 limits.max_tables,
465 )?;
466 index.counts.tables += 1;
467 return Ok(());
468 };
469 for cell in direct_children(source, cells, limits.max_table_cells, limits)?
470 .into_iter()
471 .filter(|cell| cell.head.as_deref() == Some("table_cell"))
472 {
473 bounded_push(
474 &mut index.table_cells,
475 IndexedNestedForm {
476 parent_index: table_index,
477 span: cell,
478 },
479 limits.max_table_cells,
480 )?;
481 }
482 let cell_end = index.table_cells.len();
483 bounded_push(
484 &mut index.tables,
485 IndexedTable {
486 span: span.clone(),
487 cell_range: cell_start..cell_end,
488 },
489 limits.max_tables,
490 )?;
491 index.counts.tables += 1;
492 index.counts.table_cells = index.table_cells.len();
493 Ok(())
494}
495
496fn board_variant_from_span(
497 source: &str,
498 span: &FormSpan,
499 limits: PcbLimits,
500) -> Result<PcbBoardVariant, Error> {
501 let children = direct_children(source, span, limits.max_object_children, limits)?;
502 Ok(PcbBoardVariant {
503 name: optional_child_string(source, &children, "name")?.unwrap_or_default(),
504 description: optional_child_string(source, &children, "description")?
505 .filter(|value| !value.is_empty()),
506 source_range: span.range.clone(),
507 })
508}
509
510fn image_from_span(source: &str, span: &FormSpan, limits: PcbLimits) -> Result<PcbImage, Error> {
511 let children = direct_children(source, span, limits.max_object_children, limits)?;
512 let at = optional_point(source, &children, "at")?.unwrap_or(PcbPoint { x: 0.0, y: 0.0 });
513 Ok(PcbImage {
514 at,
515 scale: optional_child_f64(source, &children, "scale")?.unwrap_or(1.0),
516 layer: optional_child_string(source, &children, "layer")?
517 .unwrap_or_else(|| "F.SilkS".to_owned()),
518 locked: nested_bool(source, Some(span), "locked", limits)?,
519 encoded_data_bytes: joined_data_bytes(source, &children, limits)?,
520 uuid: optional_uuid(source, &children)?,
521 source_range: span.range.clone(),
522 })
523}
524
525fn barcode_from_span(
526 source: &str,
527 span: &FormSpan,
528 limits: PcbLimits,
529) -> Result<PcbBarcode, Error> {
530 let children = direct_children(source, span, limits.max_object_children, limits)?;
531 let at_values = child_values(source, &children, "at")?;
532 let size = pair_or(source, &children, "size", [0.0, 0.0])?;
533 let margins = pair_or(source, &children, "margins", [0.0, 0.0])?;
534 Ok(PcbBarcode {
535 at: PcbPoint {
536 x: numeric_at(&at_values, 0, 0.0, span)?,
537 y: numeric_at(&at_values, 1, 0.0, span)?,
538 },
539 angle: numeric_at(&at_values, 2, 0.0, span)?,
540 layer: optional_child_string(source, &children, "layer")?
541 .unwrap_or_else(|| "F.SilkS".to_owned()),
542 width: size[0],
543 height: size[1],
544 text: optional_child_string(source, &children, "text")?.unwrap_or_default(),
545 text_height: optional_child_f64(source, &children, "text_height")?.unwrap_or(1.0),
546 kind: optional_child_string(source, &children, "type")?
547 .unwrap_or_else(|| "code39".to_owned()),
548 ecc_level: optional_child_string(source, &children, "ecc_level")?
549 .filter(|value| !value.is_empty()),
550 locked: nested_bool(source, Some(span), "locked", limits)?,
551 show_text: !nested_bool(source, Some(span), "hide", limits)?,
552 knockout: nested_bool(source, Some(span), "knockout", limits)?,
553 margins: PcbPoint {
554 x: margins[0],
555 y: margins[1],
556 },
557 uuid: optional_uuid(source, &children)?,
558 source_range: span.range.clone(),
559 })
560}
561
562fn table_from_span(
563 source: &str,
564 indexed: &IndexedTable,
565 limits: PcbLimits,
566) -> Result<PcbTable, Error> {
567 let span = &indexed.span;
568 let children = direct_children(source, span, limits.max_object_children, limits)?;
569 let border = child(&children, "border");
570 let separators = child(&children, "separators");
571 Ok(PcbTable {
572 column_count: optional_child_i64(source, &children, "column_count")?.unwrap_or(1),
573 layer: optional_child_string(source, &children, "layer")?
574 .unwrap_or_else(|| "F.Cu".to_owned()),
575 border_external: nested_named_bool(source, border, "external", true, limits)?,
576 border_header: nested_named_bool(source, border, "header", false, limits)?,
577 separator_rows: nested_named_bool(source, separators, "rows", true, limits)?,
578 separator_columns: nested_named_bool(source, separators, "cols", true, limits)?,
579 column_widths: numeric_list(source, &children, "column_widths", limits)?,
580 row_heights: numeric_list(source, &children, "row_heights", limits)?,
581 cell_count: indexed.cell_range.len(),
582 uuid: optional_uuid(source, &children)?,
583 source_range: span.range.clone(),
584 })
585}
586
587fn table_cell_from_span(
588 source: &str,
589 indexed: &IndexedNestedForm,
590 limits: PcbLimits,
591) -> Result<PcbTableCell, Error> {
592 let header = scalar_values(source, &indexed.span)?;
593 let children = direct_children(source, &indexed.span, limits.max_object_children, limits)?;
594 let margins = numeric_array(source, &children, "margins", [0.0; 4])?;
595 let span_values = integer_pair(source, &children, "span", [1, 1])?;
596 Ok(PcbTableCell {
597 table_index: indexed.parent_index,
598 text: header.first().map(token_string).unwrap_or_default(),
599 start: optional_point(source, &children, "start")?.unwrap_or(PcbPoint { x: 0.0, y: 0.0 }),
600 end: optional_point(source, &children, "end")?.unwrap_or(PcbPoint { x: 0.0, y: 0.0 }),
601 margins,
602 column_span: span_values[0],
603 row_span: span_values[1],
604 angle: optional_child_f64(source, &children, "angle")?.unwrap_or(0.0),
605 layer: optional_child_string(source, &children, "layer")?
606 .unwrap_or_else(|| "F.Cu".to_owned()),
607 locked: nested_bool(source, Some(&indexed.span), "locked", limits)?,
608 uuid: optional_uuid(source, &children)?,
609 source_range: indexed.span.range.clone(),
610 })
611}
612
613fn nested_f64(
614 source: &str,
615 parent: Option<&FormSpan>,
616 head: &str,
617 limits: PcbLimits,
618) -> Result<Option<f64>, Error> {
619 let Some(parent) = parent else {
620 return Ok(None);
621 };
622 let children = direct_children(source, parent, limits.max_object_children, limits)?;
623 optional_child_f64(source, &children, head)
624}
625
626fn nested_bool(
627 source: &str,
628 parent: Option<&FormSpan>,
629 head: &str,
630 limits: PcbLimits,
631) -> Result<bool, Error> {
632 nested_named_bool(source, parent, head, false, limits)
633}
634
635fn nested_named_bool(
636 source: &str,
637 parent: Option<&FormSpan>,
638 head: &str,
639 default: bool,
640 limits: PcbLimits,
641) -> Result<bool, Error> {
642 let Some(parent) = parent else {
643 return Ok(default);
644 };
645 let children = direct_children(source, parent, limits.max_object_children, limits)?;
646 let Some(field) = child(&children, head) else {
647 return Ok(false);
648 };
649 let values = scalar_values(source, field)?;
650 Ok(values
651 .first()
652 .is_some_and(|value| matches!(token_string(value).as_str(), "yes" | "true" | "1")))
653}
654
655fn optional_point(
656 source: &str,
657 children: &[FormSpan],
658 head: &str,
659) -> Result<Option<PcbPoint>, Error> {
660 let Some(span) = child(children, head) else {
661 return Ok(None);
662 };
663 let values = scalar_values(source, span)?;
664 Ok(Some(PcbPoint {
665 x: numeric_at(&values, 0, 0.0, span)?,
666 y: numeric_at(&values, 1, 0.0, span)?,
667 }))
668}
669
670fn child_values<'a>(
671 source: &'a str,
672 children: &[FormSpan],
673 head: &str,
674) -> Result<Vec<Token<'a>>, Error> {
675 child(children, head)
676 .map(|span| scalar_values(source, span))
677 .transpose()
678 .map(Option::unwrap_or_default)
679}
680
681fn numeric_at(
682 values: &[Token<'_>],
683 index: usize,
684 default: f64,
685 span: &FormSpan,
686) -> Result<f64, Error> {
687 optional_f64(values.get(index), span).map(|value| value.unwrap_or(default))
688}
689
690fn pair_or(
691 source: &str,
692 children: &[FormSpan],
693 head: &str,
694 default: [f64; 2],
695) -> Result<[f64; 2], Error> {
696 let Some(span) = child(children, head) else {
697 return Ok(default);
698 };
699 let values = scalar_values(source, span)?;
700 Ok([
701 numeric_at(&values, 0, default[0], span)?,
702 numeric_at(&values, 1, default[1], span)?,
703 ])
704}
705
706fn numeric_array<const N: usize>(
707 source: &str,
708 children: &[FormSpan],
709 head: &str,
710 default: [f64; N],
711) -> Result<[f64; N], Error> {
712 let Some(span) = child(children, head) else {
713 return Ok(default);
714 };
715 let values = scalar_values(source, span)?;
716 let mut result = default;
717 for (index, output) in result.iter_mut().enumerate() {
718 *output = numeric_at(&values, index, *output, span)?;
719 }
720 Ok(result)
721}
722
723fn integer_pair(
724 source: &str,
725 children: &[FormSpan],
726 head: &str,
727 default: [i64; 2],
728) -> Result<[i64; 2], Error> {
729 let Some(span) = child(children, head) else {
730 return Ok(default);
731 };
732 let values = scalar_values(source, span)?;
733 Ok([
734 values
735 .first()
736 .map(|value| parse_i64(value, span))
737 .transpose()?
738 .unwrap_or(default[0]),
739 values
740 .get(1)
741 .map(|value| parse_i64(value, span))
742 .transpose()?
743 .unwrap_or(default[1]),
744 ])
745}
746
747fn numeric_list(
748 source: &str,
749 children: &[FormSpan],
750 head: &str,
751 limits: PcbLimits,
752) -> Result<Vec<f64>, Error> {
753 let Some(span) = child(children, head) else {
754 return Ok(Vec::new());
755 };
756 let values = bounded_scalar_values(source, span, limits.max_table_values)?;
757 values.iter().map(|value| parse_f64(value, span)).collect()
758}
759
760fn joined_data_bytes(
761 source: &str,
762 children: &[FormSpan],
763 limits: PcbLimits,
764) -> Result<usize, Error> {
765 let Some(data) = child(children, "data") else {
766 return Ok(0);
767 };
768 let values = bounded_scalar_values(source, data, limits.max_image_data_parts)?;
769 values.iter().try_fold(0_usize, |total, token| {
770 let length = if token.kind == TokenKind::QuotedString {
771 token.lexeme.len().saturating_sub(2)
772 } else {
773 token.lexeme.len()
774 };
775 total.checked_add(length).ok_or_else(image_limit_error)
776 })
777}
778
779fn image_limit_error() -> Error {
780 Error::at(
781 ErrorPhase::Tree,
782 ErrorKind::ResourceLimit,
783 "PCB image data exceeds configured limits",
784 Position::START,
785 )
786}