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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! Table-based decoding.

use super::StructMetadata;
use super::TableEncoder;
use crate::inplace::InplaceOption;
use crate::protobuf::FieldReader;
use crate::protobuf::MessageReader;
use crate::Error;
use crate::FieldDecode;
use crate::MessageDecode;
use core::marker::PhantomData;
use std::mem::MaybeUninit;
use std::slice;

/// Calls `f` on `item`, splitting the pointer and initialized flag out.
///
/// # Safety
///
/// The caller must ensure that on the return, the bool specifies the
/// initialized state of the item.
unsafe fn run_inplace<T, R>(
    item: &mut InplaceOption<'_, T>,
    f: impl FnOnce(*mut u8, &mut bool) -> R,
) -> R {
    let mut initialized = item.forget();
    let base = item.as_mut_ptr().cast::<u8>();
    let r = f(base, &mut initialized);
    if initialized {
        // SAFETY: the caller ensures that `item` is initialized.
        unsafe { item.set_init_unchecked() };
    }
    r
}

impl<'de, T, R> MessageDecode<'de, T, R> for TableEncoder
where
    T: StructDecodeMetadata<'de, R>,
{
    fn read_message(
        item: &mut InplaceOption<'_, T>,
        reader: MessageReader<'de, '_, R>,
    ) -> crate::Result<()> {
        // SAFETY: T guarantees that the metadata is valid.
        unsafe {
            run_inplace(item, |base, initialized| {
                read_fields(
                    T::NUMBERS,
                    T::DECODERS,
                    T::OFFSETS,
                    base,
                    initialized,
                    reader,
                )
            })
        }
    }
}

impl<'de, T, R> FieldDecode<'de, T, R> for TableEncoder
where
    T: StructDecodeMetadata<'de, R>,
{
    // Override the default implementation to use the table decoder directly.
    // This saves code size by avoiding extra stub functions and vtables.
    const ENTRY: DecoderEntry<'de, T, R> = DecoderEntry::table();

    fn read_field(
        item: &mut InplaceOption<'_, T>,
        reader: FieldReader<'de, '_, R>,
    ) -> crate::Result<()> {
        // SAFETY: T guarantees that the metadata is valid.
        unsafe {
            run_inplace(item, |base, initialized| {
                read_message(
                    T::NUMBERS,
                    T::DECODERS,
                    T::OFFSETS,
                    base,
                    initialized,
                    reader,
                )
            })
        }
    }

    fn default_field(item: &mut InplaceOption<'_, T>) -> crate::Result<()> {
        // SAFETY: T guarantees that the metadata is valid.
        unsafe {
            run_inplace(item, |base, initialized| {
                default_fields(T::DECODERS, T::OFFSETS, base, initialized)
            })
        }
    }
}

/// Read a field as a message from the provided field metadata.
///
/// # Safety
///
/// The caller must ensure that `base` points to a location that can be written
/// to, that `struct_initialized` is set correctly, and that the metadata is
/// correct and complete for the type of the object pointed to by `base`.
#[doc(hidden)] // only used publicly in mesh_derive
pub unsafe fn read_message<R>(
    numbers: &[u32],
    decoders: &[ErasedDecoderEntry],
    offsets: &[usize],
    base: *mut u8,
    struct_initialized: &mut bool,
    reader: FieldReader<'_, '_, R>,
) -> Result<(), Error> {
    assert_eq!(numbers.len(), decoders.len());
    assert_eq!(numbers.len(), offsets.len());
    // SAFETY: guaranteed by caller and by the assertions above.
    unsafe {
        // Convert the slices to pointers and a single length to shrink
        // code size.
        read_message_by_ptr(
            numbers.len(),
            numbers.as_ptr(),
            decoders.as_ptr(),
            offsets.as_ptr(),
            base,
            struct_initialized,
            reader,
        )
    }
}

// Don't inline this since it is used by every table decoder instantiation.
#[inline(never)]
unsafe fn read_message_by_ptr<R>(
    count: usize,
    numbers: *const u32,
    decoders: *const ErasedDecoderEntry,
    offsets: *const usize,
    base: *mut u8,
    struct_initialized: &mut bool,
    reader: FieldReader<'_, '_, R>,
) -> Result<(), Error> {
    // SAFETY: guaranteed by caller.
    unsafe {
        read_fields_inline(
            slice::from_raw_parts(numbers, count),
            slice::from_raw_parts(decoders, count),
            slice::from_raw_parts(offsets, count),
            base,
            struct_initialized,
            reader.message()?,
        )
    }
}

/// Read a message from the provided field metadata.
///
/// # Safety
///
/// The caller must ensure that `base` points to a location that can be written
/// to, that `struct_initialized` is set correctly, and that the metadata is
/// correct and complete for the type of the object pointed to by `base`.
unsafe fn read_fields<R>(
    numbers: &[u32],
    decoders: &[ErasedDecoderEntry],
    offsets: &[usize],
    base: *mut u8,
    struct_initialized: &mut bool,
    reader: MessageReader<'_, '_, R>,
) -> Result<(), Error> {
    assert_eq!(numbers.len(), decoders.len());
    assert_eq!(numbers.len(), offsets.len());
    // SAFETY: guaranteed by caller and by the assertions above.
    unsafe {
        // Convert the slices to pointers and a single length to shrink
        // code size.
        read_fields_by_ptr(
            numbers.len(),
            numbers.as_ptr(),
            decoders.as_ptr(),
            offsets.as_ptr(),
            base,
            struct_initialized,
            reader,
        )
    }
}

// Don't inline this since it is used by every table decoder instantiation.
#[inline(never)]
unsafe fn read_fields_by_ptr<R>(
    count: usize,
    numbers: *const u32,
    decoders: *const ErasedDecoderEntry,
    offsets: *const usize,
    base: *mut u8,
    struct_initialized: &mut bool,
    reader: MessageReader<'_, '_, R>,
) -> Result<(), Error> {
    // SAFETY: guaranteed by caller.
    unsafe {
        read_fields_inline(
            slice::from_raw_parts(numbers, count),
            slice::from_raw_parts(decoders, count),
            slice::from_raw_parts(offsets, count),
            base,
            struct_initialized,
            reader,
        )
    }
}

/// Reads fields from the provided field metadata.
///
/// # Safety
///
/// The caller must ensure that `base` points to a location that can be written
/// to, that `initialized` is set correctly, and that the metadata is correct
/// and complete for the type of the object pointed to by `base`.
unsafe fn read_fields_inline<R>(
    numbers: &[u32],
    decoders: &[ErasedDecoderEntry],
    offsets: &[usize],
    base: *mut u8,
    struct_initialized: &mut bool,
    reader: MessageReader<'_, '_, R>,
) -> Result<(), Error> {
    const STACK_LIMIT: usize = 32;
    let mut field_init_static;
    let mut field_init_dynamic;
    let field_inits = if numbers.len() <= STACK_LIMIT {
        field_init_static = [false; STACK_LIMIT];
        field_init_static[..numbers.len()].fill(*struct_initialized);
        &mut field_init_static[..numbers.len()]
    } else {
        field_init_dynamic = vec![*struct_initialized; numbers.len()];
        &mut field_init_dynamic[..]
    };

    // SAFETY: guaranteed by caller.
    let r = unsafe { read_fields_inner(numbers, decoders, offsets, base, field_inits, reader) };
    *struct_initialized = true;
    if r.is_err() && !field_inits.iter().all(|&b| b) {
        // Drop any initialized fields.
        for ((field_init, &offset), decoder) in field_inits.iter_mut().zip(offsets).zip(decoders) {
            if *field_init {
                // SAFETY: guaranteed by the caller.
                unsafe {
                    decoder.drop_struct(base.add(offset));
                }
            }
        }
        *struct_initialized = false;
    }
    r
}

/// Reads fields from the provided field metadata, but does not drop any fields
/// of a partially initialized message on failure.
unsafe fn read_fields_inner<R>(
    numbers: &[u32],
    decoders: &[ErasedDecoderEntry],
    offsets: &[usize],
    base: *mut u8,
    field_init: &mut [bool],
    reader: MessageReader<'_, '_, R>,
) -> Result<(), Error> {
    let decoders = &decoders[..numbers.len()];
    let offsets = &offsets[..numbers.len()];
    let field_init = &mut field_init[..numbers.len()];
    for field in reader {
        let (number, reader) = field?;
        if let Some(index) = numbers.iter().position(|&n| n == number) {
            let decoder = &decoders[index];
            // SAFETY: the decoder is valid according to the caller.
            unsafe {
                decoder.read_struct(base.add(offsets[index]), &mut field_init[index], reader)?;
            }
        }
    }
    for ((field_init, &offset), decoder) in field_init.iter_mut().zip(offsets).zip(decoders) {
        if !*field_init {
            // SAFETY: the decoder is valid according to the caller.
            unsafe {
                decoder.default_struct(base.add(offset), field_init)?;
            }
            assert!(*field_init);
        }
    }
    Ok(())
}

/// Sets fields to their default values from the provided field metadata.
///
/// # Safety
///
/// The caller must ensure that `base` points to a location that can be written
/// to, that `struct_initialized` is set correctly, and that the metadata is
/// correct and complete for the type of the object pointed to by `base`.
unsafe fn default_fields(
    decoders: &[ErasedDecoderEntry],
    offsets: &[usize],
    base: *mut u8,
    struct_initialized: &mut bool,
) -> Result<(), Error> {
    assert_eq!(decoders.len(), offsets.len());
    // SAFETY: guaranteed by caller and by the assertion above.
    unsafe {
        default_fields_by_ptr(
            decoders.len(),
            decoders.as_ptr(),
            offsets.as_ptr(),
            base,
            struct_initialized,
        )
    }
}

#[inline(never)]
unsafe fn default_fields_by_ptr(
    count: usize,
    decoders: *const ErasedDecoderEntry,
    offsets: *const usize,
    base: *mut u8,
    struct_initialized: &mut bool,
) -> Result<(), Error> {
    // SAFETY: guaranteed by caller.
    unsafe {
        default_fields_inline(
            slice::from_raw_parts(decoders, count),
            slice::from_raw_parts(offsets, count),
            base,
            struct_initialized,
        )
    }
}

unsafe fn default_fields_inline(
    decoders: &[ErasedDecoderEntry],
    offsets: &[usize],
    base: *mut u8,
    struct_initialized: &mut bool,
) -> Result<(), Error> {
    for (i, (&offset, decoder)) in offsets.iter().zip(decoders).enumerate() {
        let mut field_initialized = *struct_initialized;
        // SAFETY: the decoder is valid according to the caller.
        let r = unsafe { decoder.default_struct(base.add(offset), &mut field_initialized) };
        if let Err(err) = r {
            if !field_initialized || !*struct_initialized {
                // Drop initialized fields.
                let initialized_until = i;
                for (i, (&offset, decoder)) in offsets.iter().zip(decoders).enumerate() {
                    if i < initialized_until
                        || (i == initialized_until && field_initialized)
                        || (i > initialized_until && *struct_initialized)
                    {
                        // SAFETY: the decoder is valid according to the caller, and the field is initialized.
                        unsafe {
                            decoder.drop_struct(base.add(offset));
                        }
                    }
                }
                *struct_initialized = false;
            }
            return Err(err);
        }
        assert!(field_initialized);
    }
    *struct_initialized = true;
    Ok(())
}

/// The struct metadata for decoding a struct.
///
/// # Safety
///
/// The implementor must ensure that the `DECODERS` are correct and complete for
/// `Self`, such that if every field is decoded, then the struct value is valid.
pub unsafe trait StructDecodeMetadata<'de, R>: StructMetadata {
    /// The list of decoder vtables.
    const DECODERS: &'static [ErasedDecoderEntry];
}

/// An entry in the decoder table.
///
/// This contains the metadata necessary to apply an decoder to a field.
///
/// This cannot be instantiated directly; use [`FieldDecode::ENTRY`] to get an
/// instance for a particular decoder.
pub struct DecoderEntry<'a, T, R>(
    ErasedDecoderEntry,
    PhantomData<fn(&mut T, &mut R, &'a mut ())>,
);

impl<'a, T, R> DecoderEntry<'a, T, R> {
    /// # Safety
    /// The caller must ensure that the erased entry is an valid entry for `T`
    /// and `R`.
    pub(crate) const unsafe fn new_unchecked(entry: ErasedDecoderEntry) -> Self {
        Self(entry, PhantomData)
    }

    pub(crate) const fn custom<E: FieldDecode<'a, T, R>>() -> Self {
        Self(
            ErasedDecoderEntry(
                std::ptr::from_ref(
                    const {
                        &StaticDecoderVtable {
                            read_fn: read_field_dyn::<T, R, E>,
                            default_fn: default_field_dyn::<T, R, E>,
                            drop_fn: if std::mem::needs_drop::<T>() {
                                Some(drop_field_dyn::<T>)
                            } else {
                                None
                            },
                        }
                    },
                )
                .cast(),
            ),
            PhantomData,
        )
    }

    const fn table() -> Self
    where
        T: StructDecodeMetadata<'a, R>,
    {
        Self(
            ErasedDecoderEntry(
                std::ptr::from_ref(
                    const {
                        &DecoderTable {
                            count: T::NUMBERS.len(),
                            numbers: T::NUMBERS.as_ptr(),
                            decoders: T::DECODERS.as_ptr(),
                            offsets: T::OFFSETS.as_ptr(),
                        }
                    },
                )
                .cast::<()>()
                .wrapping_byte_add(ENTRY_IS_TABLE),
            ),
            PhantomData,
        )
    }

    /// Erases the type of the decoder entry.
    pub const fn erase(&self) -> ErasedDecoderEntry {
        self.0
    }
}

/// An entry in a [`StructDecodeMetadata::DECODERS`] table.
//
// Internally, this is a pointer to either a vtable or a table.
// The low bit is used to distinguish between the two.
#[derive(Copy, Clone)]
pub struct ErasedDecoderEntry(*const ());

const ENTRY_IS_TABLE: usize = 1;

const _: () = assert!(align_of::<ErasedDecoderEntry>() > ENTRY_IS_TABLE);
const _: () = assert!(align_of::<StaticDecoderVtable<'_, ()>>() > ENTRY_IS_TABLE);

impl ErasedDecoderEntry {
    /// Decodes the entry into either a vtable or a table.
    ///
    /// # Safety
    /// The caller must ensure that the encoder was for resource type `R`.
    unsafe fn decode<'de, R>(&self) -> Result<&StaticDecoderVtable<'de, R>, &DecoderTable> {
        // SAFETY: guaranteed by caller.
        unsafe {
            if self.0 as usize & ENTRY_IS_TABLE == 0 {
                Ok(&*self.0.cast::<StaticDecoderVtable<'_, R>>())
            } else {
                Err(&*self
                    .0
                    .wrapping_byte_sub(ENTRY_IS_TABLE)
                    .cast::<DecoderTable>())
            }
        }
    }

    /// Reads a struct using the decoder metadata.
    ///
    /// # Safety
    /// The caller must ensure that the decoder was for resource type `R` and
    /// the object type matching what `ptr` is pointing to.
    unsafe fn read_struct<R>(
        &self,
        ptr: *mut u8,
        init: &mut bool,
        reader: FieldReader<'_, '_, R>,
    ) -> Result<(), Error> {
        // SAFETY: guaranteed by caller.
        unsafe {
            match self.decode::<R>() {
                Ok(vtable) => (vtable.read_fn)(ptr, init, reader),
                Err(table) => read_message_by_ptr(
                    table.count,
                    table.numbers,
                    table.decoders,
                    table.offsets,
                    ptr,
                    init,
                    reader,
                ),
            }
        }
    }

    /// Initializes a struct to its default state using the decoder metadata.
    ///
    /// # Safety
    /// The caller must ensure that the decoder was for the object type matching
    /// what `ptr` is pointing to.
    unsafe fn default_struct(&self, ptr: *mut u8, init: &mut bool) -> Result<(), Error> {
        // SAFETY: guaranteed by caller.
        unsafe {
            match self.decode::<()>() {
                Ok(vtable) => (vtable.default_fn)(ptr, init),
                Err(table) => {
                    default_fields_by_ptr(table.count, table.decoders, table.offsets, ptr, init)
                }
            }
        }
    }

    /// Drops a struct in place using the decoder metadata.
    ///
    /// # Safety
    /// The caller must ensure that the decoder was for the object type matching
    /// what `ptr` is pointing to, and that `ptr` is ready to be dropped.
    unsafe fn drop_struct(&self, ptr: *mut u8) {
        // SAFETY: guaranteed by caller.
        unsafe {
            match self.decode::<()>() {
                Ok(vtable) => {
                    if let Some(drop_fn) = vtable.drop_fn {
                        drop_fn(ptr);
                    }
                }
                Err(table) => {
                    for i in 0..table.count {
                        let offset = *table.offsets.add(i);
                        let decoder = &*table.decoders.add(i);
                        decoder.drop_struct(ptr.add(offset));
                    }
                }
            }
        }
    }
}

struct DecoderTable {
    count: usize,
    numbers: *const u32,
    decoders: *const ErasedDecoderEntry,
    offsets: *const usize,
}

/// A vtable for decoding a message.
#[repr(C)] // to ensure the layout is the same regardless of R
struct StaticDecoderVtable<'de, R> {
    read_fn: unsafe fn(*mut u8, init: *mut bool, FieldReader<'de, '_, R>) -> Result<(), Error>,
    default_fn: unsafe fn(*mut u8, init: *mut bool) -> Result<(), Error>,
    drop_fn: Option<unsafe fn(*mut u8)>,
}

unsafe fn read_field_dyn<'a, T, R, E: FieldDecode<'a, T, R>>(
    field: *mut u8,
    init: *mut bool,
    reader: FieldReader<'a, '_, R>,
) -> Result<(), Error> {
    // SAFETY: `init` is valid according to the caller.
    let init = unsafe { &mut *init };
    // SAFETY: `field` is valid and points to a valid `MaybeUninit<T>` according
    // to the caller.
    let field = unsafe { &mut *field.cast::<MaybeUninit<T>>() };
    let mut field = if *init {
        // SAFETY: the caller attests that the field is initialized.
        unsafe { InplaceOption::new_init_unchecked(field) }
    } else {
        InplaceOption::uninit(field)
    };
    let r = E::read_field(&mut field, reader);
    *init = field.forget();
    r
}

unsafe fn default_field_dyn<'a, T, R, E: FieldDecode<'a, T, R>>(
    field: *mut u8,
    init: *mut bool,
) -> Result<(), Error> {
    // SAFETY: `init` is valid according to the caller.
    let init = unsafe { &mut *init };
    // SAFETY: `field` is valid and points to a valid `MaybeUninit<T>` according
    // to the caller.
    let field = unsafe { &mut *field.cast::<MaybeUninit<T>>() };
    let mut field = if *init {
        // SAFETY: the caller attests that the field is initialized.
        unsafe { InplaceOption::new_init_unchecked(field) }
    } else {
        InplaceOption::uninit(field)
    };
    let r = E::default_field(&mut field);
    *init = field.forget();
    r
}

unsafe fn drop_field_dyn<T>(field: *mut u8) {
    let field = field.cast::<T>();
    // SAFETY: `field` is valid and points to a valid `T` according to the
    // caller.
    unsafe { field.drop_in_place() }
}