Skip to main content

ic_wire/bounded/packed_i16/
mod.rs

1use crate::Error;
2use alloc::vec::Vec;
3use core::fmt;
4use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
5
6/// Bounded signed 16-bit words encoded as little-endian bytes.
7///
8/// Unlike `List<i16, N>` or `Vec<i16>`, this uses a byte count and fixed-width
9/// words instead of an element count and ZigZag varints. Switching a field
10/// requires coordinated consumers. Small-magnitude values take more space.
11#[derive(Clone, Debug, Eq, PartialEq)]
12pub struct PackedI16<const N: usize>(Vec<i16>);
13impl<const N: usize> PackedI16<N> {
14    /// Admit an owned sequence without copying. `N` counts elements, not bytes.
15    pub fn new(values: Vec<i16>) -> Result<Self, Error> {
16        if values.len() > N {
17            Err(Error::Limit)
18        } else {
19            Ok(Self(values))
20        }
21    }
22    /// Borrow the admitted words.
23    pub fn as_slice(&self) -> &[i16] {
24        &self.0
25    }
26    /// Recover the admitted sequence without copying.
27    pub fn into_vec(self) -> Vec<i16> {
28        self.0
29    }
30}
31impl<const N: usize> Serialize for PackedI16<N> {
32    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
33        // Opt-in field layout: [32767] changes from 01 fe ff 03 (Vec<i16>)
34        // to 02 ff 7f (byte count + LE words). Ordinary lists are unchanged;
35        // consumers switching this field must coordinate schemas and retry bytes.
36        // Share the sealed LE writer only. Decoders retain their own bound and
37        // allocation/copy paths; bytes and admission are unchanged.
38        crate::packed::serialize_words(&self.0, serializer)
39    }
40}
41impl<'de, const N: usize> Deserialize<'de> for PackedI16<N> {
42    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
43        deserializer
44            .deserialize_bytes(PackedVisitor { limit: N })
45            .map(Self)
46    }
47}
48
49// Share decoding across bounds instead of specializing the allocation/copy loop
50// for each N. The field's exact element limit is still checked before allocation;
51// byte layout, primitive validation and budget charges remain unchanged.
52struct PackedVisitor {
53    limit: usize,
54}
55impl de::Visitor<'_> for PackedVisitor {
56    type Value = Vec<i16>;
57    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
58        f.write_str("bounded packed little-endian i16 words")
59    }
60    #[inline(never)]
61    fn visit_bytes<E: de::Error>(self, bytes: &[u8]) -> Result<Self::Value, E> {
62        if !bytes.len().is_multiple_of(2) || bytes.len() / 2 > self.limit {
63            return Err(E::custom("invalid packed length"));
64        }
65        let mut values = Vec::new();
66        values
67            .try_reserve_exact(bytes.len() / 2)
68            .map_err(|_| E::custom("allocation"))?;
69        values.extend(
70            bytes
71                .as_chunks::<2>()
72                .0
73                .iter()
74                .map(|word| i16::from_le_bytes(*word)),
75        );
76        Ok(values)
77    }
78}