cuprate_epee_encoding/
value.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
//! This module contains a [`EpeeValue`] trait and
//! impls for some possible base epee values.

use alloc::{string::String, vec, vec::Vec};
use core::fmt::Debug;

use bytes::{Buf, BufMut, Bytes, BytesMut};

use cuprate_fixed_bytes::{ByteArray, ByteArrayVec};
use cuprate_helper::cast::u64_to_usize;

use crate::{
    io::{checked_read_primitive, checked_write_primitive},
    varint::{read_varint, write_varint},
    write_bytes, write_iterator, EpeeObject, Error, InnerMarker, Marker, Result,
    MAX_STRING_LEN_POSSIBLE,
};

/// A trait for epee values.
///
/// All [`EpeeObject`] objects automatically implement [`EpeeValue`].
pub trait EpeeValue: Sized {
    const MARKER: Marker;

    fn read<B: Buf>(r: &mut B, marker: &Marker) -> Result<Self>;

    fn should_write(&self) -> bool {
        true
    }

    /// This is different than default field values and instead is the default
    /// value of a whole type.
    ///
    /// For example a `Vec` has a default value of a zero length vec as when a
    /// sequence has no entries it is not encoded.
    fn epee_default_value() -> Option<Self> {
        None
    }

    fn write<B: BufMut>(self, w: &mut B) -> Result<()>;
}

impl<T: EpeeObject> EpeeValue for T {
    const MARKER: Marker = Marker::new(InnerMarker::Object);

    fn read<B: Buf>(r: &mut B, marker: &Marker) -> Result<Self> {
        if marker != &Self::MARKER {
            return Err(Error::Format("Marker does not match expected Marker"));
        }

        let mut skipped_objects = 0;
        crate::read_object(r, &mut skipped_objects)
    }

    fn write<B: BufMut>(self, w: &mut B) -> Result<()> {
        write_varint(self.number_of_fields(), w)?;
        self.write_fields(w)
    }
}

impl<T: EpeeObject> EpeeValue for Vec<T> {
    const MARKER: Marker = T::MARKER.into_seq();

    fn read<B: Buf>(r: &mut B, marker: &Marker) -> Result<Self> {
        if !marker.is_seq {
            return Err(Error::Format(
                "Marker is not sequence when a sequence was expected",
            ));
        }
        let len = u64_to_usize(read_varint(r)?);

        let individual_marker = Marker::new(marker.inner_marker);

        let mut res = Self::with_capacity(len);
        for _ in 0..len {
            res.push(T::read(r, &individual_marker)?);
        }
        Ok(res)
    }

    fn should_write(&self) -> bool {
        !self.is_empty()
    }

    fn epee_default_value() -> Option<Self> {
        Some(Self::new())
    }

    fn write<B: BufMut>(self, w: &mut B) -> Result<()> {
        write_iterator(self.into_iter(), w)
    }
}

impl<T: EpeeObject + Debug, const N: usize> EpeeValue for [T; N] {
    const MARKER: Marker = <T>::MARKER.into_seq();

    fn read<B: Buf>(r: &mut B, marker: &Marker) -> Result<Self> {
        let vec = Vec::<T>::read(r, marker)?;

        if vec.len() != N {
            return Err(Error::Format("Array has incorrect length"));
        }

        Ok(vec.try_into().unwrap())
    }

    fn write<B: BufMut>(self, w: &mut B) -> Result<()> {
        write_iterator(self.into_iter(), w)
    }
}

macro_rules! epee_numb {
    ($numb:ty, $marker:ident, $read_fn:ident, $write_fn:ident) => {
        impl EpeeValue for $numb {
            const MARKER: Marker = Marker::new(InnerMarker::$marker);

            fn read<B: Buf>(r: &mut B, marker: &Marker) -> Result<Self> {
                if marker != &Self::MARKER {
                    return Err(Error::Format("Marker does not match expected Marker"));
                }

                checked_read_primitive(r, Buf::$read_fn)
            }

            fn write<B: BufMut>(self, w: &mut B) -> Result<()> {
                checked_write_primitive(w, BufMut::$write_fn, self)
            }
        }
    };
}

epee_numb!(i64, I64, get_i64_le, put_i64_le);
epee_numb!(i32, I32, get_i32_le, put_i32_le);
epee_numb!(i16, I16, get_i16_le, put_i16_le);
epee_numb!(i8, I8, get_i8, put_i8);
epee_numb!(u8, U8, get_u8, put_u8);
epee_numb!(u16, U16, get_u16_le, put_u16_le);
epee_numb!(u32, U32, get_u32_le, put_u32_le);
epee_numb!(u64, U64, get_u64_le, put_u64_le);
epee_numb!(f64, F64, get_f64_le, put_f64_le);

impl EpeeValue for bool {
    const MARKER: Marker = Marker::new(InnerMarker::Bool);

    fn read<B: Buf>(r: &mut B, marker: &Marker) -> Result<Self> {
        if marker != &Self::MARKER {
            return Err(Error::Format("Marker does not match expected Marker"));
        }

        Ok(checked_read_primitive(r, Buf::get_u8)? != 0)
    }

    fn write<B: BufMut>(self, w: &mut B) -> Result<()> {
        checked_write_primitive(w, BufMut::put_u8, if self { 1 } else { 0 })
    }
}

impl EpeeValue for Vec<u8> {
    const MARKER: Marker = Marker::new(InnerMarker::String);

    fn read<B: Buf>(r: &mut B, marker: &Marker) -> Result<Self> {
        if marker != &Self::MARKER {
            return Err(Error::Format("Marker does not match expected Marker"));
        }

        let len = read_varint(r)?;
        if len > MAX_STRING_LEN_POSSIBLE {
            return Err(Error::Format("Byte array exceeded max length"));
        }

        let len = u64_to_usize(len);

        if r.remaining() < len {
            return Err(Error::IO("Not enough bytes to fill object"));
        }

        let mut res = vec![0; len];
        r.copy_to_slice(&mut res);

        Ok(res)
    }

    fn epee_default_value() -> Option<Self> {
        Some(Self::new())
    }

    fn should_write(&self) -> bool {
        !self.is_empty()
    }

    fn write<B: BufMut>(self, w: &mut B) -> Result<()> {
        write_bytes(self, w)
    }
}

impl EpeeValue for Bytes {
    const MARKER: Marker = Marker::new(InnerMarker::String);

    fn read<B: Buf>(r: &mut B, marker: &Marker) -> Result<Self> {
        if marker != &Self::MARKER {
            return Err(Error::Format("Marker does not match expected Marker"));
        }

        let len = read_varint(r)?;
        if len > MAX_STRING_LEN_POSSIBLE {
            return Err(Error::Format("Byte array exceeded max length"));
        }

        let len = u64_to_usize(len);

        if r.remaining() < len {
            return Err(Error::IO("Not enough bytes to fill object"));
        }

        Ok(r.copy_to_bytes(len))
    }

    fn epee_default_value() -> Option<Self> {
        Some(Self::new())
    }

    fn should_write(&self) -> bool {
        !self.is_empty()
    }

    fn write<B: BufMut>(self, w: &mut B) -> Result<()> {
        write_bytes(self, w)
    }
}

impl EpeeValue for BytesMut {
    const MARKER: Marker = Marker::new(InnerMarker::String);

    fn read<B: Buf>(r: &mut B, marker: &Marker) -> Result<Self> {
        if marker != &Self::MARKER {
            return Err(Error::Format("Marker does not match expected Marker"));
        }

        let len = read_varint(r)?;
        if len > MAX_STRING_LEN_POSSIBLE {
            return Err(Error::Format("Byte array exceeded max length"));
        }

        let len = u64_to_usize(len);

        if r.remaining() < len {
            return Err(Error::IO("Not enough bytes to fill object"));
        }

        let mut bytes = Self::zeroed(len);
        r.copy_to_slice(&mut bytes);

        Ok(bytes)
    }

    fn epee_default_value() -> Option<Self> {
        Some(Self::new())
    }

    fn should_write(&self) -> bool {
        !self.is_empty()
    }

    fn write<B: BufMut>(self, w: &mut B) -> Result<()> {
        write_bytes(self, w)
    }
}

impl<const N: usize> EpeeValue for ByteArrayVec<N> {
    const MARKER: Marker = Marker::new(InnerMarker::String);

    fn read<B: Buf>(r: &mut B, marker: &Marker) -> Result<Self> {
        if marker != &Self::MARKER {
            return Err(Error::Format("Marker does not match expected Marker"));
        }

        let len = read_varint(r)?;
        if len > MAX_STRING_LEN_POSSIBLE {
            return Err(Error::Format("Byte array exceeded max length"));
        }

        let len = u64_to_usize(len);

        if r.remaining() < len {
            return Err(Error::IO("Not enough bytes to fill object"));
        }

        Self::try_from(r.copy_to_bytes(len)).map_err(|_| Error::Format("Field has invalid length"))
    }

    fn epee_default_value() -> Option<Self> {
        Some(Self::try_from(Bytes::new()).unwrap())
    }

    fn should_write(&self) -> bool {
        !self.is_empty()
    }

    fn write<B: BufMut>(self, w: &mut B) -> Result<()> {
        let bytes = self.take_bytes();
        write_bytes(bytes, w)
    }
}

impl<const N: usize> EpeeValue for ByteArray<N> {
    const MARKER: Marker = Marker::new(InnerMarker::String);

    fn read<B: Buf>(r: &mut B, marker: &Marker) -> Result<Self> {
        if marker != &Self::MARKER {
            return Err(Error::Format("Marker does not match expected Marker"));
        }

        let len = u64_to_usize(read_varint(r)?);
        if len != N {
            return Err(Error::Format("Byte array has incorrect length"));
        }

        if r.remaining() < N {
            return Err(Error::IO("Not enough bytes to fill object"));
        }

        Self::try_from(r.copy_to_bytes(N)).map_err(|_| Error::Format("Field has invalid length"))
    }

    fn write<B: BufMut>(self, w: &mut B) -> Result<()> {
        let bytes = self.take_bytes();
        write_bytes(bytes, w)
    }
}

impl EpeeValue for String {
    const MARKER: Marker = Marker::new(InnerMarker::String);

    fn read<B: Buf>(r: &mut B, marker: &Marker) -> Result<Self> {
        let bytes = Vec::<u8>::read(r, marker)?;
        Self::from_utf8(bytes).map_err(|_| Error::Format("Invalid string"))
    }

    fn should_write(&self) -> bool {
        !self.is_empty()
    }

    fn epee_default_value() -> Option<Self> {
        Some(Self::new())
    }

    fn write<B: BufMut>(self, w: &mut B) -> Result<()> {
        write_bytes(self, w)
    }
}

impl<const N: usize> EpeeValue for [u8; N] {
    const MARKER: Marker = Marker::new(InnerMarker::String);

    fn read<B: Buf>(r: &mut B, marker: &Marker) -> Result<Self> {
        let bytes = Vec::<u8>::read(r, marker)?;

        if bytes.len() != N {
            return Err(Error::Format("Byte array has incorrect length"));
        }

        Ok(bytes.try_into().unwrap())
    }

    fn write<B: BufMut>(self, w: &mut B) -> Result<()> {
        write_bytes(self, w)
    }
}

impl<const N: usize> EpeeValue for Vec<[u8; N]> {
    const MARKER: Marker = <[u8; N]>::MARKER.into_seq();

    fn read<B: Buf>(r: &mut B, marker: &Marker) -> Result<Self> {
        if !marker.is_seq {
            return Err(Error::Format(
                "Marker is not sequence when a sequence was expected",
            ));
        }

        let len = u64_to_usize(read_varint(r)?);

        let individual_marker = Marker::new(marker.inner_marker);

        let mut res = Self::with_capacity(len);
        for _ in 0..len {
            res.push(<[u8; N]>::read(r, &individual_marker)?);
        }
        Ok(res)
    }

    fn should_write(&self) -> bool {
        !self.is_empty()
    }

    fn epee_default_value() -> Option<Self> {
        Some(Self::new())
    }

    fn write<B: BufMut>(self, w: &mut B) -> Result<()> {
        write_iterator(self.into_iter(), w)
    }
}

macro_rules! epee_seq {
    ($val:ty) => {
        impl EpeeValue for Vec<$val> {
            const MARKER: Marker = <$val>::MARKER.into_seq();

            fn read<B: Buf>(r: &mut B, marker: &Marker) -> Result<Self> {
                if !marker.is_seq {
                    return Err(Error::Format(
                        "Marker is not sequence when a sequence was expected",
                    ));
                }

                let len = u64_to_usize(read_varint(r)?);

                let individual_marker = Marker::new(marker.inner_marker.clone());

                let mut res = Vec::with_capacity(len);
                for _ in 0..len {
                    res.push(<$val>::read(r, &individual_marker)?);
                }
                Ok(res)
            }

            fn should_write(&self) -> bool {
                !self.is_empty()
            }

            fn epee_default_value() -> Option<Self> {
                Some(Vec::new())
            }

            fn write<B: BufMut>(self, w: &mut B) -> Result<()> {
                write_iterator(self.into_iter(), w)
            }
        }

        impl<const N: usize> EpeeValue for [$val; N] {
            const MARKER: Marker = <$val>::MARKER.into_seq();

            fn read<B: Buf>(r: &mut B, marker: &Marker) -> Result<Self> {
                let vec = Vec::<$val>::read(r, marker)?;

                if vec.len() != N {
                    return Err(Error::Format("Array has incorrect length"));
                }

                Ok(vec.try_into().unwrap())
            }

            fn write<B: BufMut>(self, w: &mut B) -> Result<()> {
                write_iterator(self.into_iter(), w)
            }
        }
    };
}

epee_seq!(i64);
epee_seq!(i32);
epee_seq!(i16);
epee_seq!(i8);
epee_seq!(u64);
epee_seq!(u32);
epee_seq!(u16);
epee_seq!(f64);
epee_seq!(bool);
epee_seq!(Vec<u8>);
epee_seq!(String);
epee_seq!(Bytes);
epee_seq!(BytesMut);

impl<T: EpeeValue> EpeeValue for Option<T> {
    const MARKER: Marker = T::MARKER;

    fn read<B: Buf>(r: &mut B, marker: &Marker) -> Result<Self> {
        Ok(Some(T::read(r, marker)?))
    }

    fn should_write(&self) -> bool {
        match self {
            Some(t) => t.should_write(),
            None => false,
        }
    }

    fn epee_default_value() -> Option<Self> {
        Some(None)
    }

    fn write<B: BufMut>(self, w: &mut B) -> Result<()> {
        match self {
            Some(t) => t.write(w)?,
            None => panic!("Can't write an Option::None value, this should be handled elsewhere"),
        }
        Ok(())
    }
}