fayalite 0.2.0

Hardware Description Language embedded in Rust, using FIRRTL's semantics
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
// SPDX-License-Identifier: LGPL-3.0-or-later
// See Notices.txt for copyright information
#![allow(clippy::type_complexity)]
use crate::intern::type_map::TypeIdMap;
use bitvec::{ptr::BitPtr, slice::BitSlice, vec::BitVec};
use hashbrown::{hash_map::RawEntryMut, HashMap, HashTable};
use serde::{Deserialize, Serialize};
use std::{
    any::{Any, TypeId},
    borrow::{Borrow, Cow},
    cmp::Ordering,
    fmt,
    hash::{BuildHasher, Hash, Hasher},
    iter::FusedIterator,
    marker::PhantomData,
    ops::Deref,
    sync::{Mutex, RwLock},
};

pub mod type_map;

pub trait LazyInternedTrait<T: ?Sized + Send + Sync + 'static>: Send + Sync + Any {
    fn get(&self) -> Interned<T>;
}

impl<T: ?Sized + Send + Sync + 'static, F: ?Sized + Fn() -> Interned<T> + Send + Sync + Any>
    LazyInternedTrait<T> for F
{
    fn get(&self) -> Interned<T> {
        self()
    }
}

#[repr(transparent)]
pub struct LazyInternedFn<T: ?Sized + Send + Sync + 'static>(pub &'static dyn LazyInternedTrait<T>);

impl<T: ?Sized + Send + Sync + 'static> Copy for LazyInternedFn<T> {}

impl<T: ?Sized + Send + Sync + 'static> Clone for LazyInternedFn<T> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<T: ?Sized + Send + Sync + 'static> Hash for LazyInternedFn<T> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.0.get_ptr_eq_with_type_id().hash(state);
    }
}

impl<T: ?Sized + Send + Sync + 'static> Eq for LazyInternedFn<T> {}

impl<T: ?Sized + Send + Sync + 'static> PartialEq for LazyInternedFn<T> {
    fn eq(&self, other: &Self) -> bool {
        self.0.get_ptr_eq_with_type_id() == other.0.get_ptr_eq_with_type_id()
    }
}

pub enum LazyInterned<T: ?Sized + Send + Sync + 'static> {
    Interned(Interned<T>),
    Lazy(LazyInternedFn<T>),
}

impl<T: ?Sized + Send + Sync + 'static> LazyInterned<T> {
    pub const fn new_lazy(v: &'static dyn LazyInternedTrait<T>) -> Self {
        Self::Lazy(LazyInternedFn(v))
    }
}

impl<T: ?Sized + Sync + Send + 'static> Clone for LazyInterned<T> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<T: ?Sized + Sync + Send + 'static> Copy for LazyInterned<T> {}

impl<T: ?Sized + Sync + Send + 'static + Intern> Deref for LazyInterned<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        Interned::into_inner(self.interned())
    }
}

impl<T: ?Sized + Sync + Send + 'static + Intern> Eq for LazyInterned<T> where Interned<T>: Eq {}

impl<T: ?Sized + Sync + Send + 'static + Intern> PartialEq for LazyInterned<T>
where
    Interned<T>: PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        self.interned() == other.interned()
    }
}

impl<T: ?Sized + Sync + Send + 'static + Intern> Ord for LazyInterned<T>
where
    Interned<T>: Ord,
{
    fn cmp(&self, other: &Self) -> Ordering {
        self.interned().cmp(&other.interned())
    }
}

impl<T: ?Sized + Sync + Send + 'static + Intern> PartialOrd for LazyInterned<T>
where
    Interned<T>: PartialOrd,
{
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        self.interned().partial_cmp(&other.interned())
    }
}

impl<T: ?Sized + Sync + Send + 'static + Intern> Hash for LazyInterned<T>
where
    Interned<T>: Hash,
{
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.interned().hash(state);
    }
}

impl<T: ?Sized + Sync + Send + 'static> LazyInterned<T> {
    pub fn interned(self) -> Interned<T>
    where
        T: Intern,
    {
        struct MemoizeInterned<T: ?Sized + Intern>(PhantomData<T>);

        impl<T: ?Sized + Intern> Hash for MemoizeInterned<T> {
            fn hash<H: Hasher>(&self, _state: &mut H) {}
        }

        impl<T: ?Sized + Intern> PartialEq for MemoizeInterned<T> {
            fn eq(&self, _other: &Self) -> bool {
                true
            }
        }

        impl<T: ?Sized + Intern> Eq for MemoizeInterned<T> {}

        impl<T: ?Sized + Intern> Clone for MemoizeInterned<T> {
            fn clone(&self) -> Self {
                *self
            }
        }

        impl<T: ?Sized + Intern> Copy for MemoizeInterned<T> {}

        impl<T: ?Sized + Intern> MemoizeGeneric for MemoizeInterned<T> {
            type InputRef<'a> = LazyInternedFn<T>;

            type InputOwned = LazyInternedFn<T>;

            type InputCow<'a> = LazyInternedFn<T>;

            type Output = Interned<T>;

            fn input_eq(a: Self::InputRef<'_>, b: Self::InputRef<'_>) -> bool {
                a == b
            }

            fn input_borrow(input: &Self::InputOwned) -> Self::InputRef<'_> {
                *input
            }

            fn input_cow_into_owned(input: Self::InputCow<'_>) -> Self::InputOwned {
                input
            }

            fn input_cow_borrow<'a>(input: &'a Self::InputCow<'_>) -> Self::InputRef<'a> {
                *input
            }

            fn input_cow_from_owned<'a>(input: Self::InputOwned) -> Self::InputCow<'a> {
                input
            }

            fn input_cow_from_ref(input: Self::InputRef<'_>) -> Self::InputCow<'_> {
                input
            }

            fn inner(self, input: Self::InputRef<'_>) -> Self::Output {
                input.0.get()
            }
        }
        match self {
            Self::Interned(retval) => retval,
            Self::Lazy(retval) => MemoizeInterned(PhantomData).get(retval),
        }
    }
}

pub trait InternedCompare {
    type InternedCompareKey: Ord + Hash;
    fn interned_compare_key_ref(this: &Self) -> Self::InternedCompareKey;
}

/// Warning: doesn't do what you want with `T = dyn Trait`,
/// since it compares pointers, but pointers can be unequal due do
/// different copies of the same vtable
pub struct PtrEqWithMetadata<T: ?Sized>(pub *const T);

impl<T: ?Sized> Copy for PtrEqWithMetadata<T> {}

impl<T: ?Sized> Clone for PtrEqWithMetadata<T> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<T: ?Sized> PartialEq for PtrEqWithMetadata<T> {
    fn eq(&self, other: &Self) -> bool {
        std::ptr::eq(self.0, other.0)
    }
}

impl<T: ?Sized> Eq for PtrEqWithMetadata<T> {}

impl<T: ?Sized> PartialOrd for PtrEqWithMetadata<T> {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl<T: ?Sized> Ord for PtrEqWithMetadata<T> {
    fn cmp(&self, other: &Self) -> Ordering {
        #[allow(ambiguous_wide_pointer_comparisons)]
        self.0.cmp(&other.0)
    }
}

impl<T: ?Sized> Hash for PtrEqWithMetadata<T> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.0.hash(state);
    }
}

impl<T: ?Sized> fmt::Debug for PtrEqWithMetadata<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("PtrEqWithMetadata").field(&self.0).finish()
    }
}

/// Warning: doesn't do what you want for `[T]` or `str`, since it ignores length
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub struct PtrEqWithTypeId(pub *const (), pub TypeId);

mod sealed {
    pub trait SupportsPtrEqWithTypeIdSealed {}
}

pub trait SupportsPtrEqWithTypeId: 'static + sealed::SupportsPtrEqWithTypeIdSealed {
    fn get_ptr_eq_with_type_id(&self) -> PtrEqWithTypeId;
}

impl<T: 'static> sealed::SupportsPtrEqWithTypeIdSealed for T {}

impl<T: 'static> SupportsPtrEqWithTypeId for T {
    fn get_ptr_eq_with_type_id(&self) -> PtrEqWithTypeId {
        PtrEqWithTypeId(self as *const Self as *const (), TypeId::of::<Self>())
    }
}

impl<T> InternedCompare for T {
    type InternedCompareKey = PtrEqWithMetadata<Self>;
    fn interned_compare_key_ref(this: &Self) -> Self::InternedCompareKey {
        PtrEqWithMetadata(this)
    }
}

impl<T> InternedCompare for [T] {
    type InternedCompareKey = PtrEqWithMetadata<Self>;
    fn interned_compare_key_ref(this: &Self) -> Self::InternedCompareKey {
        PtrEqWithMetadata(this)
    }
}

#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct BitSlicePtrEq(BitPtr, usize);

impl InternedCompare for BitSlice {
    type InternedCompareKey = BitSlicePtrEq;
    fn interned_compare_key_ref(this: &Self) -> Self::InternedCompareKey {
        BitSlicePtrEq(this.as_bitptr(), this.len())
    }
}

impl InternedCompare for str {
    type InternedCompareKey = PtrEqWithMetadata<Self>;
    fn interned_compare_key_ref(this: &Self) -> Self::InternedCompareKey {
        PtrEqWithMetadata(this)
    }
}

pub trait Intern: Any + Send + Sync {
    fn intern(&self) -> Interned<Self>;
    fn intern_sized(self) -> Interned<Self>
    where
        Self: Clone,
    {
        Self::intern_owned(self)
    }
    fn intern_owned(this: <Self as ToOwned>::Owned) -> Interned<Self>
    where
        Self: ToOwned,
    {
        Self::intern_cow(Cow::Owned(this))
    }
    fn intern_cow(this: Cow<'_, Self>) -> Interned<Self>
    where
        Self: ToOwned,
    {
        this.intern()
    }
}

pub struct Interner<T: ?Sized + 'static + Send + Sync> {
    map: Mutex<HashMap<&'static T, ()>>,
}

impl<T: ?Sized + 'static + Send + Sync> Interner<T> {
    fn get() -> &'static Interner<T> {
        static TYPE_ID_MAP: TypeIdMap = TypeIdMap::new();
        TYPE_ID_MAP.get_or_insert_default()
    }
}

impl<T: ?Sized + 'static + Send + Sync> Default for Interner<T> {
    fn default() -> Self {
        Self {
            map: Default::default(),
        }
    }
}

impl<T: ?Sized + 'static + Send + Sync + Hash + Eq + ToOwned> Interner<T> {
    fn intern<F: FnOnce(Cow<'_, T>) -> &'static T>(
        &self,
        alloc: F,
        value: Cow<'_, T>,
    ) -> Interned<T> {
        let mut map = self.map.lock().unwrap();
        let hasher = map.hasher().clone();
        let hash = hasher.hash_one(&*value);
        let inner = match map.raw_entry_mut().from_hash(hash, |k| **k == *value) {
            RawEntryMut::Occupied(entry) => *entry.key(),
            RawEntryMut::Vacant(entry) => {
                *entry
                    .insert_with_hasher(hash, alloc(value), (), |k| hasher.hash_one(&**k))
                    .0
            }
        };
        Interned { inner }
    }
}

impl<T: Clone + 'static + Send + Sync + Hash + Eq> Interner<T> {
    fn intern_sized(&self, value: Cow<'_, T>) -> Interned<T> {
        self.intern(|value| Box::leak(Box::new(value.into_owned())), value)
    }
}

impl<T: Clone + 'static + Send + Sync + Hash + Eq> Interner<[T]> {
    fn intern_slice(&self, value: Cow<'_, [T]>) -> Interned<[T]> {
        self.intern(|value| value.into_owned().leak(), value)
    }
}

impl Interner<BitSlice> {
    fn intern_bit_slice(&self, value: Cow<'_, BitSlice>) -> Interned<BitSlice> {
        self.intern(|value| value.into_owned().leak(), value)
    }
}

impl Interner<str> {
    fn intern_str(&self, value: Cow<'_, str>) -> Interned<str> {
        self.intern(|value| value.into_owned().leak(), value)
    }
}

pub struct Interned<T: ?Sized + 'static + Send + Sync> {
    inner: &'static T,
}

macro_rules! forward_fmt_trait {
    ($Tr:ident) => {
        impl<T: ?Sized + Intern + fmt::$Tr> fmt::$Tr for LazyInterned<T> {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                T::fmt(&**self, f)
            }
        }

        impl<T: ?Sized + 'static + Send + Sync + fmt::$Tr> fmt::$Tr for Interned<T> {
            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                self.inner.fmt(f)
            }
        }
    };
}

forward_fmt_trait!(Debug);
forward_fmt_trait!(Display);
forward_fmt_trait!(LowerExp);
forward_fmt_trait!(LowerHex);
forward_fmt_trait!(Octal);
forward_fmt_trait!(Pointer);
forward_fmt_trait!(UpperExp);
forward_fmt_trait!(UpperHex);

#[derive(Clone, Debug)]
pub struct InternedSliceIter<T: Clone + 'static + Send + Sync> {
    slice: Interned<[T]>,
    index: std::ops::Range<usize>,
}

impl<T: Clone + 'static + Send + Sync> Iterator for InternedSliceIter<T> {
    type Item = T;

    fn next(&mut self) -> Option<Self::Item> {
        self.index.next().map(|index| self.slice[index].clone())
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.index.size_hint()
    }
}

impl<T: Clone + 'static + Send + Sync> DoubleEndedIterator for InternedSliceIter<T> {
    fn next_back(&mut self) -> Option<Self::Item> {
        self.index
            .next_back()
            .map(|index| self.slice[index].clone())
    }
}

impl<T: Clone + 'static + Send + Sync> FusedIterator for InternedSliceIter<T> {}

impl<T: Clone + 'static + Send + Sync> ExactSizeIterator for InternedSliceIter<T> {}

impl<T: Clone + 'static + Send + Sync> IntoIterator for Interned<[T]> {
    type Item = T;
    type IntoIter = InternedSliceIter<T>;

    fn into_iter(self) -> Self::IntoIter {
        InternedSliceIter {
            index: 0..self.len(),
            slice: self,
        }
    }
}

impl<'a, T: 'static + Send + Sync> IntoIterator for &'a Interned<[T]> {
    type Item = &'a T;
    type IntoIter = std::slice::Iter<'a, T>;

    fn into_iter(self) -> Self::IntoIter {
        self.inner.iter()
    }
}

impl<'a, T: 'static + Send + Sync> IntoIterator for &'a mut Interned<[T]> {
    type Item = &'a T;
    type IntoIter = std::slice::Iter<'a, T>;

    fn into_iter(self) -> Self::IntoIter {
        self.inner.iter()
    }
}

impl<I: Clone> FromIterator<I> for Interned<[I]>
where
    [I]: Intern,
{
    fn from_iter<T: IntoIterator<Item = I>>(iter: T) -> Self {
        Intern::intern_owned(Vec::from_iter(iter))
    }
}

impl<T: 'static + Clone + Send + Sync> From<Interned<[T]>> for Vec<T> {
    fn from(value: Interned<[T]>) -> Self {
        Vec::from(&*value)
    }
}

impl<T: 'static + Clone + Send + Sync> From<Interned<[T]>> for Box<[T]> {
    fn from(value: Interned<[T]>) -> Self {
        Box::from(&*value)
    }
}

impl From<Interned<str>> for String {
    fn from(value: Interned<str>) -> Self {
        String::from(&*value)
    }
}

impl<I> Default for Interned<[I]>
where
    [I]: Intern,
{
    fn default() -> Self {
        [][..].intern()
    }
}

impl Default for Interned<str> {
    fn default() -> Self {
        "".intern()
    }
}

impl Default for Interned<BitSlice> {
    fn default() -> Self {
        <&BitSlice>::default().intern()
    }
}

impl<I: Clone + Default> Default for Interned<I>
where
    I: Intern,
{
    fn default() -> Self {
        I::default().intern()
    }
}

impl<T: ?Sized + 'static + Send + Sync> Interned<T> {
    pub fn cast_unchecked<U: ?Sized + 'static + Send + Sync>(
        this: Self,
        f: impl FnOnce(&'static T) -> &'static U,
    ) -> Interned<U> {
        Interned {
            inner: f(this.inner),
        }
    }
    pub fn try_cast_unchecked<U: ?Sized + 'static + Send + Sync, E>(
        this: Self,
        f: impl FnOnce(&'static T) -> Result<&'static U, E>,
    ) -> Result<Interned<U>, E> {
        Ok(Interned {
            inner: f(this.inner)?,
        })
    }
    pub fn into_inner(this: Self) -> &'static T {
        this.inner
    }
    pub fn get_ref(this: &Self) -> &&'static T {
        &this.inner
    }
}

impl<T: ?Sized + 'static + Send + Sync> Clone for Interned<T> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<T: ?Sized + 'static + Send + Sync> Copy for Interned<T> where &'static T: Copy {}

impl<T: ?Sized + 'static + Send + Sync> Deref for Interned<T>
where
    &'static T: Borrow<T>,
{
    type Target = T;

    fn deref(&self) -> &Self::Target {
        self.inner
    }
}

impl<T: ?Sized + 'static + Send + Sync + InternedCompare> PartialEq for Interned<T> {
    fn eq(&self, other: &Self) -> bool {
        T::interned_compare_key_ref(self.inner) == T::interned_compare_key_ref(other.inner)
    }
}

impl<T: ?Sized + 'static + Send + Sync + InternedCompare> Eq for Interned<T> {}

impl<T: ?Sized + 'static + Send + Sync + InternedCompare> PartialOrd for Interned<T> {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl<T: ?Sized + 'static + Send + Sync + InternedCompare> Ord for Interned<T> {
    fn cmp(&self, other: &Self) -> Ordering {
        T::interned_compare_key_ref(self.inner).cmp(&T::interned_compare_key_ref(other.inner))
    }
}

impl<T: ?Sized + 'static + Send + Sync + InternedCompare> Hash for Interned<T> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        T::interned_compare_key_ref(self.inner).hash(state);
    }
}

impl<T: ?Sized + 'static + Send + Sync + Serialize> Serialize for Interned<T> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        T::serialize(self, serializer)
    }
}

impl<'de, T: 'static + Send + Sync + Deserialize<'de> + Clone + Intern> Deserialize<'de>
    for Interned<T>
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        T::deserialize(deserializer).map(Intern::intern_sized)
    }
}

impl<'de, T: 'static + Send + Sync + Clone> Deserialize<'de> for Interned<[T]>
where
    [T]: Intern,
    Vec<T>: Deserialize<'de>,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        Vec::<T>::deserialize(deserializer).map(Intern::intern_owned)
    }
}

impl<'de> Deserialize<'de> for Interned<BitSlice> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        BitVec::deserialize(deserializer).map(Intern::intern_owned)
    }
}

impl<'de> Deserialize<'de> for Interned<str> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        String::deserialize(deserializer).map(Intern::intern_owned)
    }
}

impl<T: Clone + Send + Sync + 'static + Hash + Eq> Intern for T {
    fn intern(&self) -> Interned<Self> {
        Self::intern_cow(Cow::Borrowed(self))
    }

    fn intern_owned(this: <Self as ToOwned>::Owned) -> Interned<Self>
    where
        Self: ToOwned,
    {
        Self::intern_cow(Cow::Owned(this))
    }

    fn intern_cow(this: Cow<'_, Self>) -> Interned<Self>
    where
        Self: ToOwned,
    {
        Interner::get().intern_sized(this)
    }
}

impl<T: Clone + Send + Sync + 'static + Hash + Eq> Intern for [T] {
    fn intern(&self) -> Interned<Self> {
        Self::intern_cow(Cow::Borrowed(self))
    }

    fn intern_owned(this: <Self as ToOwned>::Owned) -> Interned<Self>
    where
        Self: ToOwned,
    {
        Self::intern_cow(Cow::Owned(this))
    }

    fn intern_cow(this: Cow<'_, Self>) -> Interned<Self>
    where
        Self: ToOwned,
    {
        Interner::get().intern_slice(this)
    }
}

impl Intern for BitSlice {
    fn intern(&self) -> Interned<Self> {
        Self::intern_cow(Cow::Borrowed(self))
    }

    fn intern_owned(this: <Self as ToOwned>::Owned) -> Interned<Self>
    where
        Self: ToOwned,
    {
        Self::intern_cow(Cow::Owned(this))
    }

    fn intern_cow(this: Cow<'_, Self>) -> Interned<Self>
    where
        Self: ToOwned,
    {
        Interner::get().intern_bit_slice(this)
    }
}

impl Intern for str {
    fn intern(&self) -> Interned<Self> {
        Self::intern_cow(Cow::Borrowed(self))
    }

    fn intern_owned(this: <Self as ToOwned>::Owned) -> Interned<Self>
    where
        Self: ToOwned,
    {
        Self::intern_cow(Cow::Owned(this))
    }

    fn intern_cow(this: Cow<'_, Self>) -> Interned<Self>
    where
        Self: ToOwned,
    {
        Interner::get().intern_str(this)
    }
}

pub trait MemoizeGeneric: 'static + Send + Sync + Hash + Eq + Copy {
    type InputRef<'a>: 'a + Send + Sync + Hash + Copy;
    type InputOwned: 'static + Send + Sync;
    type InputCow<'a>: 'a;
    type Output: 'static + Send + Sync + Clone;
    fn input_eq(a: Self::InputRef<'_>, b: Self::InputRef<'_>) -> bool;
    fn input_borrow(input: &Self::InputOwned) -> Self::InputRef<'_>;
    fn input_cow_into_owned(input: Self::InputCow<'_>) -> Self::InputOwned;
    fn input_cow_borrow<'a>(input: &'a Self::InputCow<'_>) -> Self::InputRef<'a>;
    fn input_cow_from_owned<'a>(input: Self::InputOwned) -> Self::InputCow<'a>;
    fn input_cow_from_ref(input: Self::InputRef<'_>) -> Self::InputCow<'_>;
    fn inner(self, input: Self::InputRef<'_>) -> Self::Output;
    fn get_cow(self, input: Self::InputCow<'_>) -> Self::Output {
        static TYPE_ID_MAP: TypeIdMap = TypeIdMap::new();
        let map: &RwLock<(
            hashbrown::hash_map::DefaultHashBuilder,
            HashTable<(Self, Self::InputOwned, Self::Output)>,
        )> = TYPE_ID_MAP.get_or_insert_default();
        fn hash_eq_key<'a, 'b, T: MemoizeGeneric>(
            this: &'a T,
            input: T::InputRef<'b>,
        ) -> (&'a T, T::InputRef<'b>) {
            (this, input)
        }
        fn hash_eq_key_eq<T: MemoizeGeneric>(
            key: (&T, T::InputRef<'_>),
            this: &T,
            input: T::InputRef<'_>,
        ) -> bool {
            let other = hash_eq_key(this, input);
            key.0 == other.0 && T::input_eq(key.1, other.1)
        }
        let key = hash_eq_key(&self, Self::input_cow_borrow(&input));
        let hash;
        {
            let read = map.read().unwrap();
            let (hasher, map) = &*read;
            hash = hasher.hash_one(key);
            if let Some((_, _, output)) = map.find(hash, |(this2, input2, _)| {
                hash_eq_key_eq(key, this2, Self::input_borrow(input2))
            }) {
                return output.clone();
            }
            drop(read);
        }
        // make sure to call inner while map isn't locked since inner may call get_cow again
        let output = self.inner(Self::input_cow_borrow(&input));
        let mut write = map.write().unwrap();
        let (hasher, map) = &mut *write;
        map.entry(
            hash,
            |(this2, input2, _)| hash_eq_key_eq(key, this2, Self::input_borrow(input2)),
            |(this2, input2, _)| hasher.hash_one(hash_eq_key(this2, Self::input_borrow(input2))),
        )
        .or_insert_with(|| (self, Self::input_cow_into_owned(input), output))
        .get()
        .2
        .clone()
    }
    fn get_owned(self, input: Self::InputOwned) -> Self::Output {
        self.get_cow(Self::input_cow_from_owned(input))
    }
    fn get(self, input: Self::InputRef<'_>) -> Self::Output {
        self.get_cow(Self::input_cow_from_ref(input))
    }
}

pub trait Memoize: 'static + Send + Sync + Hash + Eq + Copy {
    type Input: ?Sized + 'static + Send + Sync + ToOwned<Owned = Self::InputOwned> + Hash + Eq;
    type InputOwned: 'static + Send + Sync + Borrow<Self::Input>;
    type Output: 'static + Send + Sync + Clone;
    fn inner(self, input: &Self::Input) -> Self::Output;
    fn get_cow(self, input: Cow<'_, Self::Input>) -> Self::Output {
        #[derive(Hash, Eq, PartialEq, Copy, Clone)]
        struct MemoizeGenericWrapper<T: Memoize>(T);
        impl<T: Memoize> MemoizeGeneric for MemoizeGenericWrapper<T> {
            type InputRef<'a> = &'a T::Input;
            type InputOwned = T::InputOwned;
            type InputCow<'a> = Cow<'a, T::Input>;
            type Output = T::Output;

            fn input_borrow(input: &Self::InputOwned) -> Self::InputRef<'_> {
                input.borrow()
            }

            fn input_eq(a: Self::InputRef<'_>, b: Self::InputRef<'_>) -> bool {
                a == b
            }

            fn input_cow_into_owned(input: Self::InputCow<'_>) -> Self::InputOwned {
                input.into_owned()
            }

            fn input_cow_borrow<'a>(input: &'a Self::InputCow<'_>) -> Self::InputRef<'a> {
                &**input
            }

            fn input_cow_from_owned<'a>(input: Self::InputOwned) -> Self::InputCow<'a> {
                Cow::Owned(input)
            }

            fn input_cow_from_ref(input: Self::InputRef<'_>) -> Self::InputCow<'_> {
                Cow::Borrowed(input)
            }

            fn inner(self, input: Self::InputRef<'_>) -> Self::Output {
                self.0.inner(input)
            }
        }

        MemoizeGenericWrapper(self).get_cow(input)
    }
    fn get_owned(self, input: Self::InputOwned) -> Self::Output {
        self.get_cow(Cow::Owned(input))
    }
    fn get(self, input: &Self::Input) -> Self::Output {
        self.get_cow(Cow::Borrowed(input))
    }
}