ic_wire/bounded/borrowed/
mod.rs1use super::{Bytes, Text};
3use crate::{Error, Shape, Wire, schema::Schema};
4use core::fmt;
5use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
6
7#[derive(Clone, Copy, Debug, Eq, PartialEq)]
10pub struct BytesRef<'a, const N: usize>(&'a [u8]);
11impl<'a, const N: usize> BytesRef<'a, N> {
12 pub fn new(bytes: &'a [u8]) -> Result<Self, Error> {
14 if bytes.len() > N {
15 Err(Error::Limit)
16 } else {
17 Ok(Self(bytes))
18 }
19 }
20 pub fn as_slice(&self) -> &'a [u8] {
22 self.0
23 }
24 pub(super) fn from_owned(bytes: &'a Bytes<N>) -> Self {
25 Self(bytes.as_slice())
26 }
27}
28impl<const N: usize> Serialize for BytesRef<'_, N> {
29 fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
30 s.serialize_bytes(self.0)
31 }
32}
33impl<'de: 'a, 'a, const N: usize> Deserialize<'de> for BytesRef<'a, N> {
34 fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
35 struct Visitor<const N: usize>;
36 impl<'de, const N: usize> de::Visitor<'de> for Visitor<N> {
37 type Value = BytesRef<'de, N>;
38 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
39 f.write_str("bounded borrowed bytes")
40 }
41 fn visit_borrowed_bytes<E: de::Error>(
42 self,
43 bytes: &'de [u8],
44 ) -> Result<Self::Value, E> {
45 BytesRef::new(bytes).map_err(|_| E::custom("byte limit"))
46 }
47 }
48 d.deserialize_bytes(Visitor::<N>)
49 }
50}
51impl<const N: usize> Wire for BytesRef<'_, N> {
52 const SHAPE: Shape = Shape {
53 heap: 0,
54 ..Bytes::<N>::SHAPE
55 };
56 const SCHEMA: Schema = Bytes::<N>::SCHEMA;
57}
58
59#[derive(Clone, Copy, Debug, Eq, PartialEq)]
62pub struct TextRef<'a, const N: usize>(&'a str);
63impl<'a, const N: usize> TextRef<'a, N> {
64 pub fn new(text: &'a str) -> Result<Self, Error> {
66 if text.len() > N {
67 Err(Error::Limit)
68 } else {
69 Ok(Self(text))
70 }
71 }
72 pub fn as_str(&self) -> &'a str {
74 self.0
75 }
76 pub(super) fn from_owned(text: &'a Text<N>) -> Self {
77 Self(text.as_str())
78 }
79}
80impl<const N: usize> Serialize for TextRef<'_, N> {
81 fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
82 s.serialize_str(self.0)
83 }
84}
85impl<'de: 'a, 'a, const N: usize> Deserialize<'de> for TextRef<'a, N> {
86 fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
87 struct Visitor<const N: usize>;
88 impl<'de, const N: usize> de::Visitor<'de> for Visitor<N> {
89 type Value = TextRef<'de, N>;
90 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91 f.write_str("bounded borrowed UTF-8 text")
92 }
93 fn visit_borrowed_str<E: de::Error>(self, text: &'de str) -> Result<Self::Value, E> {
94 TextRef::new(text).map_err(|_| E::custom("text limit"))
95 }
96 }
97 d.deserialize_str(Visitor::<N>)
98 }
99}
100impl<const N: usize> Wire for TextRef<'_, N> {
101 const SHAPE: Shape = Shape {
102 heap: 0,
103 ..Text::<N>::SHAPE
104 };
105 const SCHEMA: Schema = Text::<N>::SCHEMA;
106}