Skip to main content

ic_wire/fields/
borrowed.rs

1//! Input-backed finite byte and text values. Deserializers must lend their input.
2use super::{Bytes, Text};
3use crate::Error;
4use core::fmt;
5use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
6
7/// Opaque bytes bounded in length, borrowing their backing storage.
8/// Decoding accepts borrowed input only; the value cannot outlive that input.
9///
10/// ```compile_fail
11/// use ic_wire::{BytesRef, Encoding, Limits, decode};
12/// let value = {
13///     let input = [1, 7];
14///     decode::<BytesRef<'_, 1>>(&input, Encoding::Payload,
15///         Limits { bytes: 2, allocation: 1024, nodes: 8, depth: 8 }).unwrap()
16/// };
17/// assert_eq!(value.as_slice(), &[7]);
18/// ```
19#[derive(Clone, Copy, Debug, Eq, PartialEq)]
20pub struct BytesRef<'a, const N: usize>(&'a [u8]);
21impl<'a, const N: usize> BytesRef<'a, N> {
22    /// Admit a borrowed slice without copying or allocating.
23    pub fn new(bytes: &'a [u8]) -> Result<Self, Error> {
24        if bytes.len() > N {
25            Err(Error::Limit)
26        } else {
27            Ok(Self(bytes))
28        }
29    }
30
31    /// Borrow the admitted bytes for their original storage lifetime.
32    #[must_use]
33    pub fn as_slice(&self) -> &'a [u8] {
34        self.0
35    }
36
37    pub(super) fn from_owned(bytes: &'a Bytes<N>) -> Self {
38        Self(bytes.as_slice())
39    }
40}
41impl<const N: usize> Serialize for BytesRef<'_, N> {
42    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
43        s.serialize_bytes(self.0)
44    }
45}
46impl<'de: 'a, 'a, const N: usize> Deserialize<'de> for BytesRef<'a, N> {
47    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
48        struct Visitor<const N: usize>;
49        impl<'de, const N: usize> de::Visitor<'de> for Visitor<N> {
50            type Value = BytesRef<'de, N>;
51            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52                f.write_str("bounded borrowed bytes")
53            }
54
55            fn visit_borrowed_bytes<E: de::Error>(
56                self,
57                bytes: &'de [u8],
58            ) -> Result<Self::Value, E> {
59                BytesRef::new(bytes).map_err(|_| E::custom("byte limit"))
60            }
61        }
62        d.deserialize_bytes(Visitor::<N>)
63    }
64}
65
66/// UTF-8 text bounded in bytes, borrowing its backing storage.
67/// Decoding accepts borrowed input only, without an owned fallback.
68///
69/// ```compile_fail
70/// use ic_wire::{TextRef, Encoding, Limits, decode};
71/// let mut input = [1, b'a'];
72/// let text = decode::<TextRef<'_, 1>>(&input, Encoding::Payload,
73///     Limits { bytes: 2, allocation: 1024, nodes: 8, depth: 8 }).unwrap();
74/// input[1] = b'b';
75/// assert_eq!(text.as_str(), "a");
76/// ```
77#[derive(Clone, Copy, Debug, Eq, PartialEq)]
78pub struct TextRef<'a, const N: usize>(&'a str);
79impl<'a, const N: usize> TextRef<'a, N> {
80    /// Admit borrowed text without copying or allocating.
81    pub fn new(text: &'a str) -> Result<Self, Error> {
82        if text.len() > N {
83            Err(Error::Limit)
84        } else {
85            Ok(Self(text))
86        }
87    }
88
89    /// Borrow the admitted text for its original storage lifetime.
90    #[must_use]
91    pub fn as_str(&self) -> &'a str {
92        self.0
93    }
94
95    pub(super) fn from_owned(text: &'a Text<N>) -> Self {
96        Self(text.as_str())
97    }
98}
99impl<const N: usize> Serialize for TextRef<'_, N> {
100    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
101        s.serialize_str(self.0)
102    }
103}
104impl<'de: 'a, 'a, const N: usize> Deserialize<'de> for TextRef<'a, N> {
105    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
106        struct Visitor<const N: usize>;
107        impl<'de, const N: usize> de::Visitor<'de> for Visitor<N> {
108            type Value = TextRef<'de, N>;
109            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
110                f.write_str("bounded borrowed UTF-8 text")
111            }
112
113            fn visit_borrowed_str<E: de::Error>(self, text: &'de str) -> Result<Self::Value, E> {
114                TextRef::new(text).map_err(|_| E::custom("text limit"))
115            }
116        }
117        d.deserialize_str(Visitor::<N>)
118    }
119}