cuprate_epee_encoding/
value.rs

1//! This module contains a [`EpeeValue`] trait and
2//! impls for some possible base epee values.
3
4use alloc::{string::String, vec, vec::Vec};
5use core::fmt::Debug;
6
7use bytes::{Buf, BufMut, Bytes, BytesMut};
8
9use cuprate_fixed_bytes::{ByteArray, ByteArrayVec};
10
11use crate::{
12    io::{checked_read_primitive, checked_write_primitive},
13    varint::{read_varint, write_varint},
14    write_bytes, write_iterator, EpeeObject, Error, InnerMarker, Marker, Result,
15    MAX_STRING_LEN_POSSIBLE,
16};
17
18/// A trait for epee values.
19///
20/// All [`EpeeObject`] objects automatically implement [`EpeeValue`].
21pub trait EpeeValue: Sized {
22    const MARKER: Marker;
23
24    fn read<B: Buf>(r: &mut B, marker: &Marker) -> Result<Self>;
25
26    fn should_write(&self) -> bool {
27        true
28    }
29
30    /// This is different than default field values and instead is the default
31    /// value of a whole type.
32    ///
33    /// For example a `Vec` has a default value of a zero length vec as when a
34    /// sequence has no entries it is not encoded.
35    fn epee_default_value() -> Option<Self> {
36        None
37    }
38
39    fn write<B: BufMut>(self, w: &mut B) -> Result<()>;
40}
41
42impl<T: EpeeObject> EpeeValue for T {
43    const MARKER: Marker = Marker::new(InnerMarker::Object);
44
45    fn read<B: Buf>(r: &mut B, marker: &Marker) -> Result<Self> {
46        if marker != &Self::MARKER {
47            return Err(Error::Format("Marker does not match expected Marker"));
48        }
49
50        let mut skipped_objects = 0;
51        crate::read_object(r, &mut skipped_objects)
52    }
53
54    fn write<B: BufMut>(self, w: &mut B) -> Result<()> {
55        write_varint(self.number_of_fields(), w)?;
56        self.write_fields(w)
57    }
58}
59
60impl<T: EpeeObject> EpeeValue for Vec<T> {
61    const MARKER: Marker = T::MARKER.into_seq();
62
63    fn read<B: Buf>(r: &mut B, marker: &Marker) -> Result<Self> {
64        if !marker.is_seq {
65            return Err(Error::Format(
66                "Marker is not sequence when a sequence was expected",
67            ));
68        }
69        let len = read_varint(r)?;
70
71        let individual_marker = Marker::new(marker.inner_marker);
72
73        let mut res = Self::with_capacity(len);
74        for _ in 0..len {
75            res.push(T::read(r, &individual_marker)?);
76        }
77        Ok(res)
78    }
79
80    fn should_write(&self) -> bool {
81        !self.is_empty()
82    }
83
84    fn epee_default_value() -> Option<Self> {
85        Some(Self::new())
86    }
87
88    fn write<B: BufMut>(self, w: &mut B) -> Result<()> {
89        write_iterator(self.into_iter(), w)
90    }
91}
92
93impl<T: EpeeObject + Debug, const N: usize> EpeeValue for [T; N] {
94    const MARKER: Marker = <T>::MARKER.into_seq();
95
96    fn read<B: Buf>(r: &mut B, marker: &Marker) -> Result<Self> {
97        let vec = Vec::<T>::read(r, marker)?;
98
99        if vec.len() != N {
100            return Err(Error::Format("Array has incorrect length"));
101        }
102
103        Ok(vec.try_into().unwrap())
104    }
105
106    fn write<B: BufMut>(self, w: &mut B) -> Result<()> {
107        write_iterator(self.into_iter(), w)
108    }
109}
110
111macro_rules! epee_numb {
112    ($numb:ty, $marker:ident, $read_fn:ident, $write_fn:ident) => {
113        impl EpeeValue for $numb {
114            const MARKER: Marker = Marker::new(InnerMarker::$marker);
115
116            fn read<B: Buf>(r: &mut B, marker: &Marker) -> Result<Self> {
117                if marker != &Self::MARKER {
118                    return Err(Error::Format("Marker does not match expected Marker"));
119                }
120
121                checked_read_primitive(r, Buf::$read_fn)
122            }
123
124            fn write<B: BufMut>(self, w: &mut B) -> Result<()> {
125                checked_write_primitive(w, BufMut::$write_fn, self)
126            }
127        }
128    };
129}
130
131epee_numb!(i64, I64, get_i64_le, put_i64_le);
132epee_numb!(i32, I32, get_i32_le, put_i32_le);
133epee_numb!(i16, I16, get_i16_le, put_i16_le);
134epee_numb!(i8, I8, get_i8, put_i8);
135epee_numb!(u8, U8, get_u8, put_u8);
136epee_numb!(u16, U16, get_u16_le, put_u16_le);
137epee_numb!(u32, U32, get_u32_le, put_u32_le);
138epee_numb!(u64, U64, get_u64_le, put_u64_le);
139epee_numb!(f64, F64, get_f64_le, put_f64_le);
140
141impl EpeeValue for bool {
142    const MARKER: Marker = Marker::new(InnerMarker::Bool);
143
144    fn read<B: Buf>(r: &mut B, marker: &Marker) -> Result<Self> {
145        if marker != &Self::MARKER {
146            return Err(Error::Format("Marker does not match expected Marker"));
147        }
148
149        Ok(checked_read_primitive(r, Buf::get_u8)? != 0)
150    }
151
152    fn write<B: BufMut>(self, w: &mut B) -> Result<()> {
153        checked_write_primitive(w, BufMut::put_u8, if self { 1 } else { 0 })
154    }
155}
156
157impl EpeeValue for Vec<u8> {
158    const MARKER: Marker = Marker::new(InnerMarker::String);
159
160    fn read<B: Buf>(r: &mut B, marker: &Marker) -> Result<Self> {
161        if marker != &Self::MARKER {
162            return Err(Error::Format("Marker does not match expected Marker"));
163        }
164
165        let len = read_varint(r)?;
166        if len > MAX_STRING_LEN_POSSIBLE {
167            return Err(Error::Format("Byte array exceeded max length"));
168        }
169
170        if r.remaining() < len {
171            return Err(Error::IO("Not enough bytes to fill object"));
172        }
173
174        let mut res = vec![0; len];
175        r.copy_to_slice(&mut res);
176
177        Ok(res)
178    }
179
180    fn epee_default_value() -> Option<Self> {
181        Some(Self::new())
182    }
183
184    fn should_write(&self) -> bool {
185        !self.is_empty()
186    }
187
188    fn write<B: BufMut>(self, w: &mut B) -> Result<()> {
189        write_bytes(self, w)
190    }
191}
192
193impl EpeeValue for Bytes {
194    const MARKER: Marker = Marker::new(InnerMarker::String);
195
196    fn read<B: Buf>(r: &mut B, marker: &Marker) -> Result<Self> {
197        if marker != &Self::MARKER {
198            return Err(Error::Format("Marker does not match expected Marker"));
199        }
200
201        let len = read_varint(r)?;
202        if len > MAX_STRING_LEN_POSSIBLE {
203            return Err(Error::Format("Byte array exceeded max length"));
204        }
205
206        if r.remaining() < len {
207            return Err(Error::IO("Not enough bytes to fill object"));
208        }
209
210        Ok(r.copy_to_bytes(len))
211    }
212
213    fn epee_default_value() -> Option<Self> {
214        Some(Self::new())
215    }
216
217    fn should_write(&self) -> bool {
218        !self.is_empty()
219    }
220
221    fn write<B: BufMut>(self, w: &mut B) -> Result<()> {
222        write_bytes(self, w)
223    }
224}
225
226impl EpeeValue for BytesMut {
227    const MARKER: Marker = Marker::new(InnerMarker::String);
228
229    fn read<B: Buf>(r: &mut B, marker: &Marker) -> Result<Self> {
230        if marker != &Self::MARKER {
231            return Err(Error::Format("Marker does not match expected Marker"));
232        }
233
234        let len = read_varint(r)?;
235        if len > MAX_STRING_LEN_POSSIBLE {
236            return Err(Error::Format("Byte array exceeded max length"));
237        }
238
239        if r.remaining() < len {
240            return Err(Error::IO("Not enough bytes to fill object"));
241        }
242
243        let mut bytes = Self::zeroed(len);
244        r.copy_to_slice(&mut bytes);
245
246        Ok(bytes)
247    }
248
249    fn epee_default_value() -> Option<Self> {
250        Some(Self::new())
251    }
252
253    fn should_write(&self) -> bool {
254        !self.is_empty()
255    }
256
257    fn write<B: BufMut>(self, w: &mut B) -> Result<()> {
258        write_bytes(self, w)
259    }
260}
261
262impl<const N: usize> EpeeValue for ByteArrayVec<N> {
263    const MARKER: Marker = Marker::new(InnerMarker::String);
264
265    fn read<B: Buf>(r: &mut B, marker: &Marker) -> Result<Self> {
266        if marker != &Self::MARKER {
267            return Err(Error::Format("Marker does not match expected Marker"));
268        }
269
270        let len = read_varint::<_, usize>(r)?;
271        if len > MAX_STRING_LEN_POSSIBLE {
272            return Err(Error::Format("Byte array exceeded max length"));
273        }
274
275        if r.remaining() < len {
276            return Err(Error::IO("Not enough bytes to fill object"));
277        }
278
279        Self::try_from(r.copy_to_bytes(len)).map_err(|_| Error::Format("Field has invalid length"))
280    }
281
282    fn epee_default_value() -> Option<Self> {
283        Some(Self::try_from(Bytes::new()).unwrap())
284    }
285
286    fn should_write(&self) -> bool {
287        !self.is_empty()
288    }
289
290    fn write<B: BufMut>(self, w: &mut B) -> Result<()> {
291        let bytes = self.take_bytes();
292        write_bytes(bytes, w)
293    }
294}
295
296impl<const N: usize> EpeeValue for ByteArray<N> {
297    const MARKER: Marker = Marker::new(InnerMarker::String);
298
299    fn read<B: Buf>(r: &mut B, marker: &Marker) -> Result<Self> {
300        if marker != &Self::MARKER {
301            return Err(Error::Format("Marker does not match expected Marker"));
302        }
303
304        let len = read_varint::<_, usize>(r)?;
305        if len != N {
306            return Err(Error::Format("Byte array has incorrect length"));
307        }
308
309        if r.remaining() < N {
310            return Err(Error::IO("Not enough bytes to fill object"));
311        }
312
313        Self::try_from(r.copy_to_bytes(N)).map_err(|_| Error::Format("Field has invalid length"))
314    }
315
316    fn write<B: BufMut>(self, w: &mut B) -> Result<()> {
317        let bytes = self.take_bytes();
318        write_bytes(bytes, w)
319    }
320}
321
322impl EpeeValue for String {
323    const MARKER: Marker = Marker::new(InnerMarker::String);
324
325    fn read<B: Buf>(r: &mut B, marker: &Marker) -> Result<Self> {
326        let bytes = Vec::<u8>::read(r, marker)?;
327        Self::from_utf8(bytes).map_err(|_| Error::Format("Invalid string"))
328    }
329
330    fn should_write(&self) -> bool {
331        !self.is_empty()
332    }
333
334    fn epee_default_value() -> Option<Self> {
335        Some(Self::new())
336    }
337
338    fn write<B: BufMut>(self, w: &mut B) -> Result<()> {
339        write_bytes(self, w)
340    }
341}
342
343impl<const N: usize> EpeeValue for [u8; N] {
344    const MARKER: Marker = Marker::new(InnerMarker::String);
345
346    fn read<B: Buf>(r: &mut B, marker: &Marker) -> Result<Self> {
347        let bytes = Vec::<u8>::read(r, marker)?;
348
349        if bytes.len() != N {
350            return Err(Error::Format("Byte array has incorrect length"));
351        }
352
353        Ok(bytes.try_into().unwrap())
354    }
355
356    fn write<B: BufMut>(self, w: &mut B) -> Result<()> {
357        write_bytes(self, w)
358    }
359}
360
361impl<const N: usize> EpeeValue for Vec<[u8; N]> {
362    const MARKER: Marker = <[u8; N]>::MARKER.into_seq();
363
364    fn read<B: Buf>(r: &mut B, marker: &Marker) -> Result<Self> {
365        if !marker.is_seq {
366            return Err(Error::Format(
367                "Marker is not sequence when a sequence was expected",
368            ));
369        }
370
371        let len = read_varint(r)?;
372
373        let individual_marker = Marker::new(marker.inner_marker);
374
375        let mut res = Self::with_capacity(len);
376        for _ in 0..len {
377            res.push(<[u8; N]>::read(r, &individual_marker)?);
378        }
379        Ok(res)
380    }
381
382    fn should_write(&self) -> bool {
383        !self.is_empty()
384    }
385
386    fn epee_default_value() -> Option<Self> {
387        Some(Self::new())
388    }
389
390    fn write<B: BufMut>(self, w: &mut B) -> Result<()> {
391        write_iterator(self.into_iter(), w)
392    }
393}
394
395macro_rules! epee_seq {
396    ($val:ty) => {
397        impl EpeeValue for Vec<$val> {
398            const MARKER: Marker = <$val>::MARKER.into_seq();
399
400            fn read<B: Buf>(r: &mut B, marker: &Marker) -> Result<Self> {
401                if !marker.is_seq {
402                    return Err(Error::Format(
403                        "Marker is not sequence when a sequence was expected",
404                    ));
405                }
406
407                let len = read_varint(r)?;
408
409                let individual_marker = Marker::new(marker.inner_marker.clone());
410
411                let mut res = Vec::with_capacity(len);
412                for _ in 0..len {
413                    res.push(<$val>::read(r, &individual_marker)?);
414                }
415                Ok(res)
416            }
417
418            fn should_write(&self) -> bool {
419                !self.is_empty()
420            }
421
422            fn epee_default_value() -> Option<Self> {
423                Some(Vec::new())
424            }
425
426            fn write<B: BufMut>(self, w: &mut B) -> Result<()> {
427                write_iterator(self.into_iter(), w)
428            }
429        }
430
431        impl<const N: usize> EpeeValue for [$val; N] {
432            const MARKER: Marker = <$val>::MARKER.into_seq();
433
434            fn read<B: Buf>(r: &mut B, marker: &Marker) -> Result<Self> {
435                let vec = Vec::<$val>::read(r, marker)?;
436
437                if vec.len() != N {
438                    return Err(Error::Format("Array has incorrect length"));
439                }
440
441                Ok(vec.try_into().unwrap())
442            }
443
444            fn write<B: BufMut>(self, w: &mut B) -> Result<()> {
445                write_iterator(self.into_iter(), w)
446            }
447        }
448    };
449}
450
451epee_seq!(i64);
452epee_seq!(i32);
453epee_seq!(i16);
454epee_seq!(i8);
455epee_seq!(u64);
456epee_seq!(u32);
457epee_seq!(u16);
458epee_seq!(f64);
459epee_seq!(bool);
460epee_seq!(Vec<u8>);
461epee_seq!(String);
462epee_seq!(Bytes);
463epee_seq!(BytesMut);
464
465impl<T: EpeeValue> EpeeValue for Option<T> {
466    const MARKER: Marker = T::MARKER;
467
468    fn read<B: Buf>(r: &mut B, marker: &Marker) -> Result<Self> {
469        Ok(Some(T::read(r, marker)?))
470    }
471
472    fn should_write(&self) -> bool {
473        match self {
474            Some(t) => t.should_write(),
475            None => false,
476        }
477    }
478
479    fn epee_default_value() -> Option<Self> {
480        Some(None)
481    }
482
483    fn write<B: BufMut>(self, w: &mut B) -> Result<()> {
484        match self {
485            Some(t) => t.write(w)?,
486            None => panic!("Can't write an Option::None value, this should be handled elsewhere"),
487        }
488        Ok(())
489    }
490}