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