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