Skip to main content

codec_cbor/general/
profile.rs

1// SPDX-FileCopyrightText: 2026 ReallyMe Technologies Limited
2//
3// SPDX-License-Identifier: MIT OR Apache-2.0
4
5use super::error::{error, CborError, ErrorReason};
6
7/// Schema-generated policies used by the native compatibility facade.
8pub use codec_proto::generated::proto::reallyme::codec::v1::{
9    CodecGeneralCborFloatPolicy as FloatPolicy, CodecGeneralCborLengthPolicy as LengthPolicy,
10    CodecGeneralCborMapKeyEquality as MapKeyEquality, CodecGeneralCborMapOrdering as MapOrdering,
11    CodecGeneralCborNanPolicy as NanPolicy, CodecGeneralCborSerialization as Serialization,
12};
13
14/// Basic validity and selected serialization guarantees.
15///
16/// Validation checks UTF-8 and rejects equivalent map keys using the selected
17/// data model. Registered tag semantics remain opaque; tag 24
18/// has a separate explicit embedded-item validation operation.
19#[derive(Clone, Copy, Debug, Eq, PartialEq)]
20pub struct Profile {
21    pub(super) serialization: Serialization,
22    pub(super) lengths: LengthPolicy,
23    pub(super) floats: FloatPolicy,
24    pub(super) ordering: MapOrdering,
25    map_key_equality: Option<MapKeyEquality>,
26    nan_policy: Option<NanPolicy>,
27}
28
29impl Profile {
30    pub(super) fn ensure_supported(self) -> Result<(), CborError> {
31        Self::new(self.serialization, self.lengths, self.floats, self.ordering).map(|_| ())
32    }
33
34    /// Construct an explicit profile; preferred serialization requires definite lengths.
35    pub fn new(
36        serialization: Serialization,
37        lengths: LengthPolicy,
38        floats: FloatPolicy,
39        ordering: MapOrdering,
40    ) -> Result<Self, CborError> {
41        ensure_lengths_supported(lengths)?;
42        if !matches!(
43            serialization,
44            Serialization::Received | Serialization::Preferred
45        ) || !matches!(
46            floats,
47            FloatPolicy::All | FloatPolicy::FiniteOnly | FloatPolicy::Reject
48        ) || !matches!(
49            ordering,
50            MapOrdering::Received | MapOrdering::LengthFirst | MapOrdering::Bytewise
51        ) {
52            return Err(error(ErrorReason::UnsupportedPolicy));
53        }
54        if serialization == Serialization::Preferred && lengths != LengthPolicy::DefiniteOnly {
55            return Err(error(ErrorReason::UnsupportedPolicy));
56        }
57        Ok(Self {
58            serialization,
59            lengths,
60            floats,
61            ordering,
62            map_key_equality: None,
63            nan_policy: None,
64        })
65    }
66
67    /// Basic validity with received widths, indefinite support, and unsorted unique maps.
68    #[must_use]
69    pub const fn received() -> Self {
70        Self {
71            serialization: Serialization::Received,
72            lengths: LengthPolicy::AllowIndefinite,
73            floats: FloatPolicy::All,
74            ordering: MapOrdering::Received,
75            map_key_equality: None,
76            nan_policy: None,
77        }
78    }
79
80    /// Preferred widths and definite lengths, with unsorted unique maps.
81    #[must_use]
82    pub const fn preferred() -> Self {
83        Self {
84            serialization: Serialization::Preferred,
85            lengths: LengthPolicy::DefiniteOnly,
86            floats: FloatPolicy::All,
87            ordering: MapOrdering::Received,
88            map_key_equality: None,
89            nan_policy: None,
90        }
91    }
92
93    /// Select floating-point acceptance without changing other guarantees.
94    #[must_use]
95    pub const fn with_floats(mut self, policy: FloatPolicy) -> Self {
96        self.floats = policy;
97        self
98    }
99
100    /// Select map ordering; encoding never sorts caller data automatically.
101    #[must_use]
102    pub const fn with_map_ordering(mut self, ordering: MapOrdering) -> Self {
103        self.ordering = ordering;
104        self
105    }
106
107    /// Select scalar wire equality and structural compound key equality.
108    pub fn with_map_key_equality(mut self, equality: MapKeyEquality) -> Result<Self, CborError> {
109        match equality {
110            MapKeyEquality::EncodedScalars => {
111                self.map_key_equality = Some(equality);
112                Ok(self)
113            }
114            _ => Err(error(ErrorReason::UnsupportedPolicy)),
115        }
116    }
117
118    /// Select a NaN width restriction independently of general float acceptance.
119    pub fn with_nan_policy(mut self, policy: NanPolicy) -> Result<Self, CborError> {
120        match policy {
121            NanPolicy::Binary16Only => {
122                self.nan_policy = Some(policy);
123                Ok(self)
124            }
125            _ => Err(error(ErrorReason::UnsupportedPolicy)),
126        }
127    }
128
129    /// Inspect the optional map key equality rule.
130    #[must_use]
131    pub const fn map_key_equality(self) -> Option<MapKeyEquality> {
132        self.map_key_equality
133    }
134
135    /// Inspect the optional NaN width restriction.
136    #[must_use]
137    pub const fn nan_policy(self) -> Option<NanPolicy> {
138        self.nan_policy
139    }
140
141    pub(super) const fn has_encoded_scalar_keys(self) -> bool {
142        self.map_key_equality.is_some()
143    }
144
145    pub(super) const fn requires_binary16_nan(self) -> bool {
146        self.nan_policy.is_some()
147    }
148
149    /// Inspect the received length policy.
150    #[must_use]
151    pub const fn lengths(self) -> LengthPolicy {
152        self.lengths
153    }
154
155    /// Inspect serialization guarantees.
156    #[must_use]
157    pub const fn serialization(self) -> Serialization {
158        self.serialization
159    }
160
161    /// Inspect floating-point acceptance.
162    #[must_use]
163    pub const fn floats(self) -> FloatPolicy {
164        self.floats
165    }
166
167    /// Inspect the independently selected map-order constraint.
168    #[must_use]
169    pub const fn map_ordering(self) -> MapOrdering {
170        self.ordering
171    }
172}
173
174pub(super) fn ensure_lengths_supported(value: LengthPolicy) -> Result<(), CborError> {
175    match value {
176        LengthPolicy::DefiniteOnly | LengthPolicy::AllowIndefinite => Ok(()),
177        _ => Err(error(ErrorReason::UnsupportedPolicy)),
178    }
179}