cadmpeg-ir 0.6.1

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
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
// SPDX-License-Identifier: Apache-2.0
//! Provenance and exactness value types.
//!
//! [`Exactness`] classifies how an IR value relates to source bytes. Current
//! documents store exactness and source locations in
//! [`crate::annotations::Annotations`].

#[cfg(feature = "schema")]
use schemars::JsonSchema;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::sync::Arc;

use crate::topology::Color;
use serde::de::Error as _;
use std::fmt;

/// Registry codec format id stored on a source-object association.
///
/// The variant set is the generated `FORMAT` constants. Serialize as the
/// registry string. Deserialize rejects any other string.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[cfg_attr(feature = "schema", schemars(rename_all = "lowercase"))]
pub enum CodecFormat {
    /// `acis`
    Acis,
    /// `catia`
    Catia,
    /// `creo`
    Creo,
    /// `f3d`
    F3d,
    /// `fcstd`
    Fcstd,
    /// `iges`
    Iges,
    /// `inventor`
    Inventor,
    /// `nx`
    Nx,
    /// `parasolid`
    Parasolid,
    /// `rhino`
    Rhino,
    /// `sat`
    Sat,
    /// `sldprt`
    Sldprt,
    /// `step`
    Step,
}

impl CodecFormat {
    /// Parse a generated registry format id.
    #[must_use]
    pub fn parse(id: &str) -> Option<Self> {
        Some(match id {
            "acis" => Self::Acis,
            "catia" => Self::Catia,
            "creo" => Self::Creo,
            "f3d" => Self::F3d,
            "fcstd" => Self::Fcstd,
            "iges" => Self::Iges,
            "inventor" => Self::Inventor,
            "nx" => Self::Nx,
            "parasolid" => Self::Parasolid,
            "rhino" => Self::Rhino,
            "sat" => Self::Sat,
            "sldprt" => Self::Sldprt,
            "step" => Self::Step,
            _ => return None,
        })
    }

    /// The generated registry format id.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Acis => "acis",
            Self::Catia => "catia",
            Self::Creo => "creo",
            Self::F3d => "f3d",
            Self::Fcstd => "fcstd",
            Self::Iges => "iges",
            Self::Inventor => "inventor",
            Self::Nx => "nx",
            Self::Parasolid => "parasolid",
            Self::Rhino => "rhino",
            Self::Sat => "sat",
            Self::Sldprt => "sldprt",
            Self::Step => "step",
        }
    }

    /// Check a generated `FORMAT` constant against the registry.
    ///
    /// The [`codec_format!`](crate::codec_format) macro evaluates this in a
    /// const initializer and turns `None` into a compile error. Runtime text
    /// must use [`CodecFormat::parse`], which returns `None` instead of
    /// panicking.
    #[must_use]
    pub const fn from_registry_id(id: &str) -> Option<Self> {
        let bytes = id.as_bytes();
        if registry_id_is(bytes, b"acis") {
            Some(Self::Acis)
        } else if registry_id_is(bytes, b"catia") {
            Some(Self::Catia)
        } else if registry_id_is(bytes, b"creo") {
            Some(Self::Creo)
        } else if registry_id_is(bytes, b"f3d") {
            Some(Self::F3d)
        } else if registry_id_is(bytes, b"fcstd") {
            Some(Self::Fcstd)
        } else if registry_id_is(bytes, b"iges") {
            Some(Self::Iges)
        } else if registry_id_is(bytes, b"inventor") {
            Some(Self::Inventor)
        } else if registry_id_is(bytes, b"nx") {
            Some(Self::Nx)
        } else if registry_id_is(bytes, b"parasolid") {
            Some(Self::Parasolid)
        } else if registry_id_is(bytes, b"rhino") {
            Some(Self::Rhino)
        } else if registry_id_is(bytes, b"sat") {
            Some(Self::Sat)
        } else if registry_id_is(bytes, b"sldprt") {
            Some(Self::Sldprt)
        } else if registry_id_is(bytes, b"step") {
            Some(Self::Step)
        } else {
            None
        }
    }
}

/// True when the registry id `bytes` spells exactly `expected`.
const fn registry_id_is(bytes: &[u8], expected: &[u8]) -> bool {
    if bytes.len() != expected.len() {
        return false;
    }
    let mut index = 0;
    while index < bytes.len() {
        if bytes[index] != expected[index] {
            return false;
        }
        index += 1;
    }
    true
}

/// The [`CodecFormat`] a generated `FORMAT` constant names.
///
/// The id is read in the initializer of a `const` item, so a codec whose
/// `FORMAT` is not a registry id fails `cargo check` with E0080 instead of
/// panicking when the association is built.
#[macro_export]
macro_rules! codec_format {
    ($id:expr) => {{
        const CODEC_FORMAT: $crate::CodecFormat = match $crate::CodecFormat::from_registry_id($id) {
            Some(format) => format,
            None => {
                assert!(
                    false,
                    "a registry format id names one of the generated FORMAT constants"
                );
                $crate::CodecFormat::Step
            }
        };
        CODEC_FORMAT
    }};
}

impl fmt::Display for CodecFormat {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl Serialize for CodecFormat {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(self.as_str())
    }
}

impl<'de> Deserialize<'de> for CodecFormat {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let id = String::deserialize(deserializer)?;
        Self::parse(&id).ok_or_else(|| D::Error::custom(format!("format: unknown codec id {id}")))
    }
}

/// Whether source geometry is a standalone object or a support of another object.
/// Supports retain their mathematics when their owner cannot be projected; writers
/// must not promote them to standalone geometry merely because they are unused.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum SourceGeometryRole {
    /// Geometry independently present in the source document.
    Independent,
    /// Geometry used to define another source object.
    Support,
}

/// Native object identity and effective display metadata for a free carrier.
///
/// `format` identifies the source format. `object_id` is the source format's
/// native object identifier, not an IR arena identifier. `name`, `color`, and
/// `visible` are the effective object display values. `layer` is the native
/// layer identifier. `instance_path` contains native instance identifiers in
/// outermost-to-innermost order; an empty path means that the object is not
/// nested in an instance.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct SourceObjectAssociation {
    /// Source format identifier.
    pub format: CodecFormat,
    /// Source ownership, when it can be established independently of projection.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_geometry_role"
    )]
    pub geometry_role: Option<SourceGeometryRole>,
    /// Native source object identifier.
    #[serde(deserialize_with = "deserialize_object_id")]
    pub object_id: cadmpeg_core::text::NonBlankString,
    /// Effective source object name, when present.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_name"
    )]
    pub name: Option<String>,
    /// Effective source object color, when present.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_color"
    )]
    pub color: Option<Color>,
    /// Effective source object visibility, when present.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_visible"
    )]
    pub visible: Option<bool>,
    /// Native source layer identifier, when present.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_layer"
    )]
    pub layer: Option<String>,
    /// Native instance identifiers from outermost to innermost.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub instance_path: Vec<String>,
}

impl SourceObjectAssociation {
    /// Copy source identity and display text under the caller's limits.
    pub fn try_clone_for_decode(
        &self,
        ctx: &cadmpeg_core::decode::DecodeContext<'_>,
        operation: &'static str,
    ) -> Result<Self, cadmpeg_core::CodecError> {
        let text = |value: &str| ctx.copy_retained_text(value, operation);
        let object_id = cadmpeg_core::text::NonBlankString::new(text(self.object_id.as_str())?)
            .ok_or_else(|| {
                cadmpeg_core::CodecError::malformed("invalid decoded source object ID")
            })?;
        let name = self.name.as_deref().map(text).transpose()?;
        let layer = self.layer.as_deref().map(text).transpose()?;
        let instance_path =
            ctx.try_collect_retained_with(&self.instance_path, operation, |id| text(id))?;
        Ok(Self {
            format: self.format,
            geometry_role: self.geometry_role,
            object_id,
            name,
            color: self.color,
            visible: self.visible,
            layer,
            instance_path,
        })
    }
}

crate::units::named_field!(
    deserialize_object_id,
    cadmpeg_core::text::NonBlankString,
    "object_id"
);

/// Provenance for bytes identified by a typed location.
///
/// The location type distinguishes report provenance from a shared
/// annotation stream. Both forms share byte-offset and source-tag semantics
/// without admitting one form where the other is required.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Provenance<Location> {
    location: Location,
    /// Byte offset of the record within its source stream.
    pub offset: u64,
    /// Source record/class name/tag, when the decoder can attribute one.
    pub tag: Option<String>,
}

/// Name of a container stream inside a source format.
///
/// The empty string is not a stream name; the root stream is the absence of
/// one. Build a compile-time name with [`crate::stream_name!`].
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize)]
#[serde(try_from = "String", into = "String")]
pub struct StreamName(std::borrow::Cow<'static, str>);

#[cfg(feature = "schema")]
impl JsonSchema for StreamName {
    fn schema_name() -> std::borrow::Cow<'static, str> {
        "StreamName".into()
    }

    fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
        schemars::json_schema!({"type": "string", "minLength": 1})
    }
}

/// A static stream name whose non-empty invariant was admitted during const
/// evaluation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StaticStreamName {
    value: &'static str,
}

impl StaticStreamName {
    /// Admit a static stream name, returning `None` for the empty string.
    #[must_use]
    pub const fn new(value: &'static str) -> Option<Self> {
        if value.is_empty() {
            None
        } else {
            Some(Self { value })
        }
    }
}

/// The empty string does not name a container stream.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error("a source stream name cannot be empty")]
pub struct EmptyStreamName;

impl StreamName {
    /// Construct a stream name from a static proof.
    #[must_use]
    pub const fn from_static(proof: StaticStreamName) -> Self {
        Self(std::borrow::Cow::Borrowed(proof.value))
    }

    /// Returns the stream name.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Append a value to an admitted stream-name prefix.
    ///
    /// The prefix proves non-empty output. The caller admits the formatted storage.
    pub fn with_suffix(
        self,
        ctx: &cadmpeg_core::decode::DecodeContext<'_>,
        suffix: impl fmt::Display,
        operation: &'static str,
    ) -> Result<Self, cadmpeg_core::CodecError> {
        Ok(Self(std::borrow::Cow::Owned(ctx.format_retained(
            format_args!("{}{}", self.0, suffix),
            operation,
        )?)))
    }
}

/// Build a checked stream name from a literal.
///
/// ```compile_fail
/// # fn main() {
/// let _ = cadmpeg_ir::stream_name!("");
/// # }
/// ```
#[macro_export]
macro_rules! stream_name {
    ($value:literal) => {{
        const STATIC_STREAM_NAME: $crate::StaticStreamName =
            match $crate::StaticStreamName::new($value) {
                Some(name) => name,
                None => panic!("a source stream name cannot be empty"),
            };
        $crate::StreamName::from_static(STATIC_STREAM_NAME)
    }};
}

impl TryFrom<String> for StreamName {
    type Error = EmptyStreamName;

    fn try_from(name: String) -> Result<Self, Self::Error> {
        if name.is_empty() {
            return Err(EmptyStreamName);
        }
        Ok(Self(std::borrow::Cow::Owned(name)))
    }
}

impl From<StreamName> for String {
    fn from(name: StreamName) -> Self {
        name.0.into_owned()
    }
}

/// Owner of retained source bytes. An empty wire spelling names the root stream.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SourceOwner {
    /// Bytes in the root source stream.
    Root,
    /// Bytes in a named container stream.
    Named(StreamName),
}

impl SourceOwner {
    /// Return the retained-record wire spelling.
    #[must_use]
    pub(crate) fn as_str(&self) -> &str {
        match self {
            Self::Root => "",
            Self::Named(stream) => stream.as_str(),
        }
    }
}

impl From<String> for SourceOwner {
    fn from(stream: String) -> Self {
        if stream.is_empty() {
            Self::Root
        } else {
            Self::Named(StreamName(std::borrow::Cow::Owned(stream)))
        }
    }
}

impl From<&str> for SourceOwner {
    fn from(stream: &str) -> Self {
        Self::from(stream.to_owned())
    }
}

impl From<StreamName> for SourceOwner {
    fn from(stream: StreamName) -> Self {
        Self::Named(stream)
    }
}

impl Serialize for SourceOwner {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(self.as_str())
    }
}

impl<'de> Deserialize<'de> for SourceOwner {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        Ok(Self::from(String::deserialize(deserializer)?))
    }
}

/// Source format and optional named stream used by a report loss.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SourceLocation {
    format: String,
    stream: Option<StreamName>,
}

/// Source provenance attached to a report loss.
pub type SourceProvenance = Provenance<SourceLocation>;

/// Opaque owned reference to an annotation stream.
///
/// The admitted name travels with the provenance in memory and on the wire.
/// Moving or merging annotations cannot invalidate the stream reference.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AnnotationLocation {
    stream: Arc<StreamName>,
}

/// Provenance attached to an entity in [`crate::Annotations`].
pub type AnnotationProvenance = Provenance<AnnotationLocation>;

impl Provenance<AnnotationLocation> {
    pub(crate) fn try_clone_for_decode(
        &self,
        ctx: &cadmpeg_core::decode::DecodeContext<'_>,
        operation: &'static str,
    ) -> Result<Self, cadmpeg_core::CodecError> {
        let tag = self
            .tag
            .as_deref()
            .map(|tag| ctx.copy_retained_text(tag, operation))
            .transpose()?;
        ctx.charge_work(1, operation)?;
        Ok(Self::annotation(
            Arc::clone(&self.location.stream),
            self.offset,
            tag,
        ))
    }

    pub(crate) fn annotation(stream: Arc<StreamName>, offset: u64, tag: Option<String>) -> Self {
        Self {
            location: AnnotationLocation { stream },
            offset,
            tag,
        }
    }

    /// Return the owned source stream name.
    #[must_use]
    pub fn stream(&self) -> &str {
        self.location.stream.as_str()
    }
}

impl Provenance<SourceLocation> {
    /// Copies source provenance through the active decode admission context.
    pub(crate) fn try_clone_for_decode(
        &self,
        ctx: &cadmpeg_core::decode::DecodeContext<'_>,
        operation: &'static str,
    ) -> Result<Self, cadmpeg_core::CodecError> {
        let format = ctx.copy_retained_text(&self.location.format, operation)?;
        let stream = self
            .location
            .stream
            .as_ref()
            .map(|value| {
                let text = ctx.copy_retained_text(value.as_str(), operation)?;
                StreamName::try_from(text)
                    .map_err(|error| cadmpeg_core::CodecError::malformed(error.to_string()))
            })
            .transpose()?;
        let tag = self
            .tag
            .as_deref()
            .map(|value| ctx.copy_retained_text(value, operation))
            .transpose()?;
        Ok(Self {
            location: SourceLocation { format, stream },
            offset: self.offset,
            tag,
        })
    }

    /// Construct provenance relative to a format's root source stream.
    pub fn root(format: impl Into<String>, offset: u64) -> Self {
        Self {
            location: SourceLocation {
                format: format.into(),
                stream: None,
            },
            offset,
            tag: None,
        }
    }

    /// Construct provenance relative to a named container stream.
    pub fn in_stream(format: impl Into<String>, stream: StreamName, offset: u64) -> Self {
        Self {
            location: SourceLocation {
                format: format.into(),
                stream: Some(stream),
            },
            offset,
            tag: None,
        }
    }

    /// Attach a source record or class name.
    #[must_use]
    pub fn with_tag(mut self, tag: impl Into<String>) -> Self {
        self.tag = Some(tag.into());
        self
    }

    /// Attach an optional source record or class name.
    #[must_use]
    pub fn with_optional_tag(mut self, tag: Option<String>) -> Self {
        self.tag = tag;
        self
    }
}

#[derive(Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
struct AnnotationProvenanceWire {
    stream: StreamName,
    offset: u64,
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_tag"
    )]
    tag: Option<String>,
}

impl<'de> Deserialize<'de> for Provenance<AnnotationLocation> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let wire = AnnotationProvenanceWire::deserialize(deserializer)?;
        Ok(Self {
            location: AnnotationLocation {
                stream: Arc::new(wire.stream),
            },
            offset: wire.offset,
            tag: wire.tag,
        })
    }
}

#[cfg(feature = "schema")]
impl JsonSchema for Provenance<AnnotationLocation> {
    fn schema_name() -> std::borrow::Cow<'static, str> {
        "AnnotationProvenance".into()
    }

    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
        AnnotationProvenanceWire::json_schema(generator)
    }
}

#[derive(Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(deny_unknown_fields)]
struct SourceProvenanceWire {
    format: String,
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_stream"
    )]
    stream: Option<StreamName>,
    offset: u64,
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "deserialize_tag"
    )]
    tag: Option<String>,
}

impl From<SourceProvenanceWire> for Provenance<SourceLocation> {
    fn from(wire: SourceProvenanceWire) -> Self {
        Self {
            location: SourceLocation {
                format: wire.format,
                stream: wire.stream,
            },
            offset: wire.offset,
            tag: wire.tag,
        }
    }
}

impl<'de> Deserialize<'de> for Provenance<SourceLocation> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        SourceProvenanceWire::deserialize(deserializer).map(Self::from)
    }
}

#[cfg(feature = "schema")]
impl JsonSchema for Provenance<SourceLocation> {
    fn schema_name() -> std::borrow::Cow<'static, str> {
        "SourceProvenance".into()
    }

    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
        SourceProvenanceWire::json_schema(generator)
    }
}

/// How an entity or field value was established from its source.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(JsonSchema))]
#[serde(rename_all = "snake_case")]
#[serde(deny_unknown_fields)]
pub enum Exactness {
    /// Read verbatim from the source stream with no transformation beyond
    /// documented unit conversion.
    ByteExact,
    /// Computed deterministically from byte-exact inputs.
    Derived,
    /// Filled in from context or convention rather than an explicit source field.
    Inferred,
    /// Origin or trustworthiness could not be established.
    Unknown,
}

#[cfg(test)]
mod tests {
    #[cfg(feature = "schema")]
    use super::StreamName;
    use super::{CodecFormat, SourceObjectAssociation, SourceProvenance};
    use cadmpeg_test_support::wire;

    #[cfg(feature = "schema")]
    #[test]
    fn provenance_schemas_use_admitted_stream_names_and_codec_spellings() {
        let schema = serde_json::to_value(schemars::schema_for!(StreamName)).unwrap();
        assert_eq!(schema["type"], "string");
        assert_eq!(schema["minLength"], 1);
        let schema = serde_json::to_value(schemars::schema_for!(CodecFormat)).unwrap();
        let variants = schema["oneOf"].as_array().unwrap();
        for variant in variants {
            let text = variant["const"].as_str().unwrap();
            let format = CodecFormat::parse(text).unwrap();
            assert_eq!(serde_json::to_value(format).unwrap(), variant["const"]);
        }
        assert_eq!(variants.len(), 13);
        assert!(variants.iter().any(|variant| variant["const"] == "f3d"));
        let schema = serde_json::to_value(schemars::schema_for!(SourceObjectAssociation)).unwrap();
        assert_eq!(
            schema["properties"]["format"]["$ref"],
            "#/$defs/CodecFormat"
        );
        assert_eq!(
            schema["$defs"]["CodecFormat"]["oneOf"].as_array().unwrap(),
            variants
        );
    }

    #[test]
    fn registry_format_parser_is_total_for_runtime_text() {
        const STEP: CodecFormat = crate::codec_format!("step");

        assert_eq!(
            CodecFormat::from_registry_id("step"),
            Some(CodecFormat::Step)
        );
        assert_eq!(CodecFormat::from_registry_id("unknown"), None);
        assert_eq!(STEP, CodecFormat::Step);
    }

    #[test]
    fn a_source_provenance_stream_is_named_or_absent() {
        let root = SourceProvenance::root("iges", 12);
        let wire = serde_json::to_value(&root).expect("serialize");
        assert_eq!(wire, serde_json::json!({"format": "iges", "offset": 12}));
        let read: SourceProvenance = serde_json::from_value(wire).expect("root reads back");
        assert_eq!(
            wire::field_or_default::<Option<String>>(&read, "stream").as_deref(),
            None
        );
        assert_eq!(read, root);

        let named = SourceProvenance::in_stream("fcstd", crate::stream_name!("Document.xml"), 0);
        let wire = serde_json::to_value(&named).expect("serialize");
        assert_eq!(
            wire,
            serde_json::json!({"format": "fcstd", "stream": "Document.xml", "offset": 0})
        );
        let read: SourceProvenance = serde_json::from_value(wire).expect("named reads back");
        assert_eq!(
            wire::field_or_default::<Option<String>>(&read, "stream").as_deref(),
            Some("Document.xml")
        );

        let error = serde_json::from_value::<SourceProvenance>(
            serde_json::json!({"format": "iges", "stream": "", "offset": 0}),
        )
        .expect_err("the empty string does not name a stream")
        .to_string();
        assert!(error.contains("stream name cannot be empty"), "{error}");
    }

    #[test]
    fn stream_name_composition_keeps_the_admitted_prefix() {
        let ctx = cadmpeg_test_support::service_decode_context();
        let prefix = crate::stream_name!("codec:");
        assert_eq!(
            prefix
                .clone()
                .with_suffix(&ctx, "", "stream suffix")
                .unwrap()
                .as_str(),
            "codec:"
        );
        assert_eq!(
            prefix
                .with_suffix(&ctx, 7, "stream suffix")
                .unwrap()
                .as_str(),
            "codec:7"
        );
    }

    #[test]
    fn stream_suffix_preserves_the_original_storage_refusal() {
        use cadmpeg_core::decode::{DecodeArena, DecodeContext, DecodePolicy, ResourceDimension};
        use cadmpeg_core::CodecError;
        for dimension in [
            ResourceDimension::RetainedBytes,
            ResourceDimension::WorkUnits,
            ResourceDimension::MaterializedBytes,
        ] {
            let arena = DecodeArena::new();
            let mut policy = DecodePolicy::service();
            match dimension {
                ResourceDimension::RetainedBytes => policy.limits.max_retained_bytes = 0,
                ResourceDimension::WorkUnits => policy.limits.max_work_units = 0,
                ResourceDimension::MaterializedBytes => policy.limits.max_materialized_bytes = 0,
                _ => unreachable!(),
            }
            let (ctx, _) = DecodeContext::from_root_bytes(&[], &arena, &policy).unwrap();
            let create = || crate::stream_name!("codec:").with_suffix(&ctx, 7, "stream suffix");
            let result = if dimension == ResourceDimension::MaterializedBytes {
                ctx.with_scoped_storage("temporary stream name", create)
                    .map(|_| ())
            } else {
                create().map(|_| ())
            };
            let Err(CodecError::ResourceLimit(limit)) = result else {
                panic!("suffix must refuse");
            };
            assert_eq!(limit.dimension, dimension);
            assert_eq!(limit.operation, "stream suffix");
            assert!(
                matches!(ctx.finish_session(), Err(CodecError::ResourceLimit(original)) if original == limit)
            );
        }
    }

    #[test]
    fn stream_suffix_uses_bytes_without_collection_slots() {
        use cadmpeg_core::decode::{DecodeArena, DecodeContext, DecodePolicy};
        let arena = DecodeArena::new();
        let mut policy = DecodePolicy::service();
        policy.limits.max_collection_items = 0;
        policy.limits.max_materialized_bytes = 0;
        let (ctx, _) = DecodeContext::from_root_bytes(&[], &arena, &policy).unwrap();
        let name = crate::stream_name!("codec:")
            .with_suffix(&ctx, 7, "stream suffix")
            .unwrap();
        assert_eq!(name.as_str(), "codec:7");
        ctx.finish_session().unwrap();
    }

    #[test]
    fn source_object_identity_is_nonempty_and_preserves_wire() {
        let wire = serde_json::json!({"format": "step", "object_id": "#42"});
        let value: SourceObjectAssociation =
            serde_json::from_value(wire.clone()).expect("nonempty identity");
        assert_eq!(serde_json::to_value(value).expect("serialize"), wire);
        let error = serde_json::from_value::<SourceObjectAssociation>(
            serde_json::json!({"format": "step", "object_id": ""}),
        )
        .expect_err("empty identity");
        assert!(error.to_string().contains("object_id"));
    }

    #[test]
    fn source_geometry_role_preserves_ownership_and_requires_omission_for_absence() {
        for role in ["independent", "support"] {
            let wire = serde_json::json!({
                "format": "iges", "object_id": "D1", "geometry_role": role
            });
            let value: SourceObjectAssociation =
                serde_json::from_value(wire.clone()).expect("source ownership");
            assert_eq!(serde_json::to_value(value).expect("serialize"), wire);
        }
        for role in [serde_json::Value::Null, serde_json::json!("unknown")] {
            let error = serde_json::from_value::<SourceObjectAssociation>(serde_json::json!({
                "format": "iges", "object_id": "D1", "geometry_role": role
            }))
            .expect_err("invalid ownership");
            assert!(error.to_string().contains("geometry_role"));
        }
    }
}

// Each optional key below names itself in whatever it refuses.
cadmpeg_core::named_optional_field!(
    deserialize_geometry_role,
    SourceGeometryRole,
    "geometry_role"
);
cadmpeg_core::named_optional_field!(deserialize_name, String, "name");
cadmpeg_core::named_optional_field!(deserialize_color, Color, "color");
cadmpeg_core::named_optional_field!(deserialize_visible, bool, "visible");
cadmpeg_core::named_optional_field!(deserialize_layer, String, "layer");
cadmpeg_core::named_optional_field!(deserialize_tag, String, "tag");
cadmpeg_core::named_optional_field!(deserialize_stream, StreamName, "stream");

mod identity_rewrite;

mod serialization;