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    #[must_use]
24    pub fn as_slice(&self) -> &[i16] {
25        &self.0
26    }
27    /// Recover the admitted sequence without copying.
28    #[must_use]
29    pub fn into_vec(self) -> Vec<i16> {
30        self.0
31    }
32}
33impl<const N: usize> Serialize for PackedI16<N> {
34    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
35        // Opt-in field layout: [32767] changes from 01 fe ff 03 (Vec<i16>)
36        // to 02 ff 7f (byte count + LE words). Ordinary lists are unchanged;
37        // consumers switching this field must coordinate schemas and retry bytes.
38        // Share the sealed LE writer only. Decoders retain their own bound and
39        // allocation/copy paths; bytes and admission are unchanged.
40        crate::packed::serialize_words(&self.0, serializer)
41    }
42}
43impl<'de, const N: usize> Deserialize<'de> for PackedI16<N> {
44    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
45        deserializer
46            .deserialize_bytes(PackedVisitor { limit: N })
47            .map(Self)
48    }
49}
50
51// Share decoding across bounds instead of specializing the allocation/copy loop
52// for each N. The field's exact element limit is still checked before allocation;
53// byte layout, primitive validation and budget charges remain unchanged.
54struct PackedVisitor {
55    limit: usize,
56}
57impl de::Visitor<'_> for PackedVisitor {
58    type Value = Vec<i16>;
59    fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
60        f.write_str("bounded packed little-endian i16 words")
61    }
62    #[inline(never)]
63    fn visit_bytes<E: de::Error>(self, bytes: &[u8]) -> Result<Self::Value, E> {
64        crate::packed::decode_words!(
65            E,
66            bytes,
67            2,
68            bytes.len() / 2 > self.limit,
69            bytes
70                .as_chunks::<2>()
71                .0
72                .iter()
73                .map(|word| i16::from_le_bytes(*word))
74        )
75    }
76}