zerialize 0.0.1

Zero-copy serialization
Documentation
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
//! Sequences of elements.

use crate::Error;
use crate::wire::{Frame, Message, Packing, Writer};
use std::fmt::{self, Debug};
use std::marker::PhantomData;

/// A sequence of elements: messages, choices, values, or primitives.
///
/// Implementations return elements by value rather than by reference, which is
/// what lets [`ListView`] decode an element only when it is asked for.
pub trait List {
    type Item;

    fn len(&self) -> usize;

    fn is_empty(&self) -> bool {
        self.len() == 0
    }

    fn get(&self, index: usize) -> Option<Self::Item>;

    fn iter(&self) -> ListIter<'_, Self>
    where
        Self: Sized,
    {
        ListIter {
            list: self,
            index: 0,
        }
    }
}

// Implemented for the reference so that a list may be handed out borrowed, as a
// schema may: a variant carrying a list is borrowed by `as_ref` the way one
// carrying a message is.
impl<L: List + ?Sized> List for &L {
    type Item = L::Item;

    fn len(&self) -> usize {
        L::len(self)
    }

    fn get(&self, index: usize) -> Option<L::Item> {
        L::get(self, index)
    }
}

pub struct ListIter<'a, L> {
    list: &'a L,
    index: usize,
}

impl<L: List> Iterator for ListIter<'_, L> {
    type Item = L::Item;

    fn next(&mut self) -> Option<Self::Item> {
        let item = self.list.get(self.index)?;
        self.index += 1;
        Some(item)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.list.len() - self.index;
        (remaining, Some(remaining))
    }
}

impl<L: List> ExactSizeIterator for ListIter<'_, L> {}

/// A list of `Copy` items handed out by value, over one that hands out
/// references to them.
///
/// What a list of primitives or values holds, it holds by value, so this is
/// what an implementation storing them, an `OwnedList<u32>`, is handed out
/// through: `Copied(&self.scores)`.
#[derive(Clone, Copy, Debug)]
pub struct Copied<L>(pub L);

impl<'a, T: Copy + 'a, L: List<Item = &'a T>> List for Copied<L> {
    type Item = T;

    fn len(&self) -> usize {
        self.0.len()
    }

    fn get(&self, index: usize) -> Option<T> {
        self.0.get(index).copied()
    }
}

/// A list that owns its elements, for implementations that build data in
/// memory rather than decoding it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct OwnedList<T> {
    items: Vec<T>,
}

impl<T> OwnedList<T> {
    pub fn new() -> Self {
        Self { items: Vec::new() }
    }

    pub fn push(&mut self, item: T) {
        self.items.push(item);
    }

    pub fn len(&self) -> usize {
        self.items.len()
    }

    pub fn is_empty(&self) -> bool {
        self.items.is_empty()
    }

    pub fn as_slice(&self) -> &[T] {
        &self.items
    }
}

impl<T> Default for OwnedList<T> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T> From<Vec<T>> for OwnedList<T> {
    fn from(items: Vec<T>) -> Self {
        Self { items }
    }
}

impl<T> FromIterator<T> for OwnedList<T> {
    fn from_iter<I: IntoIterator<Item = T>>(items: I) -> Self {
        Self {
            items: items.into_iter().collect(),
        }
    }
}

// Implemented for the reference so that an accessor can hand out `&self.field`,
// with elements borrowed from the list rather than cloned out of it.
impl<'a, T> List for &'a OwnedList<T> {
    type Item = &'a T;

    fn len(&self) -> usize {
        self.items.len()
    }

    fn get(&self, index: usize) -> Option<&'a T> {
        self.items.get(index)
    }
}

/// What an entry of a frame holds.
///
/// A list is a frame, exactly as a message is, with its entries indexed by
/// position rather than by slot, so an element and a field are the same thing:
/// both are addressed by the entry they occupy rather than handed their bytes,
/// because each chooses its own shape on the wire. That is what lets one trait
/// stand for both, and it is what decides whether a name a field is written
/// with is a value or a choice: which of them it is, is which implementation of
/// this exists, rather than how the name is written.
///
/// Implemented here for the primitives, and by the macros for every schema and
/// value.
pub trait Element {
    /// Types that may be encoded as this element.
    ///
    /// This is a GAT so sources containing borrowed data work, and is what a
    /// schema stands apart from an implementation of it by: the source of a
    /// choice is any instantiation of it, and the source of a value is the
    /// value itself.
    type Source<'src>: ?Sized + 'src;

    /// What reading one element gives back, which borrows from the buffer
    /// wherever the element itself does.
    type Item<'buf>;

    /// How a list packs this element, where every one of them is the same
    /// size. A packed list holds its elements one after another rather than
    /// through a table of offsets, so it costs no more than what it holds, and
    /// reaching one is an index into them. An element that says it is packed
    /// says how to read itself out of the bytes it begins at as well.
    const PACKING: Option<Packing> = None;

    #[doc(hidden)]
    fn encode_element<'src>(source: &'src Self::Source<'src>, writer: &mut Writer<'_>);

    /// Reads the entry at `index` of the frame holding it, which is a slot
    /// where that frame is a message and a position where it is a list.
    ///
    /// This is how an element that is not packed is reached, and an element
    /// that is not packed implements it. See [`Element::decode_packed`] for
    /// the other half.
    #[doc(hidden)]
    fn decode_element<'buf>(_list: Message<'buf>, _index: u32) -> Result<Self::Item<'buf>, Error> {
        Err(Error::InvalidFrame)
    }

    /// Reads one element out of the bytes it begins at, which is where its
    /// position times its width puts it.
    ///
    /// This is how a packed element is reached, and a packed element
    /// implements it. [`Element::PACKING`] is what decides which of the two an
    /// element is read by, so each implements the one it is read by and the
    /// other is never called on it.
    #[doc(hidden)]
    fn decode_packed<'buf>(_bytes: &'buf [u8]) -> Result<Self::Item<'buf>, Error> {
        Err(Error::InvalidFrame)
    }
}

// A number is one width on the wire and any bytes of that width are one, so a
// list of them is packed and needs no checking beyond its length.
macro_rules! number_elements {
    ($($ty:ty: $write:ident,)*) => {
        $(
            impl Element for $ty {
                type Source<'src> = $ty;
                type Item<'buf> = $ty;

                const PACKING: Option<Packing> = Some(Packing {
                    width: size_of::<$ty>() as u8,
                    total: true,
                });

                fn encode_element(source: &$ty, writer: &mut Writer<'_>) {
                    writer.$write(*source);
                }

                #[inline]
                fn decode_packed(bytes: &[u8]) -> Result<$ty, Error> {
                    let value = bytes
                        .get(..size_of::<$ty>())
                        .ok_or(Error::UnexpectedEof)?;
                    Ok(<$ty>::from_le_bytes(
                        value.try_into().expect("the slice is exactly sized"),
                    ))
                }
            }
        )*
    };
}

number_elements! {
    u8: write_u8,
    u16: write_u16,
    u32: write_u32,
    u64: write_u64,
    u128: write_u128,
    i8: write_i8,
    i16: write_i16,
    i32: write_i32,
    i64: write_i64,
    i128: write_i128,
    f32: write_f32,
    f64: write_f64,
}

// The two primitives that are one width but not every pattern of it, so a
// packed list of them is read element by element to be checked.
impl Element for bool {
    type Source<'src> = bool;
    type Item<'buf> = bool;

    const PACKING: Option<Packing> = Some(Packing {
        width: 1,
        total: false,
    });

    fn encode_element(source: &bool, writer: &mut Writer<'_>) {
        writer.write_bool(*source);
    }

    #[inline]
    fn decode_packed(bytes: &[u8]) -> Result<bool, Error> {
        match bytes.first().ok_or(Error::UnexpectedEof)? {
            0 => Ok(false),
            1 => Ok(true),
            _ => Err(Error::InvalidBool),
        }
    }
}

impl Element for char {
    type Source<'src> = char;
    type Item<'buf> = char;

    const PACKING: Option<Packing> = Some(Packing {
        width: size_of::<char>() as u8,
        total: false,
    });

    fn encode_element(source: &char, writer: &mut Writer<'_>) {
        writer.write_char(*source);
    }

    #[inline]
    fn decode_packed(bytes: &[u8]) -> Result<char, Error> {
        char::from_u32(u32::decode_packed(bytes)?).ok_or(Error::InvalidChar)
    }
}

// The two elements that are read as handles over the buffer rather than copied
// out of it are named by what they point at, since what a frame holds is the
// element rather than the reference to it.
impl Element for str {
    type Source<'src> = str;
    type Item<'buf> = &'buf str;

    fn encode_element(source: &str, writer: &mut Writer<'_>) {
        writer.write_str(source);
    }

    fn decode_element<'buf>(list: Message<'buf>, index: u32) -> Result<&'buf str, Error> {
        list.read_str(index)
    }
}

impl Element for [u8] {
    type Source<'src> = [u8];
    type Item<'buf> = &'buf [u8];

    fn encode_element(source: &[u8], writer: &mut Writer<'_>) {
        writer.write_bytes(source);
    }

    fn decode_element<'buf>(list: Message<'buf>, index: u32) -> Result<&'buf [u8], Error> {
        list.read_bytes(index)
    }
}

/// A list of encoded elements, each decoded when it is asked for.
///
/// This is the bytes of one frame and what its header said about them, read
/// where the list was reached rather than again at every element. Reaching any
/// one of them is then an index into that frame's offset table, or, where the
/// elements are all one width, into the elements themselves.
pub struct ListView<'buf, E: ?Sized> {
    frame: Frame<'buf>,
    element: PhantomData<fn() -> *const E>,
}

impl<E: ?Sized> Clone for ListView<'_, E> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<E: ?Sized> Copy for ListView<'_, E> {}

impl<'buf, E: ?Sized> ListView<'buf, E> {
    pub(crate) fn new(frame: Frame<'buf>) -> Self {
        Self {
            frame,
            element: PhantomData,
        }
    }

    /// The list as the frame it is, which is what an element is read out of.
    fn as_message(&self, depth: u32, validate: bool) -> Message<'buf> {
        Message::nested(self.frame, depth, validate)
    }

    /// Where an element sits in that frame. An index past what an entry can be
    /// numbered by is one no list in a buffer this size can hold, since every
    /// entry costs a word of the offset table.
    fn position(index: usize) -> Option<u32> {
        u32::try_from(index).ok()
    }
}

impl<'buf, E: Element + ?Sized> List for ListView<'buf, E> {
    type Item = E::Item<'buf>;

    fn len(&self) -> usize {
        self.frame.count()
    }

    fn get(&self, index: usize) -> Option<E::Item<'buf>> {
        if index >= self.len() {
            return None;
        }
        Some(
            self.element(index)
                .expect("elements are validated when the message is decoded"),
        )
    }
}

impl<'buf, E: Element + ?Sized> ListView<'buf, E> {
    /// Reads the element at `index`, which the caller has already bounded.
    ///
    /// A packed element is where its position puts it, so reaching one is an
    /// index into the elements themselves rather than a walk through the frame
    /// holding them. Anything else is an entry of that frame, reached the way
    /// a field of a message is.
    #[inline]
    fn element(&self, index: usize) -> Result<E::Item<'buf>, Error> {
        match E::PACKING {
            Some(packing) => {
                let at = index * usize::from(packing.width);
                let bytes = self
                    .frame
                    .elements()
                    .get(at..)
                    .ok_or(Error::UnexpectedEof)?;
                E::decode_packed(bytes)
            }
            None => {
                let index = Self::position(index).ok_or(Error::UnexpectedEof)?;
                E::decode_element(self.as_message(0, false), index)
            }
        }
    }

    /// Decodes every element, so that [`List::get`] cannot fail afterwards.
    ///
    /// A packed list of numbers never reaches here: reading the frame's header
    /// already said every element is within it, and any bytes of their width
    /// are one. What does reach here is a packed list of the two primitives
    /// that is not true of, and every list that is not packed at all.
    pub(crate) fn validate(&self, depth: u32) -> Result<(), Error> {
        if E::PACKING.is_some() {
            for index in 0..self.len() {
                self.element(index)?;
            }
            return Ok(());
        }
        let list = self.as_message(depth, true);
        for index in 0..self.len() {
            let index = Self::position(index).ok_or(Error::UnexpectedEof)?;
            E::decode_element(list, index)?;
        }
        Ok(())
    }
}

impl<'buf, E: Element + ?Sized> Debug for ListView<'buf, E>
where
    E::Item<'buf>: Debug,
{
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.debug_list().entries(self.iter()).finish()
    }
}