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
use std::{
    any::{type_name, TypeId},
    fmt::Debug,
    hash::{BuildHasher, Hasher},
    marker::PhantomData,
    sync::OnceLock,
};

use bones_utils::{default, HashMap};
use hashbrown::hash_map;
use parking_lot::RwLock;

use crate::{
    prelude::*,
    raw_fns::{RawClone, RawDefault, RawDrop},
};

/// Untyped schema-aware "HashMap".
#[derive(Clone, Debug)]
pub struct SchemaMap {
    map: HashMap<SchemaBox, SchemaBox>,
    key_schema: &'static Schema,
    value_schema: &'static Schema,
}

impl SchemaMap {
    /// Create a new map, with the given key and value schemas.
    pub fn new(key_schema: &'static Schema, value_schema: &'static Schema) -> Self {
        assert!(
            key_schema.hash_fn.is_some() && key_schema.eq_fn.is_some(),
            "Key schema must implement hash and eq"
        );
        Self {
            map: HashMap::default(),
            key_schema,
            value_schema,
        }
    }

    /// Get the number of entries in the map.
    #[inline]
    pub fn len(&self) -> usize {
        self.map.len()
    }

    /// Returns `true` if the map is empty.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.map.is_empty()
    }

    /// Get the schema for the map keys.
    pub fn key_schema(&self) -> &'static Schema {
        self.key_schema
    }

    /// Get the schema for the map values.
    pub fn value_schema(&self) -> &'static Schema {
        self.value_schema
    }

    /// Insert an item into the map.
    /// # Panics
    /// Panics if the key or value schemas do not match the map's.
    #[inline]
    #[track_caller]
    pub fn insert<K: HasSchema, V: HasSchema>(&mut self, key: K, value: V) -> Option<V> {
        self.try_insert(key, value).unwrap()
    }

    /// Insert an item into the map.
    /// # Errors
    /// Errors if the key or value schemas do not match the map's.
    pub fn try_insert<K: HasSchema, V: HasSchema>(
        &mut self,
        key: K,
        value: V,
    ) -> Result<Option<V>, SchemaMismatchError> {
        let key = SchemaBox::new(key);
        let value = SchemaBox::new(value);
        self.try_insert_box(key, value)
            // SOUND: try_insert_box won't succeed unless the schema's match, so we have already
            // checked that the value schema matches.
            .map(|value| value.map(|x| unsafe { x.cast_into_unchecked() }))
    }

    /// Insert an untyped item into the map.
    /// # Panics
    /// Panics if the key or value schemas do not match the map's.
    #[track_caller]
    #[inline]
    pub fn insert_box(&mut self, key: SchemaBox, value: SchemaBox) -> Option<SchemaBox> {
        self.try_insert_box(key, value).unwrap()
    }

    /// Insert an untyped item into the map.
    /// # Errors
    /// Errors if the key or value schemas do not match the map's.
    pub fn try_insert_box(
        &mut self,
        key: SchemaBox,
        value: SchemaBox,
    ) -> Result<Option<SchemaBox>, SchemaMismatchError> {
        if key.schema() != self.key_schema || value.schema() != self.value_schema {
            Err(SchemaMismatchError)
        } else {
            // SOUnD: we've checked that the schemas are matching.
            let previous_value = unsafe { self.insert_box_unchecked(key, value) };
            Ok(previous_value)
        }
    }

    /// # Safety
    /// Key schema and value schema must match the map's.
    pub unsafe fn insert_box_unchecked(
        &mut self,
        key: SchemaBox,
        mut value: SchemaBox,
    ) -> Option<SchemaBox> {
        let hash = {
            let mut hasher = self.map.hasher().build_hasher();
            hasher.write_u64(key.hash());
            hasher.finish()
        };
        let entry = self
            .map
            .raw_entry_mut()
            .from_hash(hash, |other| other == &key);
        // Return the previous value.
        match entry {
            hash_map::RawEntryMut::Occupied(mut occupied) => {
                std::mem::swap(occupied.get_mut(), &mut value);
                Some(value)
            }
            hash_map::RawEntryMut::Vacant(vacant) => {
                vacant.insert(key, value);
                None
            }
        }
    }

    /// Get a value out of the map for the given key.
    /// # Panics
    /// Panics if the schemas of the key and value don't match the schemas of the map.
    #[track_caller]
    #[inline]
    pub fn get<K: HasSchema, V: HasSchema>(&self, key: &K) -> Option<&V> {
        self.try_get(key).unwrap()
    }

    /// Get a value out of the map for the given key.
    /// # Errors
    /// Errors if the schemas of the key and value don't match the schemas of the map.
    #[track_caller]
    pub fn try_get<K: HasSchema, V: HasSchema>(
        &self,
        key: &K,
    ) -> Result<Option<&V>, SchemaMismatchError> {
        if K::schema() != self.key_schema || V::schema() != self.value_schema {
            Err(SchemaMismatchError)
        } else {
            // SOUND: we've veriried that they key schema matches the map's
            let value = unsafe { self.get_ref_unchecked(SchemaRef::new(key)) }
                // SOUND: we've verified that the value schema maches the map's
                .map(|x| unsafe { x.cast_into_unchecked() });

            Ok(value)
        }
    }

    /// Get an untyped reference to an item in the map.
    /// # Panics
    /// Panics if the schema of the key doesn't match.
    #[inline]
    #[track_caller]
    pub fn get_ref(&self, key: SchemaRef) -> Option<SchemaRef> {
        self.try_get_ref(key).unwrap()
    }

    /// Get an untyped reference to an item in the map.
    /// # Errors
    /// Errors if the schema of the key doesn't match.
    pub fn try_get_ref(&self, key: SchemaRef) -> Result<Option<SchemaRef>, SchemaMismatchError> {
        if key.schema() != self.key_schema {
            Err(SchemaMismatchError)
        } else {
            // SOUND: we've check the key schema matches.
            Ok(unsafe { self.get_ref_unchecked(key) })
        }
    }

    /// # Safety
    /// The key's schema must match this map's key schema.
    pub unsafe fn get_ref_unchecked(&self, key: SchemaRef) -> Option<SchemaRef> {
        let Some(hash_fn) = &self.key_schema.hash_fn else {
            panic!("Key schema doesn't implement hash");
        };
        let Some(eq_fn) = &self.key_schema.eq_fn else {
            panic!("Key schema doesn't implement eq");
        };
        let key_ptr = key.as_ptr();
        // SOUND: caller asserts the key schema matches
        let raw_hash = unsafe { (hash_fn.get())(key_ptr) };
        let hash = {
            let mut hasher = self.map.hasher().build_hasher();
            hasher.write_u64(raw_hash);
            hasher.finish()
        };
        self.map
            .raw_entry()
            .from_hash(hash, |key| {
                let other_ptr = key.as_ref().as_ptr();
                // SOUND: caller asserts the key schema matches.
                unsafe { (eq_fn.get())(key_ptr, other_ptr) }
            })
            .map(|x| x.1.as_ref())
    }

    /// Get an untyped reference to an item in the map.
    /// # Panics
    /// Panics if the schema of the key doesn't match.
    #[inline]
    #[track_caller]
    pub fn get_ref_mut(&mut self, key: SchemaRef) -> Option<SchemaRefMut> {
        self.try_get_ref_mut(key).unwrap()
    }

    /// Get an untyped reference to an item in the map.
    /// # Errors
    /// Errors if the schema of the key doesn't match.
    pub fn try_get_ref_mut(
        &mut self,
        key: SchemaRef,
    ) -> Result<Option<SchemaRefMut>, SchemaMismatchError> {
        if key.schema() != self.key_schema {
            Err(SchemaMismatchError)
        } else {
            // SOUND: we've checked that the key schema matches.
            Ok(unsafe { self.get_ref_unchecked_mut(key) })
        }
    }

    /// # Safety
    /// The key's schema must match this map's key schema.
    pub unsafe fn get_ref_unchecked_mut(&mut self, key: SchemaRef) -> Option<SchemaRefMut> {
        let Some(hash_fn) = &self.key_schema.hash_fn else {
            panic!("Key schema doesn't implement hash");
        };
        let Some(eq_fn) = &self.key_schema.eq_fn else {
            panic!("Key schema doesn't implement eq");
        };
        let key_ptr = key.as_ptr();
        // SOUND: caller asserts the key schema matches
        let raw_hash = unsafe { (hash_fn.get())(key_ptr) };
        let hash = {
            let mut hasher = self.map.hasher().build_hasher();
            hasher.write_u64(raw_hash);
            hasher.finish()
        };
        let entry = self.map.raw_entry_mut().from_hash(hash, |key| {
            let other_ptr = key.as_ref().as_ptr();
            // SOUND: caller asserts the key schema matches.
            unsafe { (eq_fn.get())(key_ptr, other_ptr) }
        });
        match entry {
            hash_map::RawEntryMut::Occupied(entry) => Some(entry.into_mut()),
            hash_map::RawEntryMut::Vacant(_) => None,
        }
        .map(|x| x.as_mut())
    }

    /// Get a value out of the map for the given key.
    /// # Panics
    /// Panics if the schemas of the key and value don't match the schemas of the map.
    #[track_caller]
    #[inline]
    pub fn get_mut<K: HasSchema, V: HasSchema>(&mut self, key: &K) -> Option<&mut V> {
        self.try_get_mut(key).unwrap()
    }

    /// Get a value out of the map for the given key.
    /// # Errors
    /// Errors if the schemas of the key and value don't match the schemas of the map.
    #[track_caller]
    pub fn try_get_mut<K: HasSchema, V: HasSchema>(
        &mut self,
        key: &K,
    ) -> Result<Option<&mut V>, SchemaMismatchError> {
        if K::schema() != self.key_schema || V::schema() != self.value_schema {
            Err(SchemaMismatchError)
        } else {
            // SOUND: we've checked that the key schema matches.
            let value = unsafe { self.get_ref_unchecked_mut(SchemaRef::new(key)) }
                // SOUND: we've checked that the value schema matches.
                .map(|x| unsafe { x.cast_into_mut_unchecked() });
            Ok(value)
        }
    }

    /// Remove an item.
    /// # Panics
    /// Panics if the schemas of the key and value don't match the map.
    #[inline]
    #[track_caller]
    pub fn remove<K: HasSchema, V: HasSchema>(&mut self, key: &K) -> Option<V> {
        self.try_remove(key).unwrap()
    }

    /// Remove an item.
    /// # Errors
    /// Errors if the schemas of the key and value don't match the map.
    pub fn try_remove<K: HasSchema, V: HasSchema>(
        &mut self,
        key: &K,
    ) -> Result<Option<V>, SchemaMismatchError> {
        if K::schema() != self.key_schema || V::schema() != self.value_schema {
            Err(SchemaMismatchError)
        } else {
            // SOUND: we've checked that the key schema matches.
            let value = unsafe { self.remove_unchecked(SchemaRef::new(key)) }
                // SOUND: we've checked that the value schema matches.
                .map(|x| unsafe { x.cast_into_unchecked() });
            Ok(value)
        }
    }

    /// Untypededly remove an item.
    /// # Panics
    /// Panics if the key schema does not match the map's.
    #[inline]
    #[track_caller]
    pub fn remove_box(&mut self, key: SchemaRef) -> Option<SchemaBox> {
        self.try_remove_box(key).unwrap()
    }

    /// Untypededly remove an item.
    /// # Errors
    /// Errors if the key schema does not match the map's.
    pub fn try_remove_box(
        &mut self,
        key: SchemaRef,
    ) -> Result<Option<SchemaBox>, SchemaMismatchError> {
        if key.schema() != self.key_schema {
            Err(SchemaMismatchError)
        } else {
            // SOUND: we've checked the key schema matches.
            Ok(unsafe { self.remove_unchecked(key) })
        }
    }

    /// # Safety
    /// The key schema must match the map's.
    pub unsafe fn remove_unchecked(&mut self, key: SchemaRef) -> Option<SchemaBox> {
        let Some(hash_fn) = &self.key_schema.hash_fn else {
            panic!("Key schema doesn't implement hash");
        };
        let Some(eq_fn) = &self.key_schema.eq_fn else {
            panic!("Key schema doesn't implement eq");
        };
        let key_ptr = key.as_ptr();
        // SOUND: caller asserts the key schema matches
        let hash = unsafe { (hash_fn.get())(key_ptr) };
        let hash = {
            let mut hasher = self.map.hasher().build_hasher();
            hasher.write_u64(hash);
            hasher.finish()
        };
        let entry = self.map.raw_entry_mut().from_hash(hash, |key| {
            let other_ptr = key.as_ref().as_ptr();
            // SOUND: caller asserts the key schema matches
            unsafe { (eq_fn.get())(key_ptr, other_ptr) }
        });
        match entry {
            hash_map::RawEntryMut::Occupied(entry) => Some(entry.remove()),
            hash_map::RawEntryMut::Vacant(_) => None,
        }
    }

    /// Convert into a typed [`SMap`].
    /// # Panics
    /// Panics if the schemas of K and V don't match the [`SchemaMap`].
    #[inline]
    #[track_caller]
    pub fn into_smap<K: HasSchema, V: HasSchema>(self) -> SMap<K, V> {
        self.try_into_smap().unwrap()
    }

    /// Convert into a typed [`SMap`].
    /// # Errors
    /// Errors if the schemas of K and V don't match the [`SchemaMap`].
    pub fn try_into_smap<K: HasSchema, V: HasSchema>(
        self,
    ) -> Result<SMap<K, V>, SchemaMismatchError> {
        if K::schema() == self.key_schema && V::schema() == self.value_schema {
            Ok(SMap {
                map: self,
                _phantom: PhantomData,
            })
        } else {
            Err(SchemaMismatchError)
        }
    }
}

impl<K: HasSchema, V: HasSchema> FromIterator<(K, V)> for SMap<K, V> {
    fn from_iter<T: IntoIterator<Item = (K, V)>>(iter: T) -> Self {
        let mut this = Self::default();
        for (k, v) in iter {
            this.insert(k, v);
        }
        this
    }
}

impl<K: HasSchema, V: HasSchema> std::ops::Index<&K> for SMap<K, V> {
    type Output = V;
    fn index(&self, index: &K) -> &Self::Output {
        self.get(index).unwrap()
    }
}
impl<K: HasSchema, V: HasSchema> std::ops::IndexMut<&K> for SMap<K, V> {
    fn index_mut(&mut self, index: &K) -> &mut Self::Output {
        self.get_mut(index).unwrap()
    }
}

type SchemaMapIter<'iter> = std::iter::Map<
    hash_map::Iter<'iter, SchemaBox, SchemaBox>,
    for<'a> fn((&'a SchemaBox, &'a SchemaBox)) -> (SchemaRef<'a>, SchemaRef<'a>),
>;
type SchemaMapIterMut<'iter> = std::iter::Map<
    hash_map::IterMut<'iter, SchemaBox, SchemaBox>,
    for<'a> fn((&'a SchemaBox, &'a mut SchemaBox)) -> (SchemaRef<'a>, SchemaRefMut<'a>),
>;
impl SchemaMap {
    /// Iterate over entries in the map.
    #[allow(clippy::type_complexity)]
    pub fn iter(&self) -> SchemaMapIter {
        fn map_fn<'a>(
            (key, value): (&'a SchemaBox, &'a SchemaBox),
        ) -> (SchemaRef<'a>, SchemaRef<'a>) {
            (key.as_ref(), value.as_ref())
        }
        self.map.iter().map(map_fn)
    }

    /// Iterate over entries in the map.
    #[allow(clippy::type_complexity)]
    pub fn iter_mut(&mut self) -> SchemaMapIterMut {
        fn map_fn<'a>(
            (key, value): (&'a SchemaBox, &'a mut SchemaBox),
        ) -> (SchemaRef<'a>, SchemaRefMut<'a>) {
            (key.as_ref(), value.as_mut())
        }
        self.map.iter_mut().map(map_fn)
    }

    /// Iterate over keys in the map.
    #[allow(clippy::type_complexity)]
    pub fn keys(
        &self,
    ) -> std::iter::Map<
        hash_map::Keys<SchemaBox, SchemaBox>,
        for<'a> fn(&'a SchemaBox) -> SchemaRef<'a>,
    > {
        fn map_fn(key: &SchemaBox) -> SchemaRef {
            key.as_ref()
        }
        self.map.keys().map(map_fn)
    }

    /// Iterate over values in the map.
    #[allow(clippy::type_complexity)]
    pub fn values(
        &self,
    ) -> std::iter::Map<
        hash_map::Values<SchemaBox, SchemaBox>,
        for<'a> fn(&'a SchemaBox) -> SchemaRef<'a>,
    > {
        fn map_fn(key: &SchemaBox) -> SchemaRef {
            key.as_ref()
        }
        self.map.values().map(map_fn)
    }

    /// Iterate over values in the map.
    #[allow(clippy::type_complexity)]
    pub fn values_mut(
        &mut self,
    ) -> std::iter::Map<
        hash_map::ValuesMut<SchemaBox, SchemaBox>,
        for<'a> fn(&'a mut SchemaBox) -> SchemaRefMut<'a>,
    > {
        fn map_fn(key: &mut SchemaBox) -> SchemaRefMut {
            key.as_mut()
        }
        self.map.values_mut().map(map_fn)
    }
}
impl<'a> IntoIterator for &'a SchemaMap {
    type Item = (SchemaRef<'a>, SchemaRef<'a>);
    type IntoIter = SchemaMapIter<'a>;
    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}
impl<'a> IntoIterator for &'a mut SchemaMap {
    type Item = (SchemaRef<'a>, SchemaRefMut<'a>);
    type IntoIter = SchemaMapIterMut<'a>;
    fn into_iter(self) -> Self::IntoIter {
        self.iter_mut()
    }
}

/// Typed version of a [`SchemaMap`].
///
/// This works essentially like a [`HashMap`], but is compatible with the schema ecosystem.
///
/// It is also slightly more efficient to access an [`SMap`] compared to a [`SchemaMap`] because it
/// doesn't need to do a runtime schema check every time the map is accessed.
pub struct SMap<K: HasSchema, V: HasSchema> {
    map: SchemaMap,
    _phantom: PhantomData<(K, V)>,
}
impl<K: HasSchema + Debug, V: HasSchema + Debug> Debug for SMap<K, V> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut f = f.debug_map();
        for (k, v) in self {
            f.entry(k, v);
        }
        f.finish()
    }
}
impl<K: HasSchema, V: HasSchema> Clone for SMap<K, V> {
    fn clone(&self) -> Self {
        Self {
            map: self.map.clone(),
            _phantom: self._phantom,
        }
    }
}
impl<K: HasSchema, V: HasSchema> Default for SMap<K, V> {
    fn default() -> Self {
        Self {
            map: SchemaMap::new(K::schema(), V::schema()),
            _phantom: Default::default(),
        }
    }
}
unsafe impl<K: HasSchema, V: HasSchema> HasSchema for SMap<K, V> {
    fn schema() -> &'static Schema {
        static S: OnceLock<RwLock<HashMap<TypeId, &'static Schema>>> = OnceLock::new();
        let schema = {
            S.get_or_init(default)
                .read()
                .get(&TypeId::of::<Self>())
                .copied()
        };
        schema.unwrap_or_else(|| {
            let schema = SCHEMA_REGISTRY.register(SchemaData {
                name: type_name::<Self>().into(),
                full_name: format!("{}::{}", module_path!(), type_name::<Self>()).into(),
                kind: SchemaKind::Map {
                    key: K::schema(),
                    value: V::schema(),
                },
                type_id: Some(TypeId::of::<Self>()),
                clone_fn: Some(<Self as RawClone>::raw_clone_cb()),
                drop_fn: Some(<Self as RawDrop>::raw_drop_cb()),
                default_fn: Some(<Self as RawDefault>::raw_default_cb()),
                hash_fn: Some(unsafe {
                    Unsafe::new(Box::leak(Box::new(|a| SchemaVec::raw_hash(a))))
                }),
                eq_fn: Some(unsafe {
                    Unsafe::new(Box::leak(Box::new(|a, b| SchemaVec::raw_eq(a, b))))
                }),
                type_data: Default::default(),
            });

            S.get_or_init(default)
                .write()
                .insert(TypeId::of::<Self>(), schema);

            schema
        })
    }
}

impl<K: HasSchema, V: HasSchema> SMap<K, V> {
    /// Initialize the [`SMap`].
    pub fn new() -> Self {
        Self::default()
    }

    /// Insert an entry into the map, returning the previous value, if it exists.
    pub fn insert(&mut self, k: K, v: V) -> Option<V> {
        // SOUND: schemas are checked to match when SMap is constructed.
        unsafe {
            self.map
                .insert_box_unchecked(SchemaBox::new(k), SchemaBox::new(v))
                .map(|x| x.cast_into_unchecked())
        }
    }

    /// Get a reference to an item in the map.
    pub fn get(&self, key: &K) -> Option<&V> {
        // SOUND: schemas are checked to match when SMap is constructed.
        unsafe {
            self.map
                .get_ref_unchecked(SchemaRef::new(key))
                .map(|x| x.cast_into_unchecked())
        }
    }

    /// Get a mutable reference to an item in the map.
    pub fn get_mut(&mut self, key: &K) -> Option<&mut V> {
        // SOUND: schemas are checked to match when SMap is constructed.
        unsafe {
            self.map
                .get_ref_unchecked_mut(SchemaRef::new(key))
                .map(|x| x.cast_into_mut_unchecked())
        }
    }

    /// Remove an item from the map.
    pub fn remove(&mut self, key: &K) -> Option<V> {
        // SOUND: schemas are checked to match when SMap is constructed.
        unsafe {
            self.map
                .remove_unchecked(SchemaRef::new(key))
                .map(|x| x.cast_into_unchecked())
        }
    }

    /// Convert into an untyped [`SchemaMap`].
    pub fn into_schema_map(self) -> SchemaMap {
        self.map
    }

    /// Returns true if the map contains a value for the specified key.
    pub fn contains_key(&self, key: &K) -> bool {
        self.map.get::<K, V>(key).is_some()
    }

    /// Returns the number of elements in the map.
    pub fn len(&self) -> usize {
        self.map.len()
    }

    /// Returns true if the map contains no elements.
    pub fn is_empty(&self) -> bool {
        self.map.is_empty()
    }
}

type SMapIter<'iter, K, V> = std::iter::Map<
    hash_map::Iter<'iter, SchemaBox, SchemaBox>,
    for<'a> fn((&'a SchemaBox, &'a SchemaBox)) -> (&'a K, &'a V),
>;
type SMapIterMut<'iter, K, V> = std::iter::Map<
    hash_map::IterMut<'iter, SchemaBox, SchemaBox>,
    for<'a> fn((&'a SchemaBox, &'a mut SchemaBox)) -> (&'a K, &'a mut V),
>;
impl<K: HasSchema, V: HasSchema> SMap<K, V> {
    /// Iterate over entries in the map.
    #[allow(clippy::type_complexity)]
    pub fn iter(&self) -> SMapIter<K, V> {
        fn map_fn<'a, K: HasSchema, V: HasSchema>(
            (key, value): (&'a SchemaBox, &'a SchemaBox),
        ) -> (&'a K, &'a V) {
            // SOUND: SMap ensures K and V schemas always match.
            unsafe {
                (
                    key.as_ref().cast_into_unchecked(),
                    value.as_ref().cast_into_unchecked(),
                )
            }
        }
        self.map.map.iter().map(map_fn)
    }

    /// Iterate over entries in the map.
    #[allow(clippy::type_complexity)]
    pub fn iter_mut(&mut self) -> SMapIterMut<K, V> {
        fn map_fn<'a, K: HasSchema, V: HasSchema>(
            (key, value): (&'a SchemaBox, &'a mut SchemaBox),
        ) -> (&'a K, &'a mut V) {
            // SOUND: SMap ensures K and V schemas always match.
            unsafe {
                (
                    key.as_ref().cast_into_unchecked(),
                    value.as_mut().cast_into_mut_unchecked(),
                )
            }
        }
        self.map.map.iter_mut().map(map_fn)
    }

    /// Iterate over keys in the map.
    #[allow(clippy::type_complexity)]
    pub fn keys(
        &self,
    ) -> std::iter::Map<hash_map::Keys<SchemaBox, SchemaBox>, for<'a> fn(&'a SchemaBox) -> &'a K>
    {
        fn map_fn<K: HasSchema>(key: &SchemaBox) -> &K {
            // SOUND: SMap ensures key schema always match
            unsafe { key.as_ref().cast_into_unchecked() }
        }
        self.map.map.keys().map(map_fn)
    }

    /// Iterate over values in the map.
    #[allow(clippy::type_complexity)]
    pub fn values(
        &self,
    ) -> std::iter::Map<hash_map::Values<SchemaBox, SchemaBox>, for<'a> fn(&'a SchemaBox) -> &'a V>
    {
        fn map_fn<V: HasSchema>(value: &SchemaBox) -> &V {
            // SOUND: SMap ensures value schema always matches.
            unsafe { value.as_ref().cast_into_unchecked() }
        }
        self.map.map.values().map(map_fn)
    }

    /// Iterate over values in the map.
    #[allow(clippy::type_complexity)]
    pub fn values_mut(
        &mut self,
    ) -> std::iter::Map<
        hash_map::ValuesMut<SchemaBox, SchemaBox>,
        for<'a> fn(&'a mut SchemaBox) -> &'a mut V,
    > {
        fn map_fn<V>(value: &mut SchemaBox) -> &mut V {
            // SOUND: SMap ensures value schema always matches
            unsafe { value.as_mut().cast_into_mut_unchecked() }
        }
        self.map.map.values_mut().map(map_fn)
    }
}
impl<'a, K: HasSchema, V: HasSchema> IntoIterator for &'a SMap<K, V> {
    type Item = (&'a K, &'a V);
    type IntoIter = SMapIter<'a, K, V>;
    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}
impl<'a, K: HasSchema, V: HasSchema> IntoIterator for &'a mut SMap<K, V> {
    type Item = (&'a K, &'a mut V);
    type IntoIter = SMapIterMut<'a, K, V>;
    fn into_iter(self) -> Self::IntoIter {
        self.iter_mut()
    }
}