jsony 0.1.10

An experimental fast compiling serialization and deserialization library for JSON like formats.
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
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
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
use std::{marker::PhantomData, num::NonZeroU64, ptr::NonNull};
pub struct NestedDynamicFieldDecoder<'a, T: FieldVisitor<'a>> {
    pub inner: T,
    pub destination: NonNull<()>,
    pub schema: ObjectSchema<'a>,
    pub bitset: u64,
    pub required: u64,
}

#[repr(transparent)]
pub struct UnsafeReturn;

pub struct DynamicFieldDecoder<'a> {
    pub destination: NonNull<()>,
    pub schema: ObjectSchema<'a>,
    pub alias: &'static [(usize, &'static str)],
    pub bitset: u64,
    pub required: u64,
}

pub struct DynamicFieldDecoderIndexed<'a, const N: usize> {
    pub destination: NonNull<()>,
    pub schema: ObjectSchema<'a>,
    pub field_index: fn(&str) -> usize,
    pub bitset: [u64; N],
    pub required: &'static [u64],
}

/// helper function used for writing the default value from the Jsony derive macros
pub unsafe fn default_default<T: Default>(ptr: ::std::ptr::NonNull<()>) -> UnsafeReturn {
    // SAFETY: the caller supplies writable storage for a `T` field. This helper
    // writes exactly one initialized `T` into that location.
    unsafe {
        (ptr.as_ptr() as *mut T).write(T::default());
    }
    UnsafeReturn
}

pub const unsafe fn erase<'a>(
    input: unsafe fn(NonNull<()>, &mut Parser<'a>) -> Result<(), &'static DecodeError>,
) -> for<'b> unsafe fn(NonNull<()>, &mut Parser<'b>) -> Result<(), &'static DecodeError> {
    // SAFETY: this only erases the parser lifetime in the function pointer type.
    // The returned function remains unsafe to call; callers must ensure it is
    // invoked only with a parser/input lifetime compatible with the original
    // `input` function.
    unsafe { std::mem::transmute(input) }
}

type Foo = for<'b> unsafe fn(NonNull<()>, &mut Parser<'b>) -> Result<(), &'static DecodeError>;
#[inline(always)]
pub const unsafe fn erased_emplace_from_json<'a, T: crate::FromJson<'a>>() -> Foo {
    // SAFETY: this erases the concrete parser lifetime from `T`'s emplace
    // function so generated static schemas can store it. The resulting function
    // pointer is still unsafe to call; the schema decoder must only call it with
    // the same input lifetime used to instantiate `T: FromJson<'a>`.
    unsafe {
        std::mem::transmute(
            <T as crate::FromJson<'a>>::emplace_from_json
                as unsafe fn(NonNull<()>, &mut Parser<'a>) -> Result<(), &'static DecodeError>,
        )
    }
}

pub unsafe fn erased_drop_in_place<M: Sized>(ptr: NonNull<()>) {
    // SAFETY: the caller guarantees `ptr` points to an initialized `M`.
    unsafe {
        std::ptr::drop_in_place(ptr.as_ptr() as *mut M);
    }
}

#[doc(hidden)]
pub struct SkipFieldVisitor<F> {
    pub skipped_field: &'static str,
    pub visitor: F,
}

impl<'a, F: FieldVisitor<'a>> FieldVisitor<'a> for SkipFieldVisitor<F> {
    fn complete(&mut self) -> Result<(), &'static DecodeError> {
        self.visitor.complete()
    }
    unsafe fn destroy(&mut self) {
        // SAFETY: `SkipFieldVisitor::destroy` has the same single-call
        // contract as the wrapped visitor's `destroy`.
        unsafe { self.visitor.destroy() }
    }
    fn visit(
        &mut self,
        borrowed: crate::json::ParserWithBorrowedKey<'a, '_>,
    ) -> Result<(), &'static DecodeError> {
        if borrowed.key() == self.skipped_field {
            borrowed.into_parser().at.skip_value()
        } else {
            self.visitor.visit(borrowed)
        }
    }
}

impl<'a> FieldVisitor<'a> for DynamicFieldDecoder<'a> {
    fn complete(&mut self) -> Result<(), &'static DecodeError> {
        if self.bitset & self.required != self.required {
            return Err(&MISSING_REQUIRED_FIELDS);
        }
        for (i, (emplace_default, field)) in self
            .schema
            .inner
            .defaults
            .iter()
            .zip(self.schema.fields())
            .enumerate()
        {
            if self.bitset & (1 << i) == 0 {
                // SAFETY: `destination` is the base of the object being
                // decoded, `field.offset` comes from the schema for that
                // object, and the bitset shows this field has not yet been
                // initialized.
                unsafe {
                    emplace_default(self.destination.byte_add(field.offset));
                }
            }
        }
        Ok(())
    }
    unsafe fn destroy(&mut self) {
        for (i, field) in self.schema.fields().iter().enumerate() {
            if self.bitset & (1 << i) != 0 {
                // SAFETY: the bitset records only fields successfully
                // initialized by this decoder, and `field.offset` points to the
                // corresponding field storage inside `destination`.
                unsafe {
                    (self.schema.inner.drops[i])(self.destination.byte_add(field.offset));
                }
            }
        }
    }
    fn visit(
        &mut self,
        mut borrowed: ParserWithBorrowedKey<'a, '_>,
    ) -> Result<(), &'static DecodeError> {
        let field_name = borrowed.key();
        'unused: {
            let (index, field) = 'found: {
                let fields = self.schema.fields();
                for (index, field) in fields.iter().enumerate() {
                    if field.name != field_name {
                        continue;
                    }
                    break 'found (index, field);
                }
                for (index, alias_name) in self.alias {
                    if *alias_name != field_name {
                        continue;
                    }
                    break 'found (*index, &fields[*index]);
                }
                break 'unused;
            };
            let parser = borrowed.into_parser();
            let mask = 1 << index;
            if self.bitset & mask != 0 {
                set_object_key_context(parser, field.name);
                return Err(&DUPLICATE_FIELD);
            }
            // SAFETY: `destination + field.offset` is the uninitialized storage
            // for this schema field, and `field.decode` is the matching
            // generated emplace function. Duplicate fields are rejected before
            // this call, so the destination field is not already initialized.
            if let Err(err) =
                unsafe { (field.decode)(self.destination.byte_add(field.offset), parser) }
            {
                set_object_key_context(parser, field.name);
                return Err(err);
            }
            self.bitset |= mask;
            return Ok(());
        }
        if let Some(vis) = borrowed.parser().visit_unused_field {
            vis(borrowed.reborrow());
        }

        return borrowed.into_parser().at.skip_value();
    }
}

impl<'a, const N: usize> FieldVisitor<'a> for DynamicFieldDecoderIndexed<'a, N> {
    fn complete(&mut self) -> Result<(), &'static DecodeError> {
        debug_assert_eq!(
            N,
            self.schema.inner.fields.len().div_ceil(u64::BITS as usize)
        );
        debug_assert_eq!(N, self.required.len());
        if first_missing_required(&self.bitset, self.required).is_some() {
            return Err(&MISSING_REQUIRED_FIELDS);
        }
        // SAFETY: missing default fields have not been initialized by this
        // visitor, and defaults are paired with the first schema fields.
        unsafe {
            emplace_missing_defaults(
                self.destination,
                self.schema.fields(),
                self.schema.inner.defaults,
                &self.bitset,
            );
        }
        Ok(())
    }

    unsafe fn destroy(&mut self) {
        // SAFETY: the bitset records only fields successfully initialized by
        // this visitor, and destroy is called at most once on the error path.
        unsafe {
            drop_initialized_fields(
                self.destination,
                self.schema.fields(),
                self.schema.inner.drops,
                &self.bitset,
            );
        }
    }

    fn visit(
        &mut self,
        mut borrowed: ParserWithBorrowedKey<'a, '_>,
    ) -> Result<(), &'static DecodeError> {
        let field_name = borrowed.key();
        let index = (self.field_index)(field_name);
        if index == UNKNOWN_FIELD_INDEX {
            if let Some(vis) = borrowed.parser().visit_unused_field {
                vis(borrowed.reborrow());
            }
            return borrowed.into_parser().at.skip_value();
        }
        if index == SKIP_FIELD_ALIAS_INDEX {
            return borrowed.into_parser().at.skip_value();
        }

        let fields = self.schema.fields();
        debug_assert!(index < fields.len());
        // SAFETY: generated field-index functions return only
        // `UNKNOWN_FIELD_INDEX`, `SKIP_FIELD_ALIAS_INDEX`, or a valid field
        // index for this schema.
        let field = unsafe { fields.get_unchecked(index) };
        let parser = borrowed.into_parser();
        let (word_index, mask) = field_bit(index);
        debug_assert!(word_index < N);
        // SAFETY: `word_index` is derived from a valid field index.
        let word = unsafe { self.bitset.get_unchecked_mut(word_index) };
        if *word & mask != 0 {
            set_object_key_context(parser, field.name);
            return Err(&DUPLICATE_FIELD);
        }
        // SAFETY: `destination + field.offset` is the uninitialized storage
        // for this schema field, and the duplicate check above proves it is not
        // live yet.
        if let Err(err) = unsafe { (field.decode)(self.destination.byte_add(field.offset), parser) }
        {
            set_object_key_context(parser, field.name);
            return Err(err);
        }
        *word |= mask;
        Ok(())
    }
}

use crate::{
    error::{DUPLICATE_FIELD, MISSING_REQUIRED_FIELDS},
    json::{FieldVisitor, ParserWithBorrowedKey},
    parser::{JsonParentContext, Parser},
};

/// Array decoder for derived multi-field tuple structs. Re-exported from
/// [`crate::json`] so generated code can reach it under the `__internal` path.
pub use crate::json::dyn_tuple_decode;

type DecodeFn<'a> = unsafe fn(NonNull<()>, &mut Parser<'a>) -> Result<(), &'static DecodeError>;
use super::DecodeError;

// Maximum field count for the legacy single-word decoder.
const SMALL_MAX_FIELDS: usize = 63;

// Sanity cap for derived object schemas decoded by the indexed path.
const MAX_SCHEMA_FIELD_WORDS: usize = 16;
pub const MAX_FIELDS: usize = MAX_SCHEMA_FIELD_WORDS * u64::BITS as usize;
static TOO_MANY_FIELDS: DecodeError = DecodeError {
    message: "Too many fields in Jsony object schema",
};

pub const UNKNOWN_FIELD_INDEX: usize = usize::MAX;

fn schema_all_mask(fields_len: usize) -> Result<u64, &'static DecodeError> {
    if fields_len > SMALL_MAX_FIELDS {
        return Err(&TOO_MANY_FIELDS);
    }
    Ok((1u64 << fields_len) - 1)
}

fn schema_default_mask(
    defaults_len: usize,
    fields_len: usize,
) -> Result<u64, &'static DecodeError> {
    if defaults_len > fields_len || defaults_len > SMALL_MAX_FIELDS {
        return Err(&TOO_MANY_FIELDS);
    }
    Ok((1u64 << defaults_len) - 1)
}

#[inline]
fn field_bit(index: usize) -> (usize, u64) {
    (
        index / u64::BITS as usize,
        1u64 << (index % u64::BITS as usize),
    )
}

#[inline]
fn set_object_key_context(parser: &mut Parser<'_>, key: &'static str) {
    if matches!(&parser.parent_context, JsonParentContext::None) {
        parser.parent_context = JsonParentContext::ObjectKey(key);
    }
}

fn first_missing_required(bitset: &[u64], required: &[u64]) -> Option<usize> {
    let mut word_index = 0;
    while word_index < required.len() {
        if let Some(missing) = NonZeroU64::new(required[word_index] & !bitset[word_index]) {
            return Some(word_index * u64::BITS as usize + missing.get().trailing_zeros() as usize);
        }
        word_index += 1;
    }
    None
}

unsafe fn emplace_missing_defaults(
    dest: NonNull<()>,
    fields: &[Field<'_>],
    defaults: &[unsafe fn(NonNull<()>) -> UnsafeReturn],
    bitset: &[u64],
) {
    let defaults_len = defaults.len();
    for word_index in 0..defaults_len.div_ceil(u64::BITS as usize) {
        let start = word_index * u64::BITS as usize;
        let remaining = defaults_len - start;
        let valid = if remaining >= u64::BITS as usize {
            u64::MAX
        } else {
            (1u64 << remaining) - 1
        };
        let mut missing = !bitset[word_index] & valid;
        while let Some(nonzero) = NonZeroU64::new(missing) {
            let index = start + nonzero.get().trailing_zeros() as usize;
            // SAFETY: schema construction orders defaulted fields first, so
            // every index below `defaults_len` has a matching default callback
            // and field descriptor. The bitset shows this slot is not live yet.
            unsafe {
                defaults[index](dest.byte_add(fields[index].offset));
            }
            missing &= missing - 1;
        }
    }
}

unsafe fn drop_initialized_fields(
    dest: NonNull<()>,
    fields: &[Field<'_>],
    drops: &[unsafe fn(NonNull<()>)],
    bitset: &[u64],
) {
    for (word_index, word) in bitset.iter().copied().enumerate() {
        let Some(mut remaining) = NonZeroU64::new(word) else {
            continue;
        };
        loop {
            let index = word_index * u64::BITS as usize + remaining.get().trailing_zeros() as usize;
            // SAFETY: the bitset records only fields successfully initialized
            // by this decoder, so every set bit maps to an in-bounds field and
            // matching drop callback.
            unsafe {
                let field = fields.get_unchecked(index);
                drops.get_unchecked(index)(dest.byte_add(field.offset));
            }
            let next = remaining.get() & (remaining.get() - 1);
            let Some(next) = NonZeroU64::new(next) else {
                break;
            };
            remaining = next;
        }
    }
}

pub struct Field<'a> {
    pub name: &'static str,
    pub offset: usize,
    pub decode: DecodeFn<'a>,
}

// gets sorted by defaults
// might add a static drop at some point.
pub struct ObjectSchemaInner {
    pub fields: &'static [Field<'static>],
    pub drops: &'static [unsafe fn(NonNull<()>)],
    pub defaults: &'static [unsafe fn(NonNull<()>) -> UnsafeReturn],
}

#[derive(Clone, Copy)]
pub struct ObjectSchema<'a> {
    pub inner: &'static ObjectSchemaInner,
    pub phantom: PhantomData<&'a ()>,
}

impl<'a> ObjectSchema<'a> {
    pub fn fields(&self) -> &[Field<'a>] {
        // SAFETY: schemas store field descriptors in static memory. Generated
        // schema construction erases the parser lifetime from each decode
        // function; callers of those functions remain unsafe and must uphold
        // the lifetime compatibility required by the schema.
        unsafe {
            #[allow(clippy::unnecessary_cast, reason = "clippy false positive")]
            std::slice::from_raw_parts(
                self.inner.fields.as_ptr() as *const Field<'a>,
                self.inner.fields.len(),
            )
        }
    }
}

/// Alias-table index meaning "match this key, then discard it" rather than
/// decode it into a field.
///
/// Entries in the `alias` slice passed to [`ObjectSchema::decode_with_alias`]
/// map a key to a field index. An entry using this index resolves to no field,
/// so the matched key is skipped without being forwarded to the unused-field
/// visitor. Derived code uses it to swallow an internal tag key that shares the
/// variant object with the real fields.
pub const SKIP_FIELD_ALIAS_INDEX: usize = usize::MAX - 1;

impl<'a> ObjectSchema<'a> {
    pub unsafe fn decode_indexed(
        &self,
        dest: NonNull<()>,
        parser: &mut Parser<'a>,
        mut unused: Option<&mut dyn FieldVisitor<'a>>,
        field_index: fn(&str) -> usize,
        bitset: &mut [u64],
        required: &[u64],
    ) -> Result<(), &'static DecodeError> {
        let fields = self.fields();
        let words = fields.len().div_ceil(u64::BITS as usize);
        if fields.len() > MAX_FIELDS || bitset.len() != words || required.len() != words {
            if let Some(visitor) = unused {
                // SAFETY: the visitor was passed to this decode attempt and no
                // fields have been decoded. Destroy it before reporting the
                // invalid internal schema.
                unsafe { visitor.destroy() }
            }
            return Err(&TOO_MANY_FIELDS);
        }

        let error = 'error: {
            match parser.at.enter_object(&mut parser.scratch) {
                Ok(Some(mut key)) => {
                    'key_loop: loop {
                        'next: {
                            let index = field_index(key);
                            if index == SKIP_FIELD_ALIAS_INDEX {
                                if let Err(error) = parser.at.skip_value() {
                                    break 'error error;
                                }
                                break 'next;
                            }

                            if index != UNKNOWN_FIELD_INDEX {
                                debug_assert!(index < fields.len());
                                // SAFETY: generated field-index functions
                                // return only `UNKNOWN_FIELD_INDEX`,
                                // `SKIP_FIELD_ALIAS_INDEX`, or a valid field
                                // index for this schema.
                                let field = unsafe { fields.get_unchecked(index) };
                                let (word_index, mask) = field_bit(index);
                                debug_assert!(word_index < bitset.len());
                                if bitset[word_index] & mask != 0 {
                                    set_object_key_context(parser, field.name);
                                    break 'error &DUPLICATE_FIELD;
                                }

                                // SAFETY: the caller provides `dest` as
                                // writable storage for the object described by
                                // this schema. This field has not been seen
                                // yet, so its slot is uninitialized.
                                if let Err(err) =
                                    unsafe { (field.decode)(dest.byte_add(field.offset), parser) }
                                {
                                    set_object_key_context(parser, field.name);
                                    break 'error err;
                                }
                                bitset[word_index] |= mask;
                                break 'next;
                            }

                            if let Some(ref mut unused_processor) = unused {
                                // SAFETY: `key` was returned by this parser
                                // for the current object step and remains live
                                // until the parser advances to the next key
                                // below.
                                let borrowed = unsafe { ParserWithBorrowedKey::new(key, parser) };
                                if let Err(err) = unused_processor.visit(borrowed) {
                                    break 'error err;
                                }
                                break 'next;
                            }
                            if let Some(vis) = parser.visit_unused_field {
                                // SAFETY: same key lifetime argument as the
                                // unused-field visitor path above.
                                vis(unsafe { ParserWithBorrowedKey::new(key, parser) });
                            }

                            if let Err(error) = parser.at.skip_value() {
                                break 'error error;
                            }
                        }

                        match parser.at.object_step(&mut parser.scratch) {
                            Ok(Some(next_key2)) => {
                                key = next_key2;
                                continue 'key_loop;
                            }
                            Ok(None) => {
                                break 'key_loop;
                            }
                            Err(err) => break 'error err,
                        }
                    }
                }
                Ok(None) => {}
                Err(err) => break 'error err,
            };

            if let Some(index) = first_missing_required(bitset, required) {
                parser.parent_context = JsonParentContext::SchemaField {
                    schema: self.inner,
                    index,
                };
                break 'error &MISSING_REQUIRED_FIELDS;
            }
            if let Some(visitor) = &mut unused {
                if let Err(err) = visitor.complete() {
                    break 'error err;
                }
            }
            // SAFETY: missing default fields have not been initialized, and
            // defaults are paired with the first schema fields.
            unsafe {
                emplace_missing_defaults(dest, fields, self.inner.defaults, bitset);
            }
            return Ok(());
        };

        // SAFETY: the bitset records exactly the fields initialized before the
        // decode error.
        unsafe {
            drop_initialized_fields(dest, fields, self.inner.drops, bitset);
        }
        if let Some(visitor) = unused {
            // SAFETY: the visitor has not completed successfully and is being
            // destroyed exactly once on the error path.
            unsafe { visitor.destroy() }
        }
        Err(error)
    }

    pub unsafe fn decode_with_alias(
        &self,
        dest: NonNull<()>,
        parser: &mut Parser<'a>,
        mut unused: Option<&mut dyn FieldVisitor<'a>>,
        alias: &[(usize, &'static str)],
    ) -> Result<(), &'static DecodeError> {
        let fields_len = self.inner.fields.len();
        let all = match schema_all_mask(fields_len) {
            Ok(mask) => mask,
            Err(err) => {
                if let Some(visitor) = unused {
                    // SAFETY: the visitor was passed to this decode attempt
                    // and no fields have been decoded. Destroy it before
                    // reporting the invalid internal schema.
                    unsafe { visitor.destroy() }
                }
                return Err(err);
            }
        };
        let mut bitset = 0;

        let error = 'error: {
            match parser.at.enter_object(&mut parser.scratch) {
                Ok(Some(mut key)) => {
                    'key_loop: loop {
                        'next: {
                            'unused_dont_forward: {
                                'unused: {
                                    let (index, field) = 'found: {
                                        let fields = self.fields();
                                        for (index, field) in fields.iter().enumerate() {
                                            if field.name != key {
                                                continue;
                                            }
                                            break 'found (index, field);
                                        }
                                        for (index, alias_name) in alias {
                                            if *alias_name != key {
                                                continue;
                                            }
                                            // An out-of-bounds index (i.e.
                                            // `SKIP_FIELD_ALIAS_INDEX`) means
                                            // skip the matched key.
                                            if let Some(field) = fields.get(*index) {
                                                break 'found (*index, field);
                                            } else {
                                                break 'unused_dont_forward;
                                            }
                                        }
                                        break 'unused;
                                    };
                                    let mask = 1 << index;
                                    if bitset & mask != 0 {
                                        set_object_key_context(parser, field.name);

                                        break 'error &DUPLICATE_FIELD;
                                    }

                                    // SAFETY: the caller provides `dest` as
                                    // writable storage for the object described
                                    // by this schema. This field has not been
                                    // seen yet, so its slot is uninitialized.
                                    if let Err(err) = unsafe {
                                        (field.decode)(dest.byte_add(field.offset), parser)
                                    } {
                                        set_object_key_context(parser, field.name);
                                        break 'error err;
                                    }
                                    bitset |= mask;
                                    break 'next;
                                }
                                if let Some(ref mut unused_processor) = unused {
                                    // SAFETY: `key` was returned by this parser
                                    // for the current object step and remains
                                    // live until the parser advances to the
                                    // next key below.
                                    let borrowed =
                                        unsafe { ParserWithBorrowedKey::new(key, parser) };
                                    if let Err(err) = unused_processor.visit(borrowed) {
                                        break 'error err;
                                    }
                                    break 'next;
                                }
                                if let Some(vis) = parser.visit_unused_field {
                                    // SAFETY: same key lifetime argument as the
                                    // unused-field visitor path above.
                                    vis(unsafe { ParserWithBorrowedKey::new(key, parser) });
                                }
                            }

                            if let Err(error) = parser.at.skip_value() {
                                break 'error error;
                            }
                        }

                        match parser.at.object_step(&mut parser.scratch) {
                            Ok(Some(next_key2)) => {
                                key = next_key2;
                                continue 'key_loop;
                            }
                            Ok(None) => {
                                break 'key_loop;
                            }
                            Err(err) => break 'error err,
                        }
                    }
                }
                Ok(None) => {}
                Err(err) => break 'error err,
            };
            let default = match schema_default_mask(self.inner.defaults.len(), fields_len) {
                Ok(mask) => mask,
                Err(err) => break 'error err,
            };
            if (bitset | default) & all != all {
                parser.parent_context = JsonParentContext::Schema {
                    schema: self.inner,
                    mask: all & !(bitset | default),
                };
                break 'error &MISSING_REQUIRED_FIELDS;
            }
            if let Some(visitor) = &mut unused {
                if let Err(err) = visitor.complete() {
                    break 'error err;
                }
            }
            // todo can optimize
            for (i, (emplace_default, field)) in
                self.inner.defaults.iter().zip(self.fields()).enumerate()
            {
                if bitset & (1 << i) == 0 {
                    // SAFETY: fields missing from `bitset` have not been
                    // initialized, and defaults are paired with the first
                    // fields in schema order by generated schema construction.
                    unsafe {
                        emplace_default(dest.byte_add(field.offset));
                    }
                }
            }
            return Ok(());
        };

        for (i, (drop, field)) in self.inner.drops.iter().zip(self.fields()).enumerate() {
            if bitset & (1 << i) != 0 {
                // SAFETY: the bitset records exactly the fields initialized
                // before the decode error.
                unsafe {
                    drop(dest.byte_add(field.offset));
                }
            }
        }
        if let Some(visitor) = unused {
            // SAFETY: the visitor has not completed successfully and is being
            // destroyed exactly once on the error path.
            unsafe { visitor.destroy() }
        }
        Err(error)
    }
    pub unsafe fn decode(
        &self,
        dest: NonNull<()>,
        parser: &mut Parser<'a>,
        mut unused: Option<&mut dyn FieldVisitor<'a>>,
    ) -> Result<(), &'static DecodeError> {
        let fields_len = self.inner.fields.len();
        let all = match schema_all_mask(fields_len) {
            Ok(mask) => mask,
            Err(err) => {
                if let Some(visitor) = unused {
                    // SAFETY: the visitor was passed to this decode attempt
                    // and no fields have been decoded. Destroy it before
                    // reporting the invalid internal schema.
                    unsafe { visitor.destroy() }
                }
                return Err(err);
            }
        };
        let mut bitset = 0;

        let error = 'with_next_key: {
            match parser.at.enter_object(&mut parser.scratch) {
                Ok(Some(mut key)) => {
                    'key_loop: loop {
                        'next: {
                            for (index, field) in self.fields().iter().enumerate() {
                                let mask = 1 << index;
                                if field.name != key {
                                    continue;
                                }
                                if bitset & mask != 0 {
                                    set_object_key_context(parser, field.name);

                                    break 'with_next_key &DUPLICATE_FIELD;
                                }
                                // SAFETY: the caller provides `dest` as storage
                                // for the object described by this schema. This
                                // field is not marked initialized in `bitset`.
                                if let Err(err) =
                                    unsafe { (field.decode)(dest.byte_add(field.offset), parser) }
                                {
                                    set_object_key_context(parser, field.name);
                                    break 'with_next_key err;
                                }
                                bitset |= mask;
                                break 'next;
                            }

                            if let Some(ref mut unused_processor) = unused {
                                // SAFETY: `key` was returned by this parser for
                                // the current object step and remains live
                                // until the parser advances to the next key.
                                let borrowed = unsafe { ParserWithBorrowedKey::new(key, parser) };
                                if let Err(err) = unused_processor.visit(borrowed) {
                                    break 'with_next_key err;
                                }
                                break 'next;
                            }

                            if let Some(vis) = parser.visit_unused_field {
                                // SAFETY: same key lifetime argument as the
                                // unused-field visitor path above.
                                vis(unsafe { ParserWithBorrowedKey::new(key, parser) });
                            }

                            if let Err(error) = parser.at.skip_value() {
                                break 'with_next_key error;
                            }
                        }

                        match parser.at.object_step(&mut parser.scratch) {
                            Ok(Some(next_key2)) => {
                                key = next_key2;
                                continue 'key_loop;
                            }
                            Ok(None) => {
                                break 'key_loop;
                            }
                            Err(err) => break 'with_next_key err,
                        }
                    }
                }
                Ok(None) => {}
                Err(err) => break 'with_next_key err,
            };
            let default = match schema_default_mask(self.inner.defaults.len(), fields_len) {
                Ok(mask) => mask,
                Err(err) => break 'with_next_key err,
            };
            if (bitset | default) & all != all {
                parser.parent_context = JsonParentContext::Schema {
                    schema: self.inner,
                    mask: all & !(bitset | default),
                };
                break 'with_next_key &MISSING_REQUIRED_FIELDS;
            }
            if let Some(visitor) = &mut unused {
                if let Err(err) = visitor.complete() {
                    break 'with_next_key err;
                }
            }
            // todo can optimize
            for (i, (emplace_default, field)) in
                self.inner.defaults.iter().zip(self.fields()).enumerate()
            {
                if bitset & (1 << i) == 0 {
                    // SAFETY: fields missing from `bitset` have not been
                    // initialized, and defaults are paired with the first
                    // fields in schema order by generated schema construction.
                    unsafe {
                        emplace_default(dest.byte_add(field.offset));
                    }
                }
            }
            return Ok(());
        };

        for (i, (drop, field)) in self.inner.drops.iter().zip(self.fields()).enumerate() {
            if bitset & (1 << i) != 0 {
                // SAFETY: the bitset records exactly the fields initialized
                // before the decode error.
                unsafe {
                    drop(dest.byte_add(field.offset));
                }
            }
        }
        if let Some(visitor) = unused {
            // SAFETY: the visitor has not completed successfully and is being
            // destroyed exactly once on the error path.
            unsafe { visitor.destroy() }
        }
        Err(error)
    }
}

// Note that we make P generic here so that we couple lifetime with T
// P will always be &mut Parser<'_>
pub const unsafe fn emplace_json_for_with_attribute<P, T, F>(
    _func: &F,
) -> for<'b> unsafe fn(NonNull<()>, &mut Parser<'b>) -> Result<(), &'static DecodeError>
where
    F: Fn(P) -> Result<T, &'static DecodeError>,
{
    const { assert!(std::mem::size_of::<F>() == 0) }
    let func: unsafe fn(dest: NonNull<()>, parser: P) -> Result<(), &'static DecodeError> =
        |dest: NonNull<()>, parser: P| -> Result<(), &'static DecodeError> {
            // SAFETY: the const assertion above proves `F` is zero-sized, so
            // constructing it from `()` reads no bytes and creates the function
            // item/closure value represented by `F`.
            let func = unsafe { std::mem::transmute_copy::<(), F>(&()) };
            match func(parser) {
                Ok(value) => {
                    let value: T = value;
                    // SAFETY: callers invoke this returned emplace function
                    // with writable storage for `T`.
                    unsafe {
                        dest.cast::<T>().write(value);
                    }
                    Ok(())
                }
                Err(err) => Err(err),
            }
        };
    // SAFETY: the returned function pointer erases only the parser lifetime so
    // it can be stored in generated static schema data. Calling it remains
    // unsafe and must use the lifetime-compatible parser type.
    unsafe { std::mem::transmute(func) }
}

// Safety: The function returned has had the Parser lifetime erased, this done so that
// it can be stored in a static to workaround current limitations in the rust solver.
//
// You must not used the returned function pointer with an incompatible life time. Generally
// this enforced by ObjectSchema, where we this used internally and generated by proc macros.
//
// Panics if the size of F is not zero, as long as it's a simple function this should be true.
pub const unsafe fn emplace_json_for_validate_attribute<'a, T: crate::FromJson<'a>, F>(
    _func: &F,
) -> for<'b> unsafe fn(NonNull<()>, &mut Parser<'b>) -> Result<(), &'static DecodeError>
where
    F: Fn(&T) -> Result<(), String>,
{
    const { assert!(std::mem::size_of::<F>() == 0) }
    let func: unsafe fn(
        dest: NonNull<()>,
        parser: &mut Parser<'a>,
    ) -> Result<(), &'static DecodeError> =
        |dest: NonNull<()>, parser: &mut Parser<'a>| -> Result<(), &'static DecodeError> {
            // SAFETY: callers invoke this returned emplace function with
            // writable storage for `T`, which is exactly `T::emplace_from_json`'s
            // destination contract.
            match unsafe { T::emplace_from_json(dest, parser) } {
                Ok(()) => {
                    // SAFETY: the const assertion above proves `F` is
                    // zero-sized, so no bytes are read to construct it.
                    let func = unsafe { std::mem::transmute_copy::<(), F>(&()) };
                    // SAFETY: `T::emplace_from_json` returned `Ok`, so `dest`
                    // now contains an initialized `T`.
                    match func(unsafe { &*dest.cast().as_ptr() }) {
                        Ok(_) => Ok(()),
                        Err(err) => {
                            // SAFETY: validation failed after `T` was
                            // initialized, so drop that initialized value before
                            // reporting the error.
                            unsafe {
                                dest.cast::<T>().drop_in_place();
                            }
                            parser.report_error(err);
                            return Err(&crate::error::CUSTOM_FIELD_VALIDATION_ERROR);
                        }
                    }
                }
                Err(err) => Err(err),
            }
        };
    // SAFETY: the returned function pointer erases only the parser lifetime so
    // it can be stored in generated static schema data. Calling it remains
    // unsafe and must use the lifetime-compatible parser type.
    unsafe { std::mem::transmute(func) }
}