Skip to main content

ic_wire/serde_packed/
mod.rs

1//! Explicit bulk field adapters within the single Serde/Postcard codec.
2//!
3//! Select using `#[serde(with = "ic_wire::serde_packed::bools")]` (or another
4//! adapter below). Ordinary fields are never rewritten. Adoption changes traversal
5//! accounting and, except for bools, ordinary-list bytes. Preserve field bounds,
6//! coordinate clients and retain original retry/hash bytes. Reference contracts
7//! and qualification are recorded in docs/design/parity.md.
8
9/// Checked boolean bytes, projected as a browser boolean array.
10pub mod bools {
11    use alloc::vec::Vec;
12    use serde::{Deserializer, Serializer, de};
13    /// Borrow boolean storage as bytes; only 0/1 patterns can occur.
14    /// # Errors
15    /// Propagates serializer refusal.
16    pub fn serialize<S: Serializer>(values: &[bool], serializer: S) -> Result<S::Ok, S::Error> {
17        serializer.serialize_bytes(bytemuck::must_cast_slice(values))
18    }
19    /// Validate every byte before reserving owned output.
20    /// # Errors
21    /// Rejects invalid boolean patterns and propagates admission/allocation errors.
22    pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Vec<bool>, D::Error> {
23        struct Visitor;
24        impl de::Visitor<'_> for Visitor {
25            type Value = Vec<bool>;
26            fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
27                f.write_str("boolean bytes")
28            }
29            fn visit_bytes<E: de::Error>(self, bytes: &[u8]) -> Result<Self::Value, E> {
30                let words: &[bool] = bytemuck::checked::try_cast_slice(bytes)
31                    .map_err(|_| E::custom("invalid boolean byte"))?;
32                let mut output = Vec::new();
33                output
34                    .try_reserve_exact(words.len())
35                    .map_err(|_| E::custom("allocation"))?;
36                output.extend_from_slice(words);
37                Ok(output)
38            }
39        }
40        deserializer.deserialize_bytes(Visitor)
41    }
42}
43
44/// Packed signed words retaining the nonzero domain rule.
45pub mod nonzero_i64 {
46    use alloc::vec::Vec;
47    use core::num::NonZeroI64;
48    use serde::{Deserialize, Deserializer, Serializer};
49    /// Encode borrowed nonzero storage without a temporary integer vector.
50    /// # Errors
51    /// Propagates serializer refusal.
52    pub fn serialize<S: Serializer>(
53        values: &[NonZeroI64],
54        serializer: S,
55    ) -> Result<S::Ok, S::Error> {
56        crate::packed::serialize_words::<i64, S>(bytemuck::must_cast_slice(values), serializer)
57    }
58    /// Decode packed words and enforce nonzero values.
59    /// # Errors
60    /// Rejects zero and propagates packed decoding failures. Validation follows
61    /// owned word decoding; it is not a pre-allocation validation guarantee.
62    pub fn deserialize<'de, D: Deserializer<'de>>(
63        deserializer: D,
64    ) -> Result<Vec<NonZeroI64>, D::Error> {
65        crate::Packed::<i64>::deserialize(deserializer)?
66            .into_vec()
67            .into_iter()
68            .map(NonZeroI64::new)
69            .collect::<Option<Vec<_>>>()
70            .ok_or_else(|| serde::de::Error::custom("zero in nonzero list"))
71    }
72}
73
74/// Packed heap backing order; decoding reconstructs the heap.
75/// Re-encoding may reorder accepted input. Retain original signed/retry bytes.
76pub mod heap_u64 {
77    use alloc::collections::BinaryHeap;
78    use serde::{Deserialize, Deserializer, Serializer};
79    /// Encode the existing backing slice without copying.
80    /// # Errors
81    /// Propagates serializer refusal.
82    pub fn serialize<S: Serializer>(
83        values: &BinaryHeap<u64>,
84        serializer: S,
85    ) -> Result<S::Ok, S::Error> {
86        crate::packed::serialize_words(values.as_slice(), serializer)
87    }
88    /// Rebuild a heap from owned packed words, accepting duplicates and any order.
89    /// # Errors
90    /// Propagates packed decoding failures.
91    pub fn deserialize<'de, D: Deserializer<'de>>(
92        deserializer: D,
93    ) -> Result<BinaryHeap<u64>, D::Error> {
94        Ok(BinaryHeap::from(
95            crate::Packed::<u64>::deserialize(deserializer)?.into_vec(),
96        ))
97    }
98}
99
100// A shared source pattern for two domain adapters. No consumer-specific codec
101// generation or inherited unrolled/scanner optimization without new measurements.
102macro_rules! finite {
103    ($module:ident,$float:ty,$width:literal) => {
104        /// Finite little-endian float byte fields. Preserves signed zero and subnormals.
105        pub mod $module {
106            use alloc::vec::Vec;
107            use serde::{Deserializer, Serializer, de};
108            fn valid(bytes: &[u8]) -> bool {
109                if !bytes.len().is_multiple_of($width) {
110                    return false;
111                }
112                let mut tail = bytes;
113                if $width == 4 {
114                    // Independent f32 exponent lanes: adding one exponent unit
115                    // reaches each sign bit exactly for exponent 0xff. Masking
116                    // first prevents mantissa/sign bits and cross-lane carries.
117                    let mut pairs = bytes.chunks_exact(8);
118                    if !pairs.by_ref().all(|pair| {
119                        let bits = u64::from_le_bytes(pair.try_into().unwrap());
120                        ((bits & 0x7f80_0000_7f80_0000) + 0x0080_0000_0080_0000)
121                            & 0x8000_0000_8000_0000
122                            == 0
123                    }) {
124                        return false;
125                    }
126                    tail = pairs.remainder();
127                }
128                tail.chunks_exact($width).all(|word| {
129                    <$float>::from_le_bytes(word.try_into().expect("whole float word")).is_finite()
130                })
131            }
132            /// Encode finite values as one byte buffer without narrowing finite bits.
133            /// # Errors
134            /// Rejects NaN/infinity and propagates serializer/allocation failures.
135            pub fn serialize<S: Serializer>(
136                values: &[$float],
137                serializer: S,
138            ) -> Result<S::Ok, S::Error> {
139                #[cfg(target_endian = "little")]
140                {
141                    let bytes = bytemuck::must_cast_slice(values);
142                    if !valid(bytes) {
143                        return Err(serde::ser::Error::custom("non-finite float"));
144                    }
145                    serializer.serialize_bytes(bytes)
146                }
147                #[cfg(target_endian = "big")]
148                {
149                    serializer.serialize_bytes(&little_endian::<S::Error>(values)?)
150                }
151            }
152            #[cfg(any(target_endian = "big", test))]
153            pub(super) fn little_endian<E: serde::ser::Error>(
154                values: &[$float],
155            ) -> Result<Vec<u8>, E> {
156                if values.iter().any(|value| !value.is_finite()) {
157                    return Err(E::custom("non-finite float"));
158                }
159                let length = values
160                    .len()
161                    .checked_mul($width)
162                    .ok_or_else(|| E::custom("length overflow"))?;
163                let mut bytes = Vec::new();
164                bytes
165                    .try_reserve_exact(length)
166                    .map_err(|_| E::custom("allocation"))?;
167                for value in values {
168                    bytes.extend_from_slice(&value.to_le_bytes());
169                }
170                Ok(bytes)
171            }
172            /// Reject partial/nonfinite words before allocating owned float storage.
173            /// # Errors
174            /// Rejects invalid spans and propagates admission/allocation failures.
175            pub fn deserialize<'de, D: Deserializer<'de>>(
176                deserializer: D,
177            ) -> Result<Vec<$float>, D::Error> {
178                struct Visitor;
179                impl de::Visitor<'_> for Visitor {
180                    type Value = Vec<$float>;
181                    fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
182                        f.write_str("finite little-endian float bytes")
183                    }
184                    fn visit_bytes<E: de::Error>(self, bytes: &[u8]) -> Result<Self::Value, E> {
185                        if !valid(bytes) {
186                            return Err(E::custom("invalid finite float bytes"));
187                        }
188                        let mut values = Vec::new();
189                        values
190                            .try_reserve_exact(bytes.len() / $width)
191                            .map_err(|_| E::custom("allocation"))?;
192                        values.extend(bytes.chunks_exact($width).map(|word| {
193                            <$float>::from_le_bytes(
194                                word.try_into().expect("validated whole float word"),
195                            )
196                        }));
197                        Ok(values)
198                    }
199                }
200                deserializer.deserialize_bytes(Visitor)
201            }
202        }
203    };
204}
205finite!(finite_f32, f32, 4);
206finite!(finite_f64, f64, 8);
207#[cfg(test)]
208mod tests;