cadmpeg-ir 0.6.2

CAD data model, validation, diffing, and codec API for cadmpeg.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
// SPDX-License-Identifier: Apache-2.0
//! Sampled curves and polygonal surfaces with checked sample layouts.

use crate::features::FinitePoint3;
use crate::math::Point3;
use crate::scalar::{FiniteReal, NonNegativeReal, PositiveReal};
#[cfg(feature = "schema")]
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

/// Structural error in a sampled polyline or polygonal carrier.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum GeometryLayoutError {
    /// A sample or vertex layout the carrier cannot state. The carrier states
    /// this case; an outside caller states only [`Self::EditRefused`].
    #[non_exhaustive]
    Layout(String),
    /// An edit closure refused the value it was given, stating its own reason.
    EditRefused(String),
}

impl std::fmt::Display for GeometryLayoutError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Layout(message) | Self::EditRefused(message) => formatter.write_str(message),
        }
    }
}

impl std::error::Error for GeometryLayoutError {}

fn geometry_layout_error(message: impl Into<String>) -> GeometryLayoutError {
    GeometryLayoutError::Layout(message.into())
}

/// Admit a recorded chordal deviation that is finite and non-negative.
fn admit_chordal_deflection(
    chordal_deflection: f64,
) -> Result<NonNegativeReal, GeometryLayoutError> {
    NonNegativeReal::new(chordal_deflection)
        .ok_or_else(|| geometry_layout_error("chordal_deflection must be finite and non-negative"))
}

fn layout_error(message: &'static str) -> GeometryLayoutError {
    GeometryLayoutError::Layout(message.into())
}

/// Admit polygonal-surface vertices whose every coordinate is finite.
fn admit_finite_vertices(vertices: Vec<Point3>) -> Result<Vec<FinitePoint3>, GeometryLayoutError> {
    vertices
        .into_iter()
        .map(|point| match FinitePoint3::new(point) {
            Some(point) => Ok(point),
            None => Err(layout_error("vertices must be finite")),
        })
        .collect::<Result<Vec<_>, _>>()
}

/// Source-native polygonal surface with an explicit chordal error bound.
#[derive(Debug, Clone, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
pub struct PolygonalSurface {
    #[cfg_attr(feature = "schema", schemars(with = "Vec<Point3>"))]
    vertices: Vec<FinitePoint3>,
    triangles: Vec<[u32; 3]>,
    #[cfg_attr(feature = "schema", schemars(with = "f64"))]
    chordal_deflection: NonNegativeReal,
}

impl PolygonalSurface {
    /// Admitted polygon vertices in source order.
    pub fn vertices(&self) -> &[FinitePoint3] {
        &self.vertices
    }

    /// Triangle vertex indexes in source order.
    pub fn triangles(&self) -> &[[u32; 3]] {
        &self.triangles
    }

    /// Build a polygonal surface whose triangle indices address `vertices`.
    pub fn new(
        vertices: Vec<Point3>,
        triangles: Vec<[u32; 3]>,
        chordal_deflection: f64,
    ) -> Result<Self, GeometryLayoutError> {
        Self::build(vertices, triangles, admit_finite_vertices, || {
            NonNegativeReal::new(chordal_deflection)
        })
    }

    /// Build from admitted source deflection and placement scale.
    pub fn from_scaled_deflection(
        vertices: Vec<Point3>,
        triangles: Vec<[u32; 3]>,
        chordal_deflection: NonNegativeReal,
        scale: PositiveReal,
    ) -> Result<Self, GeometryLayoutError> {
        Self::build(vertices, triangles, admit_finite_vertices, || {
            chordal_deflection.scaled(scale)
        })
    }

    /// Build from admitted vertices, source deflection and placement scale.
    /// Only triangle relationships and scaled deflection remain to check.
    pub fn from_admitted_scaled_deflection(
        vertices: Vec<FinitePoint3>,
        triangles: Vec<[u32; 3]>,
        chordal_deflection: NonNegativeReal,
        scale: PositiveReal,
    ) -> Result<Self, GeometryLayoutError> {
        Self::build(vertices, triangles, Ok, || chordal_deflection.scaled(scale))
    }

    fn build<P>(
        vertices: Vec<P>,
        triangles: Vec<[u32; 3]>,
        convert: impl FnOnce(Vec<P>) -> Result<Vec<FinitePoint3>, GeometryLayoutError>,
        deflection: impl FnOnce() -> Option<NonNegativeReal>,
    ) -> Result<Self, GeometryLayoutError> {
        Self::check_layout(vertices.len(), &triangles)?;
        let vertices = convert(vertices)?;
        let Some(chordal_deflection) = deflection() else {
            return Err(layout_error(
                "chordal_deflection must be finite and non-negative",
            ));
        };
        Ok(Self {
            vertices,
            triangles,
            chordal_deflection,
        })
    }

    fn check_layout(
        vertex_count: usize,
        triangles: &[[u32; 3]],
    ) -> Result<(), GeometryLayoutError> {
        if vertex_count < 3 {
            return Err(layout_error(
                "polygonal surface must contain at least three vertices",
            ));
        }
        if triangles.is_empty() {
            return Err(layout_error(
                "polygonal surface must contain at least one triangle",
            ));
        }
        for index in triangles.iter().flatten() {
            if usize::try_from(*index).map_or(true, |index| index >= vertex_count) {
                return Err(layout_error(
                    "polygonal surface contains an out-of-range triangle index",
                ));
            }
        }
        Ok(())
    }

    /// Edit finite vertices transactionally.
    ///
    /// The closure states its own refusal, which discards the whole edit.
    /// The edit keeps the vertex count and the triangles, so only the edited
    /// coordinates are admitted again.
    pub fn edit_vertices(
        &mut self,
        edit: impl FnOnce(&mut [Point3]) -> Result<(), GeometryLayoutError>,
    ) -> Result<(), GeometryLayoutError> {
        let mut candidate: Vec<Point3> = self.vertices.iter().map(|point| point.get()).collect();
        edit(&mut candidate)?;
        self.vertices = admit_finite_vertices(candidate)?;
        Ok(())
    }

    /// Maximum chordal deviation recorded by the source.
    #[must_use]
    pub const fn chordal_deflection(&self) -> NonNegativeReal {
        self.chordal_deflection
    }

    /// Set the recorded chordal deviation.
    pub fn set_chordal_deflection(
        &mut self,
        chordal_deflection: f64,
    ) -> Result<(), GeometryLayoutError> {
        self.chordal_deflection = admit_chordal_deflection(chordal_deflection)?;
        Ok(())
    }
}

impl<'de> Deserialize<'de> for PolygonalSurface {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[derive(Deserialize)]
        #[serde(deny_unknown_fields)]
        struct Wire {
            vertices: Vec<Point3>,
            triangles: Vec<[u32; 3]>,
            chordal_deflection: f64,
        }

        let wire = Wire::deserialize(deserializer)?;
        Self::build(wire.vertices, wire.triangles, admit_finite_vertices, || {
            NonNegativeReal::new(wire.chordal_deflection)
        })
        .map_err(serde::de::Error::custom)
    }
}

/// One polyline sample with the source parameter recorded at it.
// A source states a raw parameter and point; a `PolylineCurve` holds the
// admitted sample, whose parameter is a `FiniteReal` and whose point is a
// `FinitePoint3`.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct PolylineVertex<R = f64, P = Point3> {
    /// Source parameter at this sample.
    pub parameter: R,
    /// Model-space sample.
    pub point: P,
}

/// The samples of a polyline, with or without source parameters.
///
/// A parameterized polyline carries one parameter per sample in the sample
/// row, so a parameter list that does not match the sample count has no
/// spelling.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(tag = "kind", rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
pub enum PolylineSamples<R = f64, P = Point3> {
    /// Samples the source did not parameterize.
    Unparameterized {
        /// Ordered model-space samples.
        points: crate::features::NonEmptyMembers<P>,
    },
    /// Samples the source parameterized.
    Parameterized {
        /// Ordered samples, each with its source parameter.
        vertices: crate::features::NonEmptyMembers<PolylineVertex<R, P>>,
    },
}

/// Source-native polyline with an explicit chordal error bound.
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[cfg_attr(feature = "schema", schemars(with = "PolylineCurveWire"))]
#[serde(try_from = "PolylineCurveWire")]
pub struct PolylineCurve {
    samples: PolylineSamples<FiniteReal, FinitePoint3>,
    chordal_deflection: NonNegativeReal,
}

#[derive(Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
struct PolylineCurveWire {
    /// The polyline's sample rows.
    samples: PolylineSamples,
    /// Maximum chordal deviation recorded by the source.
    chordal_deflection: f64,
}

/// The written form of a polyline, borrowing its admitted samples.
#[derive(Serialize)]
struct PolylineCurveWriteWire<'a> {
    samples: &'a PolylineSamples<FiniteReal, FinitePoint3>,
    chordal_deflection: NonNegativeReal,
}

impl Serialize for PolylineCurve {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        PolylineCurveWriteWire {
            samples: &self.samples,
            chordal_deflection: self.chordal_deflection,
        }
        .serialize(serializer)
    }
}

impl TryFrom<PolylineCurveWire> for PolylineCurve {
    type Error = GeometryLayoutError;

    fn try_from(wire: PolylineCurveWire) -> Result<Self, Self::Error> {
        Self::build(wire.samples, || {
            NonNegativeReal::new(wire.chordal_deflection)
        })
    }
}

impl<R, P> PolylineSamples<R, P> {
    /// Number of samples. The sample list is nonempty by type.
    #[must_use]
    pub fn count(&self) -> usize {
        match self {
            Self::Unparameterized { points } => points.len(),
            Self::Parameterized { vertices } => vertices.len(),
        }
    }
}

impl<R: Copy, P: Copy> PolylineSamples<R, P> {
    /// Ordered model-space samples.
    pub fn points(&self) -> impl Iterator<Item = P> + '_ {
        let (points, vertices) = match self {
            Self::Unparameterized { points } => (Some(points), None),
            Self::Parameterized { vertices } => (None, Some(vertices)),
        };
        points
            .into_iter()
            .flatten()
            .copied()
            .chain(vertices.into_iter().flatten().map(|vertex| vertex.point))
    }

    /// Source parameters, absent when the source stated none.
    pub fn parameters(&self) -> Option<impl Iterator<Item = R> + '_> {
        match self {
            Self::Unparameterized { .. } => None,
            Self::Parameterized { vertices } => {
                Some(vertices.iter().map(|vertex| vertex.parameter))
            }
        }
    }
}

impl PolylineSamples {
    /// Edit each sample point, keeping the prior points on a refusal.
    ///
    /// The closure states its own refusal, which discards the whole edit.
    pub fn edit_points(
        &mut self,
        mut edit: impl FnMut(&mut Point3) -> Result<(), GeometryLayoutError>,
    ) -> Result<(), GeometryLayoutError> {
        let mut candidate = self.clone();
        match &mut candidate {
            Self::Unparameterized { points } => {
                for point in points.iter_mut() {
                    edit(point)?;
                }
            }
            Self::Parameterized { vertices } => {
                for vertex in vertices.iter_mut() {
                    edit(&mut vertex.point)?;
                }
            }
        }
        *self = candidate;
        Ok(())
    }
}

impl PolylineSamples<FiniteReal, FinitePoint3> {
    fn has_strictly_monotonic_parameters(&self) -> bool {
        let Self::Parameterized { vertices } = self else {
            return true;
        };
        let mut increasing = true;
        for pair in vertices.windows(2) {
            if pair[0].parameter >= pair[1].parameter {
                increasing = false;
                break;
            }
        }
        if increasing {
            return true;
        }
        for pair in vertices.windows(2) {
            if pair[0].parameter <= pair[1].parameter {
                return false;
            }
        }
        true
    }

    /// Edit admitted points transactionally. The edit supplies an admitted
    /// point, so no coordinate needs another admission.
    pub fn edit_admitted_points<E>(
        &mut self,
        mut edit: impl FnMut(FinitePoint3) -> Result<FinitePoint3, E>,
    ) -> Result<(), E> {
        match self {
            Self::Unparameterized { points } => edit_sample_rows(points, |point| {
                *point = edit(*point)?;
                Ok(())
            }),
            Self::Parameterized { vertices } => edit_sample_rows(vertices, |vertex| {
                vertex.point = edit(vertex.point)?;
                Ok(())
            }),
        }
    }

    /// The samples with raw parameters and points.
    #[must_use]
    pub fn to_raw(&self) -> PolylineSamples {
        match self {
            Self::Unparameterized { points } => PolylineSamples::Unparameterized {
                points: points.clone().map(FinitePoint3::get),
            },
            Self::Parameterized { vertices } => PolylineSamples::Parameterized {
                vertices: vertices.clone().map(|vertex| PolylineVertex {
                    parameter: vertex.parameter.get(),
                    point: vertex.point.get(),
                }),
            },
        }
    }
}

fn edit_sample_rows<T: Copy, E>(
    rows: &mut [T],
    mut edit: impl FnMut(&mut T) -> Result<(), E>,
) -> Result<(), E> {
    let mut candidate = rows.to_vec();
    for row in &mut candidate {
        edit(row)?;
    }

    rows.copy_from_slice(&candidate);
    Ok(())
}

impl PolylineCurve {
    /// Build from admitted sample scalars and points, checking only the
    /// sample count, computed deviation, and parameter order.
    pub fn from_checked_samples(
        samples: PolylineSamples<FiniteReal, FinitePoint3>,
        chordal_deflection: f64,
    ) -> Result<Self, GeometryLayoutError> {
        Self::build_checked_samples(samples, || NonNegativeReal::new(chordal_deflection))
    }

    fn build_checked_samples(
        samples: PolylineSamples<FiniteReal, FinitePoint3>,
        deflection: impl FnOnce() -> Option<NonNegativeReal>,
    ) -> Result<Self, GeometryLayoutError> {
        Self::require_sample_count(samples.count())?;
        let chordal_deflection = Self::admit_deflection(deflection())?;
        if !samples.has_strictly_monotonic_parameters() {
            return Err(layout_error(
                "parameters must be finite and strictly monotonic",
            ));
        }
        Ok(Self {
            samples,
            chordal_deflection,
        })
    }

    /// Build a polyline from its sample rows.
    ///
    /// A parameterized sample carries its parameter in the row, so there is no
    /// second list to pair up and no count to compare.
    pub fn new(
        samples: PolylineSamples,
        chordal_deflection: f64,
    ) -> Result<Self, GeometryLayoutError> {
        Self::build(samples, || NonNegativeReal::new(chordal_deflection))
    }

    /// Build from admitted source deflection and placement scale.
    pub fn from_scaled_deflection(
        samples: PolylineSamples<FiniteReal, FinitePoint3>,
        chordal_deflection: NonNegativeReal,
        scale: PositiveReal,
    ) -> Result<Self, GeometryLayoutError> {
        Self::build_checked_samples(samples, || chordal_deflection.scaled(scale))
    }

    fn build(
        samples: PolylineSamples,
        deflection: impl FnOnce() -> Option<NonNegativeReal>,
    ) -> Result<Self, GeometryLayoutError> {
        Self::admit_sample_points(&samples)?;
        let chordal_deflection = Self::admit_deflection(deflection())?;
        let samples = Self::admit_sample_parameters(samples)?;
        Ok(Self {
            samples,
            chordal_deflection,
        })
    }

    fn require_sample_count(count: usize) -> Result<(), GeometryLayoutError> {
        if count < 2 {
            return Err(layout_error("polyline must contain at least two points"));
        }
        Ok(())
    }

    fn admit_deflection(
        value: Option<NonNegativeReal>,
    ) -> Result<NonNegativeReal, GeometryLayoutError> {
        match value {
            Some(value) => Ok(value),
            None => Err(layout_error(
                "chordal_deflection must be finite and non-negative",
            )),
        }
    }

    /// Check point finiteness before deflection and parameter admission.
    fn admit_sample_points(samples: &PolylineSamples) -> Result<(), GeometryLayoutError> {
        Self::require_sample_count(samples.count())?;
        for index in 0..samples.count() {
            let point = match samples {
                PolylineSamples::Unparameterized { points } => points[index],
                PolylineSamples::Parameterized { vertices } => vertices[index].point,
            };
            if !point.is_finite() {
                return Err(layout_error("points must be finite"));
            }
        }
        Ok(())
    }

    /// Convert final sample rows once after all source points pass admission.
    fn admit_sample_parameters(
        samples: PolylineSamples,
    ) -> Result<PolylineSamples<FiniteReal, FinitePoint3>, GeometryLayoutError> {
        fn members<T>(
            values: Vec<T>,
        ) -> Result<crate::features::NonEmptyMembers<T>, GeometryLayoutError> {
            match values.try_into() {
                Ok(values) => Ok(values),
                Err(_) => Err(layout_error("polyline must contain at least two points")),
            }
        }
        let point = |point| match FinitePoint3::new(point) {
            Some(point) => Ok(point),
            None => Err(layout_error("points must be finite")),
        };
        let samples = match samples {
            PolylineSamples::Unparameterized { points } => PolylineSamples::Unparameterized {
                points: members(
                    points
                        .into_iter()
                        .map(point)
                        .collect::<Result<Vec<_>, _>>()?,
                )?,
            },
            PolylineSamples::Parameterized { vertices } => PolylineSamples::Parameterized {
                vertices: members(
                    vertices
                        .into_iter()
                        .map(|vertex| {
                            let Some(parameter) = FiniteReal::new(vertex.parameter) else {
                                return Err(layout_error(
                                    "parameters must be finite and strictly monotonic",
                                ));
                            };
                            Ok(PolylineVertex {
                                parameter,
                                point: point(vertex.point)?,
                            })
                        })
                        .collect::<Result<Vec<_>, _>>()?,
                )?,
            },
        };
        if !samples.has_strictly_monotonic_parameters() {
            return Err(layout_error(
                "parameters must be finite and strictly monotonic",
            ));
        }
        Ok(samples)
    }

    /// Ordered admitted model-space samples.
    pub fn points(&self) -> impl Iterator<Item = FinitePoint3> + '_ {
        self.samples.points()
    }

    /// Number of samples.
    #[must_use]
    pub fn point_count(&self) -> usize {
        self.samples.count()
    }

    /// One admitted point without collecting the sample lane.
    #[must_use]
    pub fn point_at(&self, index: usize) -> Option<FinitePoint3> {
        match &self.samples {
            PolylineSamples::Unparameterized { points } => points.get(index).copied(),
            PolylineSamples::Parameterized { vertices } => vertices.get(index).map(|row| row.point),
        }
    }

    /// One source parameter, or the sample index when none was stated.
    #[must_use]
    pub fn parameter_at(&self, index: usize) -> Option<FiniteReal> {
        match &self.samples {
            PolylineSamples::Unparameterized { points } => points
                .get(index)
                .and_then(|_| FiniteReal::from_index(index)),
            PolylineSamples::Parameterized { vertices } => {
                vertices.get(index).map(|row| row.parameter)
            }
        }
    }

    /// Admitted source parameters, absent when the source stated none.
    pub fn parameters(&self) -> Option<impl Iterator<Item = FiniteReal> + '_> {
        self.samples.parameters()
    }

    /// Edit the raw sample rows transactionally and admit the result.
    ///
    /// The closure states its own refusal, which discards the whole edit.
    pub fn edit_samples(
        &mut self,
        edit: impl FnOnce(&mut PolylineSamples) -> Result<(), GeometryLayoutError>,
    ) -> Result<(), GeometryLayoutError> {
        let mut candidate = self.samples.to_raw();
        edit(&mut candidate)?;
        Self::admit_sample_points(&candidate)?;
        self.samples = Self::admit_sample_parameters(candidate)?;
        Ok(())
    }

    /// Maximum chordal deviation recorded by the source.
    #[must_use]
    pub const fn chordal_deflection(&self) -> NonNegativeReal {
        self.chordal_deflection
    }

    /// Set the recorded chordal deviation.
    pub fn set_chordal_deflection(
        &mut self,
        chordal_deflection: f64,
    ) -> Result<(), GeometryLayoutError> {
        self.chordal_deflection = admit_chordal_deflection(chordal_deflection)?;
        Ok(())
    }
}

fn scale_admitted_points<'a>(
    points: impl Iterator<Item = &'a mut FinitePoint3>,
    scale: PositiveReal,
    message: &'static str,
) -> Result<(), GeometryLayoutError> {
    for point in points {
        *point = point
            .scaled(scale)
            .ok_or_else(|| GeometryLayoutError::Layout(message.to_owned()))?;
    }
    Ok(())
}

fn scale_admitted_deflection(
    deflection: &mut NonNegativeReal,
    scale: PositiveReal,
) -> Result<(), GeometryLayoutError> {
    *deflection = deflection.scaled(scale).ok_or_else(|| {
        GeometryLayoutError::Layout("chordal_deflection must be finite and non-negative".to_owned())
    })?;
    Ok(())
}

impl PolygonalSurface {
    pub(crate) fn scale_points(&mut self, scale: PositiveReal) -> Result<(), GeometryLayoutError> {
        scale_admitted_points(self.vertices.iter_mut(), scale, "vertices must be finite")?;
        scale_admitted_deflection(&mut self.chordal_deflection, scale)
    }
}

impl PolylineCurve {
    pub(crate) fn scale_points(&mut self, scale: PositiveReal) -> Result<(), GeometryLayoutError> {
        match &mut self.samples {
            PolylineSamples::Unparameterized { points } => {
                scale_admitted_points(points.iter_mut(), scale, "points must be finite")
            }
            PolylineSamples::Parameterized { vertices } => scale_admitted_points(
                vertices.iter_mut().map(|vertex| &mut vertex.point),
                scale,
                "points must be finite",
            ),
        }?;
        scale_admitted_deflection(&mut self.chordal_deflection, scale)
    }
}

#[cfg(test)]
mod tests;

mod identity_rewrite;