aldrin_core/
serialized_value.rs

1#[cfg(test)]
2mod test;
3
4use crate::error::{DeserializeError, SerializeError};
5use crate::value::ValueKind;
6use crate::value_deserializer::{Deserialize, Deserializer};
7use crate::value_serializer::{Serialize, Serializer};
8use bytes::BytesMut;
9use std::borrow::Borrow;
10use std::fmt;
11use std::ops::Deref;
12
13#[derive(Clone, Eq)]
14pub struct SerializedValue {
15    buf: BytesMut,
16}
17
18impl SerializedValue {
19    /// Cheaply creates an empty `SerializedValue`.
20    pub fn empty() -> Self {
21        Self {
22            buf: BytesMut::new(),
23        }
24    }
25
26    pub fn serialize<T: Serialize + ?Sized>(value: &T) -> Result<Self, SerializeError> {
27        // 4 bytes message length + 1 byte message kind + 4 bytes value length.
28        let mut buf = BytesMut::zeroed(9);
29        let serializer = Serializer::new(&mut buf, 0)?;
30        value.serialize(serializer)?;
31        Ok(Self { buf })
32    }
33
34    pub(crate) fn from_bytes_mut(buf: BytesMut) -> Self {
35        // 4 bytes message length + 1 byte message kind + 4 bytes value length + at least 1 byte
36        // value.
37        debug_assert!(buf.len() >= 10);
38
39        Self { buf }
40    }
41
42    pub(crate) fn into_bytes_mut(self) -> BytesMut {
43        self.buf
44    }
45}
46
47impl Deref for SerializedValue {
48    type Target = SerializedValueSlice;
49
50    fn deref(&self) -> &SerializedValueSlice {
51        // 4 bytes message length + 1 byte message kind + 4 bytes value length.
52        SerializedValueSlice::new(&self.buf[9..])
53    }
54}
55
56// The default Debug implementation renders the bytes as ASCII or escape sequences, which isn't
57// particularly useful here.
58impl fmt::Debug for SerializedValue {
59    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
60        f.debug_struct("SerializedValue")
61            .field("buf", &&*self.buf)
62            .finish()
63    }
64}
65
66impl AsRef<SerializedValueSlice> for SerializedValue {
67    fn as_ref(&self) -> &SerializedValueSlice {
68        self
69    }
70}
71
72impl Borrow<SerializedValueSlice> for SerializedValue {
73    fn borrow(&self) -> &SerializedValueSlice {
74        self
75    }
76}
77
78impl AsRef<[u8]> for SerializedValue {
79    fn as_ref(&self) -> &[u8] {
80        self
81    }
82}
83
84impl PartialEq for SerializedValue {
85    fn eq(&self, other: &Self) -> bool {
86        ***self == ***other
87    }
88}
89
90impl PartialEq<SerializedValueSlice> for SerializedValue {
91    fn eq(&self, other: &SerializedValueSlice) -> bool {
92        ***self == **other
93    }
94}
95
96impl PartialEq<[u8]> for SerializedValue {
97    fn eq(&self, other: &[u8]) -> bool {
98        ***self == *other
99    }
100}
101
102impl PartialEq<SerializedValue> for [u8] {
103    fn eq(&self, other: &SerializedValue) -> bool {
104        *self == ***other
105    }
106}
107
108impl Serialize for SerializedValue {
109    fn serialize(&self, serializer: Serializer) -> Result<(), SerializeError> {
110        (**self).serialize(serializer)
111    }
112}
113
114impl Deserialize for SerializedValue {
115    fn deserialize(deserializer: Deserializer) -> Result<Self, DeserializeError> {
116        deserializer
117            .split_off_serialized_value()
118            .map(ToOwned::to_owned)
119    }
120}
121
122#[cfg(feature = "fuzzing")]
123impl<'a> arbitrary::Arbitrary<'a> for SerializedValue {
124    fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
125        let len = u.arbitrary_len::<u8>()?;
126        let bytes = u.bytes(len)?;
127        if bytes.len() >= 10 {
128            Ok(Self::from_bytes_mut(bytes.into()))
129        } else {
130            Err(arbitrary::Error::NotEnoughData)
131        }
132    }
133}
134
135#[derive(Debug, PartialEq, Eq)]
136#[repr(transparent)]
137pub struct SerializedValueSlice([u8]);
138
139impl SerializedValueSlice {
140    pub(crate) fn new<T: AsRef<[u8]> + ?Sized>(buf: &T) -> &Self {
141        let self_ptr = buf.as_ref() as *const [u8] as *const Self;
142        // Safe because of repr(transparent).
143        unsafe { &*self_ptr }
144    }
145
146    pub fn kind(&self) -> Result<ValueKind, DeserializeError> {
147        let mut buf = &self.0;
148        let deserializer = Deserializer::new(&mut buf, 0)?;
149        deserializer.peek_value_kind()
150    }
151
152    pub fn deserialize<T: Deserialize>(&self) -> Result<T, DeserializeError> {
153        let mut buf = &self.0;
154        let deserializer = Deserializer::new(&mut buf, 0)?;
155
156        let res = T::deserialize(deserializer);
157
158        if res.is_ok() && !buf.is_empty() {
159            return Err(DeserializeError::TrailingData);
160        }
161
162        res
163    }
164}
165
166impl Deref for SerializedValueSlice {
167    type Target = [u8];
168
169    fn deref(&self) -> &[u8] {
170        &self.0
171    }
172}
173
174impl AsRef<[u8]> for SerializedValueSlice {
175    fn as_ref(&self) -> &[u8] {
176        self
177    }
178}
179
180impl ToOwned for SerializedValueSlice {
181    type Owned = SerializedValue;
182
183    fn to_owned(&self) -> SerializedValue {
184        SerializedValue::serialize(self).unwrap()
185    }
186}
187
188impl PartialEq<SerializedValue> for SerializedValueSlice {
189    fn eq(&self, other: &SerializedValue) -> bool {
190        **self == ***other
191    }
192}
193
194impl PartialEq<[u8]> for SerializedValueSlice {
195    fn eq(&self, other: &[u8]) -> bool {
196        **self == *other
197    }
198}
199
200impl PartialEq<SerializedValueSlice> for [u8] {
201    fn eq(&self, other: &SerializedValueSlice) -> bool {
202        *self == **other
203    }
204}
205
206impl Serialize for SerializedValueSlice {
207    fn serialize(&self, serializer: Serializer) -> Result<(), SerializeError> {
208        serializer.copy_from_serialized_value(self);
209        Ok(())
210    }
211}