dync 0.4.0

An efficient alternative to `dyn Trait` for containerized types
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
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
//! This module defines a mechanism for type earasure simplar to `dyn Any`.
//!
//! This method allows storing and referencing values coming from a `DataBuffer` in other `std`
//! containers without needing a downcast.
//!
#![allow(dead_code)]

use std::any::{Any, TypeId};
use std::fmt;
use std::hash::{Hash, Hasher};
use std::mem::{ManuallyDrop, MaybeUninit};

// At the time of this writing, there is no evidence that there is a significant benefit in sharing
// vtables via Rc or Arc, but to make potential future refactoring easier we use the Ptr alias.
use std::boxed::Box as Ptr;

use crate::bytes::*;
use crate::traits::*;
use crate::Elem;

#[derive(Debug)]
pub enum Error {
    /// Value could not fit into a single pointer sized word.
    ValueTooLarge,
    /// Mismatched types.
    ///
    /// Trying to assign a value of one type to a value of another.
    MismatchedTypes { expected: TypeId, actual: TypeId },
}

impl fmt::Display for Error {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Error::ValueTooLarge => {
                write!(f, "Value could not fit into a single pointer sized word.\nTry constructing a BoxValue instead.")?;
            }
            Error::MismatchedTypes { expected, actual } => {
                writeln!(f, "Trying to assign a value of one type (with TypeId {:?}) to a value of another (with TypeId {:?}).", actual, expected)?;
            }
        }
        Ok(())
    }
}

impl std::error::Error for Error {}

/// Defines a meta struct containing information about a type but not the type itself.
///
/// Note that here V would typically represent a pointer type.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct Meta<V> {
    pub element_size: usize,
    pub element_type_id: TypeId,
    pub vtable: V,
}

impl<'a, B: GetBytesMut, V: Clone + HasDrop> From<&'a Value<B, V>> for Meta<Ptr<V>> {
    #[inline]
    fn from(val: &'a Value<B, V>) -> Meta<Ptr<V>> {
        Meta {
            element_size: val.bytes.get_bytes_ref().len(),
            element_type_id: val.type_id,
            vtable: Ptr::clone(&val.vtable),
        }
    }
}
impl<'a, V: HasDrop> From<ValueRef<'a, V>> for Meta<VTableRef<'a, V>> {
    #[inline]
    fn from(val: ValueRef<'a, V>) -> Meta<VTableRef<'a, V>> {
        Meta {
            element_size: val.bytes.len(),
            element_type_id: val.type_id,
            vtable: val.vtable,
        }
    }
}

impl<'a, V: HasDrop> From<ValueMut<'a, V>> for Meta<VTableRef<'a, V>> {
    #[inline]
    fn from(val: ValueMut<'a, V>) -> Meta<VTableRef<'a, V>> {
        Meta {
            element_size: val.bytes.len(),
            element_type_id: val.type_id,
            vtable: val.vtable,
        }
    }
}

// Implement the basis for all value types.
macro_rules! impl_value_base {
    () => {
        /// Get the size of the value pointed-to by this reference.
        #[inline]
        pub fn size(&self) -> usize {
            self.bytes.get_bytes_ref().len()
        }

        /// Get the `TypeId` of the referenced value.
        #[inline]
        pub fn value_type_id(&self) -> TypeId {
            self.type_id
        }

        /// Returns `true` if this referenced value's type is the same as `T`.
        #[inline]
        pub fn is<T: 'static>(&self) -> bool {
            self.value_type_id() == TypeId::of::<T>()
        }

        // Check that this value represents the given type, and if so return the bytes.
        // This is a helper for downcasts.
        #[inline]
        fn downcast_with<T: 'static, U, F: FnOnce(Self) -> U>(self, f: F) -> Option<U> {
            if self.is::<T>() {
                Some(f(self))
            } else {
                None
            }
        }
    };
}

impl<T: Any> HasDrop for (DropFn, T) {
    #[inline]
    fn drop_fn(&self) -> &DropFn {
        &self.0
    }
}

// The following forwarding impls make it more straightforward to call the Has* methods on the
// (DropFn, V) vtable, although they are not strictly necessary.

impl<V: HasClone> HasClone for (DropFn, V) {
    #[inline]
    fn clone_fn(&self) -> &CloneFn {
        &self.1.clone_fn()
    }
    #[inline]
    fn clone_from_fn(&self) -> &CloneFromFn {
        &self.1.clone_from_fn()
    }
    #[inline]
    fn clone_into_raw_fn(&self) -> &CloneIntoRawFn {
        &self.1.clone_into_raw_fn()
    }
}

impl<V: HasHash> HasHash for (DropFn, V) {
    #[inline]
    fn hash_fn(&self) -> &HashFn {
        &self.1.hash_fn()
    }
}

impl<V: HasPartialEq> HasPartialEq for (DropFn, V) {
    #[inline]
    fn eq_fn(&self) -> &EqFn {
        &self.1.eq_fn()
    }
}

impl<V: HasEq> HasEq for (DropFn, V) {}

impl<V: HasDebug> HasDebug for (DropFn, V) {
    #[inline]
    fn fmt_fn(&self) -> &FmtFn {
        &self.1.fmt_fn()
    }
}

// Helper trait for calling trait functions that take bytes.
pub trait GetBytesRef {
    fn get_bytes_ref(&self) -> &[MaybeUninit<u8>];
}
pub trait GetBytesMut: GetBytesRef {
    fn get_bytes_mut(&mut self) -> &mut [MaybeUninit<u8>];
}

impl GetBytesRef for Box<[MaybeUninit<u8>]> {
    #[inline]
    fn get_bytes_ref(&self) -> &[MaybeUninit<u8>] {
        &*self
    }
}
impl GetBytesMut for Box<[MaybeUninit<u8>]> {
    #[inline]
    fn get_bytes_mut(&mut self) -> &mut [MaybeUninit<u8>] {
        &mut *self
    }
}

impl GetBytesRef for MaybeUninit<usize> {
    #[inline]
    fn get_bytes_ref(&self) -> &[MaybeUninit<u8>] {
        self.as_bytes()
    }
}
impl GetBytesMut for MaybeUninit<usize> {
    #[inline]
    fn get_bytes_mut(&mut self) -> &mut [MaybeUninit<u8>] {
        self.as_bytes_mut()
    }
}

impl GetBytesRef for [MaybeUninit<u8>] {
    #[inline]
    fn get_bytes_ref(&self) -> &[MaybeUninit<u8>] {
        self
    }
}
impl GetBytesMut for [MaybeUninit<u8>] {
    #[inline]
    fn get_bytes_mut(&mut self) -> &mut [MaybeUninit<u8>] {
        self
    }
}

pub struct Value<B, V>
where
    B: GetBytesMut,
    V: ?Sized + HasDrop,
{
    pub(crate) bytes: ManuallyDrop<B>,
    pub(crate) type_id: TypeId,
    pub(crate) vtable: ManuallyDrop<Ptr<V>>,
}

pub type SmallValue<V> = Value<MaybeUninit<usize>, V>;
pub type BoxValue<V> = Value<Box<[MaybeUninit<u8>]>, V>;

impl<V: HasDrop> SmallValue<V> {
    #[inline]
    pub fn try_new<T: Any + DropBytes>(value: T) -> Option<Value<MaybeUninit<usize>, V>>
    where
        V: VTable<T>,
    {
        // Prevent drop of value when it goes out of scope.
        let val = ManuallyDrop::new(value);
        val.try_into_usize().map(|usized_value| Value {
            bytes: ManuallyDrop::new(usized_value),
            type_id: TypeId::of::<T>(),
            vtable: ManuallyDrop::new(Ptr::new(V::build_vtable())),
        })
    }
    /// This function will panic if the given type does not fit into a `usize`.
    #[inline]
    pub fn new<T: Any + DropBytes>(value: T) -> Value<MaybeUninit<usize>, V>
    where
        V: VTable<T>,
    {
        Self::try_new(value).unwrap()
    }
}

impl<V: ?Sized + HasDrop> SmallValue<V> {
    /// Create a new `SmallValue` from a `usize` and an associated `TypeId`.
    ///
    /// # Safety
    ///
    /// The given bytes must be the correct representation of the type given `TypeId`.
    #[inline]
    pub(crate) unsafe fn from_raw_parts(
        bytes: MaybeUninit<usize>,
        type_id: TypeId,
        vtable: Ptr<V>,
    ) -> Value<MaybeUninit<usize>, V> {
        Value {
            bytes: ManuallyDrop::new(bytes),
            type_id,
            vtable: ManuallyDrop::new(vtable),
        }
    }

    #[inline]
    pub fn upcast<U: HasDrop + From<V>>(self) -> SmallValue<U>
    where
        V: Clone,
    {
        // Inhibit drop for self, it will be dropped by the returned value
        let mut md = ManuallyDrop::new(self);
        let output = Value {
            bytes: md.bytes,
            type_id: md.type_id,
            vtable: ManuallyDrop::new(Ptr::new(U::from((**md.vtable).clone()))),
        };

        // Manually drop the old vtable.
        // This is safe since the old vtable will not be used again since self is consumed.
        // It will also not be double dropped since it is cloned above.
        unsafe {
            ManuallyDrop::drop(&mut md.vtable);
        }

        output
    }

    /// Convert this value into its destructured parts.
    ///
    /// The caller must insure that the memory allocated by the returned bytes is freed.
    #[inline]
    pub fn into_raw_parts(self) -> (MaybeUninit<usize>, TypeId, Ptr<V>) {
        // Inhibit drop for self.
        let mut md = ManuallyDrop::new(self);

        // Pass ownership of the vtable and bytes to the caller. This allows the table to be
        // dropped automatically if the caller ignores it, however the data represented by bytes
        // is leaked.
        let vtable = unsafe { ManuallyDrop::take(&mut md.vtable) };
        let bytes = unsafe { ManuallyDrop::take(&mut md.bytes) };

        (bytes, md.type_id, vtable)
    }
}

impl<V: HasDrop> BoxValue<V> {
    #[inline]
    pub fn new<T: Any + DropBytes>(value: T) -> Value<Box<[MaybeUninit<u8>]>, V>
    where
        V: VTable<T>,
    {
        Value {
            bytes: ManuallyDrop::new(Bytes::box_into_box_bytes(Box::new(value))),
            type_id: TypeId::of::<T>(),
            vtable: ManuallyDrop::new(Ptr::new(V::build_vtable())),
        }
    }
}

impl<V: ?Sized + HasDrop> BoxValue<V> {
    /// Create a new `BoxValue` from boxed bytes and an associated `TypeId`.
    ///
    /// # Safety
    ///
    /// The given bytes must be the correct representation of the type given `TypeId`.
    #[inline]
    pub(crate) unsafe fn from_raw_parts(
        bytes: Box<[MaybeUninit<u8>]>,
        type_id: TypeId,
        vtable: Ptr<V>,
    ) -> Value<Box<[MaybeUninit<u8>]>, V> {
        Value {
            bytes: ManuallyDrop::new(bytes),
            type_id,
            vtable: ManuallyDrop::new(vtable),
        }
    }

    #[inline]
    pub fn upcast<U: HasDrop + From<V>>(self) -> BoxValue<U>
    where
        V: Clone,
    {
        // Inhibit drop for self, it will be dropped by the returned value
        let mut md = ManuallyDrop::new(self);
        // It is safe to take the bytes from md since self is consumed and will not be used later.
        let output = Value {
            bytes: ManuallyDrop::new(unsafe { ManuallyDrop::take(&mut md.bytes) }),
            type_id: md.type_id,
            vtable: ManuallyDrop::new(Ptr::new(U::from((**md.vtable).clone()))),
        };

        // Manually drop the old vtable.
        // This is safe since the old vtable will not be used again since self is consumed.
        // It will also not be double dropped since it is cloned above.
        unsafe {
            ManuallyDrop::drop(&mut md.vtable);
        }

        output
    }

    /// Convert this value into its destructured parts.
    ///
    /// The caller must insure that the memory allocated by the returned bytes is freed.
    #[inline]
    pub fn into_raw_parts(self) -> (Box<[MaybeUninit<u8>]>, TypeId, Ptr<V>) {
        // Inhibit drop for self.
        let mut md = ManuallyDrop::new(self);

        // Pass ownership of the vtable and bytes to the caller. This allows the table to be
        // dropped automatically if the caller ignores it, however the data represented by bytes
        // is leaked.
        let vtable = unsafe { ManuallyDrop::take(&mut md.vtable) };
        let bytes = unsafe { ManuallyDrop::take(&mut md.bytes) };

        (bytes, md.type_id, vtable)
    }
}

impl<B: GetBytesMut, V: ?Sized + HasDrop> Value<B, V> {
    #[inline]
    pub fn as_ref(&self) -> ValueRef<V> {
        ValueRef {
            bytes: self.bytes.get_bytes_ref(),
            type_id: self.type_id,
            vtable: VTableRef::Ref(&self.vtable),
        }
    }
    #[inline]
    pub fn as_mut(&mut self) -> ValueMut<V> {
        ValueMut {
            bytes: self.bytes.get_bytes_mut(),
            type_id: self.type_id,
            vtable: VTableRef::Ref(&self.vtable),
        }
    }
}

unsafe impl<B: GetBytesMut, V: ?Sized + HasDrop + HasSend> Send for Value<B, V> {}
unsafe impl<B: GetBytesMut, V: ?Sized + HasDrop + HasSync> Sync for Value<B, V> {}

impl<B: GetBytesMut, V: ?Sized + HasDebug + HasDrop> fmt::Debug for Value<B, V> {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        unsafe { self.vtable.fmt_fn()(self.bytes.get_bytes_ref(), f) }
    }
}

impl<V: ?Sized + Clone + HasClone + HasDrop> Clone for Value<MaybeUninit<usize>, V> {
    #[inline]
    fn clone(&self) -> Value<MaybeUninit<usize>, V> {
        self.as_ref().clone_small_value()
    }
}

impl<V: ?Sized + Clone + HasClone + HasDrop> Clone for Value<Box<[MaybeUninit<u8>]>, V> {
    #[inline]
    fn clone(&self) -> Value<Box<[MaybeUninit<u8>]>, V> {
        self.as_ref().clone_value()
    }
}

impl<B: GetBytesMut, V: ?Sized + HasDrop> Drop for Value<B, V> {
    #[inline]
    fn drop(&mut self) {
        unsafe {
            // This is safe since self will never be used after this call.
            self.vtable.drop_fn()(self.bytes.get_bytes_mut());

            // Manually drop what we promised.
            ManuallyDrop::drop(&mut self.bytes);
            ManuallyDrop::drop(&mut self.vtable);
        }
    }
}

impl<B: GetBytesMut, V: ?Sized + HasDrop + HasPartialEq> PartialEq for Value<B, V> {
    /// # Panics
    ///
    /// This function panics if the types of the two operands don't match.
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        assert_eq!(
            self.type_id, other.type_id,
            "Comparing values of different types is forbidden"
        );
        // This is safe because we have just checked that the two types are the same.
        unsafe { self.vtable.eq_fn()(self.bytes.get_bytes_ref(), other.bytes.get_bytes_ref()) }
    }
}

impl<B: GetBytesMut, V: ?Sized + HasDrop + HasPartialEq> Eq for Value<B, V> {}

impl<B: GetBytesMut, V: ?Sized + HasDrop + HasHash> Hash for Value<B, V> {
    #[inline]
    fn hash<H: Hasher>(&self, state: &mut H) {
        unsafe {
            self.vtable.hash_fn()(self.bytes.get_bytes_ref(), state);
        }
    }
}

/// `VTable` defines a type that represents a virtual function table for some type `T`.
///
/// `T` is different than a type that can be turned into a trait object like `Box<dyn Any>`
/// because a `VTable` effectively decouples the type's behaviour from the data it contains.
///
/// This mechanism allows the virtual function table to be attached to a homogeneous container, to
/// prevent storing duplicates of these tables for each type instance stored in the container.
///
/// This is precisely how it is used to build `VecDyn<V>`, which is generic over the virtual table
/// rather than the type itself.
pub trait VTable<T> {
    fn build_vtable() -> Self;
}

impl<T: Copy> VTable<T> for () {
    #[inline]
    fn build_vtable() -> Self {}
}

impl<T: DropBytes, V: VTable<T>> VTable<T> for (DropFn, V) {
    #[inline]
    fn build_vtable() -> Self {
        (T::drop_bytes, V::build_vtable())
    }
}

impl<B: GetBytesMut, V: ?Sized + HasDrop> Value<B, V> {
    impl_value_base!();
}

impl<V: ?Sized + HasDrop> Value<Box<[MaybeUninit<u8>]>, V> {
    /// Downcast this value reference into a boxed `T` type. Return `None` if the downcast fails.
    #[inline]
    pub fn downcast<T: 'static>(self) -> Option<Box<T>> {
        // Override the Drop implementation, since we don't actually want to drop the contents
        // here, just the vtable.
        let mut s = ManuallyDrop::new(self);
        let output = if s.is::<T>() {
            // This is safe since we check that self.bytes represents a `T`.
            Some(unsafe { Bytes::box_from_box_bytes(ManuallyDrop::take(&mut s.bytes)) })
        } else {
            None
        };
        // We are done with self, dropping the remaining fields here to avoid memory leaks.
        // This is safe since `s` will not be used again.
        unsafe {
            // Note that TypeId is a Copy type and does not need to be manually dropped.
            ManuallyDrop::drop(&mut s.vtable);
        }
        output
    }
}

impl<V: ?Sized + HasDrop> Value<MaybeUninit<usize>, V> {
    /// Downcast this value reference into a boxed `T` type. Return `None` if the downcast fails.
    #[inline]
    pub fn downcast<T: 'static>(self) -> Option<T> {
        // Override the Drop implementation, since we don't actually want to drop the contents
        // here, just the vtable.
        let mut s = ManuallyDrop::new(self);
        // This is safe since we check that self.bytes represent a `T`.
        let output = if s.is::<T>() {
            unsafe { Bytes::try_from_usize(ManuallyDrop::take(&mut s.bytes)) }
        } else {
            None
        };
        // We are done with self, dropping the remaining fields here to avoid memory leaks.
        // This is safe since `s` will not be used again.
        unsafe {
            // Note that TypeId is a Copy type and does not need to be manually dropped.
            ManuallyDrop::drop(&mut s.vtable);
        }
        output
    }
}

/// A VTable reference type.
///
/// Note we always need Drop because it's possible to clone ValueRef's contents, which need to know
/// how to drop themselves.
#[derive(Clone, Debug)]
pub enum VTableRef<'a, V>
where
    V: ?Sized,
{
    Ref(&'a V),
    Box(Box<V>),
    #[cfg(feature = "shared-vtables")]
    Rc(Rc<V>),
}

impl<'a, V: Clone + ?Sized> VTableRef<'a, V> {
    #[inline]
    pub fn take(self) -> V {
        match self {
            VTableRef::Ref(v) => v.clone(),
            VTableRef::Box(v) => *v,
            #[cfg(feature = "shared-vtables")]
            VTableRef::Rc(v) => Rc::try_unwrap(v).unwrap_or_else(|v| (*v).clone()),
        }
    }

    #[inline]
    pub fn into_owned(self) -> Ptr<V> {
        match self {
            VTableRef::Ref(v) => Ptr::new(v.clone()),
            VTableRef::Box(v) => v,
            #[cfg(feature = "shared-vtables")]
            VTableRef::Rc(v) => Rc::clone(&v),
        }
    }
}

impl<'a, V: ?Sized> std::ops::Deref for VTableRef<'a, V> {
    type Target = V;
    #[inline]
    fn deref(&self) -> &Self::Target {
        self.as_ref()
    }
}

impl<'a, V: ?Sized> From<&'a V> for VTableRef<'a, V> {
    #[inline]
    fn from(v: &'a V) -> VTableRef<'a, V> {
        VTableRef::Ref(v)
    }
}

impl<'a, V: ?Sized> From<Box<V>> for VTableRef<'a, V> {
    #[inline]
    fn from(v: Box<V>) -> VTableRef<'a, V> {
        VTableRef::Box(v)
    }
}

#[cfg(feature = "shared-vtables")]
impl<'a, V: ?Sized> From<Ptr<V>> for VTableRef<'a, V> {
    #[inline]
    fn from(v: Ptr<V>) -> VTableRef<'a, V> {
        VTableRef::Rc(v)
    }
}

impl<'a, V: ?Sized> AsRef<V> for VTableRef<'a, V> {
    #[inline]
    fn as_ref(&self) -> &V {
        match self {
            VTableRef::Ref(v) => v,
            VTableRef::Box(v) => &*v,
            #[cfg(feature = "shared-vtables")]
            VTableRef::Rc(v) => &*v,
        }
    }
}

/// A generic value reference into a buffer.
#[derive(Clone)]
pub struct ValueRef<'a, V>
where
    V: ?Sized + HasDrop,
{
    pub(crate) bytes: &'a [MaybeUninit<u8>],
    pub(crate) type_id: TypeId,
    pub(crate) vtable: VTableRef<'a, V>,
}

unsafe impl<'a, V: ?Sized + HasDrop + HasSend> Send for ValueRef<'a, V> {}
unsafe impl<'a, V: ?Sized + HasDrop + HasSync> Sync for ValueRef<'a, V> {}

impl<'a, V: ?Sized + HasHash + HasDrop> Hash for ValueRef<'a, V> {
    #[inline]
    fn hash<H: Hasher>(&self, state: &mut H) {
        unsafe {
            self.vtable.as_ref().hash_fn()(self.bytes.get_bytes_ref(), state);
        }
    }
}

impl<'a, V: ?Sized + HasDebug + HasDrop> fmt::Debug for ValueRef<'a, V> {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        unsafe { self.vtable.as_ref().fmt_fn()(self.bytes.get_bytes_ref(), f) }
    }
}

impl<'a, V: ?Sized + HasPartialEq + HasDrop> PartialEq for ValueRef<'a, V> {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        assert_eq!(
            self.type_id, other.type_id,
            "Comparing values of different types is forbidden"
        );
        // This is safe because we have just checked that the two types are the same.
        unsafe {
            self.vtable.as_ref().eq_fn()(self.bytes.get_bytes_ref(), other.bytes.get_bytes_ref())
        }
    }
}

impl<'a, V: ?Sized + HasEq + HasDrop> Eq for ValueRef<'a, V> {}

impl<'a, V: HasDrop> ValueRef<'a, V> {
    /// Create a new `ValueRef` from a typed reference.
    #[inline]
    pub fn new<T: Any + DropBytes>(typed: &'a T) -> ValueRef<'a, V>
    where
        V: VTable<T>,
    {
        // Reminder: We need DropFn here in case the referenced value is cloned.
        ValueRef {
            bytes: typed.as_bytes(),
            type_id: TypeId::of::<T>(),
            vtable: VTableRef::Box(Box::new(V::build_vtable())),
        }
    }
}

impl<'a, B: GetBytesMut, V> From<&'a Value<B, V>> for ValueRef<'a, V>
where
    B: GetBytesRef,
    V: ?Sized + Clone + HasDrop,
{
    fn from(val: &'a Value<B, V>) -> Self {
        ValueRef {
            bytes: val.bytes.get_bytes_ref(),
            type_id: val.type_id,
            vtable: Ptr::clone(&val.vtable).into(),
        }
    }
}

impl<'a, V: ?Sized + HasDrop> ValueRef<'a, V> {
    impl_value_base!();

    /// Create a new `ValueRef` from a slice of bytes and an associated `TypeId`.
    ///
    /// # Safety
    ///
    /// The given bytes must be the correct representation of the type given `TypeId`.
    #[inline]
    pub(crate) unsafe fn from_raw_parts(
        bytes: &'a [MaybeUninit<u8>],
        type_id: TypeId,
        vtable: impl Into<VTableRef<'a, V>>,
    ) -> ValueRef<'a, V> {
        ValueRef {
            bytes,
            type_id,
            vtable: vtable.into(),
        }
    }

    /// Clone the referenced value.
    ///
    /// Unlike the `Clone` trait, this function will produce an owned clone of the value pointed to
    /// by this value reference.
    #[inline]
    pub fn clone_value(&self) -> Value<Box<[MaybeUninit<u8>]>, V>
    where
        V: HasClone + Clone,
    {
        Value {
            bytes: ManuallyDrop::new(unsafe { self.vtable.as_ref().clone_fn()(&self.bytes) }),
            type_id: self.type_id,
            vtable: ManuallyDrop::new(Ptr::from(self.vtable.as_ref().clone())),
        }
    }

    /// Clone the referenced value.
    ///
    /// Unlike the `Clone` trait, this function will produce an owned clone of the value pointed to
    /// by this value reference.
    ///
    /// This version of `clone_value` tries to fit the underlying value into a `usize` sized value,
    /// and panics if that fails.
    #[inline]
    pub fn clone_small_value(&self) -> Value<MaybeUninit<usize>, V>
    where
        V: HasClone + Clone,
    {
        let mut bytes = MaybeUninit::uninit();
        // This is safe because clone_into_raw_fn will not attempt to drop the value at the
        // destination.
        unsafe {
            self.vtable.clone_into_raw_fn()(self.bytes.get_bytes_ref(), bytes.as_bytes_mut());
        }
        Value {
            bytes: ManuallyDrop::new(bytes),
            type_id: self.type_id,
            vtable: ManuallyDrop::new(Ptr::from(self.vtable.as_ref().clone())),
        }
    }

    /// Downcast this value reference into a borrowed `T` type. Return `None` if the downcast fails.
    #[inline]
    pub fn downcast<T: 'static>(self) -> Option<&'a T> {
        // This is safe since we check that self.bytes represent a `T`.
        self.downcast_with::<T, _, _>(|b| unsafe { Bytes::from_bytes(b.bytes) })
    }

    #[inline]
    pub fn upcast<U: ?Sized + HasDrop + From<V>>(self) -> ValueRef<'a, U>
    where
        V: Clone,
    {
        ValueRef {
            bytes: self.bytes,
            type_id: self.type_id,
            vtable: VTableRef::Box(Box::new(U::from(self.vtable.take()))),
        }
    }

    #[inline]
    pub fn upcast_ref<U: ?Sized + HasDrop + From<V>>(&self) -> ValueRef<U>
    where
        V: Clone,
    {
        let vtable = self.vtable.as_ref();
        ValueRef {
            bytes: self.bytes,
            type_id: self.type_id,
            vtable: VTableRef::Box(Box::new(U::from((*vtable).clone()))),
        }
    }

    /// An alternative to `Clone` that doesn't require cloning the vtable.
    #[inline]
    pub fn reborrow(&self) -> ValueRef<V> {
        ValueRef {
            bytes: &*self.bytes,
            type_id: self.type_id,
            vtable: VTableRef::Ref(self.vtable.as_ref()),
        }
    }
}

/// A generic mutable value reference into a buffer.
pub struct ValueMut<'a, V>
where
    V: ?Sized + HasDrop,
{
    pub(crate) bytes: &'a mut [MaybeUninit<u8>],
    pub(crate) type_id: TypeId,
    pub(crate) vtable: VTableRef<'a, V>,
}

impl<'a, V: ?Sized + HasDebug + HasDrop> fmt::Debug for ValueMut<'a, V> {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        unsafe { self.vtable.as_ref().fmt_fn()(self.bytes, f) }
    }
}

impl<'a, V: ?Sized + HasPartialEq + HasDrop> PartialEq for ValueMut<'a, V> {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        assert_eq!(
            self.type_id, other.type_id,
            "Comparing values of different types is forbidden"
        );
        // This is safe because we have just checked that the two types are the same.
        unsafe {
            self.vtable.as_ref().eq_fn()(self.bytes.get_bytes_ref(), other.bytes.get_bytes_ref())
        }
    }
}

impl<'a, V: ?Sized + HasEq + HasDrop> Eq for ValueMut<'a, V> {}

impl<'a, V: HasDrop> ValueMut<'a, V> {
    /// Create a new `ValueRef` from a typed reference.
    #[inline]
    pub fn new<T: Any>(typed: &'a mut T) -> ValueMut<'a, V>
    where
        V: VTable<T>,
    {
        ValueMut {
            bytes: typed.as_bytes_mut(),
            type_id: TypeId::of::<T>(),
            vtable: VTableRef::Box(Box::new(V::build_vtable())),
        }
    }
}

impl<'a, V: ?Sized + HasDrop> ValueMut<'a, V> {
    impl_value_base!();

    /// Swap the values between `other` and `self`.
    #[inline]
    pub fn swap<'b>(&mut self, other: &mut ValueMut<'b, V>) {
        if self.value_type_id() == other.value_type_id() {
            self.bytes.swap_with_slice(other.bytes);
        }
    }

    /// Moves the given value into self.
    pub fn assign<B: GetBytesMut>(&mut self, mut value: Value<B, V>) {
        // Swapping the values ensures that `value` will not be dropped, but the overwritten value
        // in self will.
        self.swap(&mut value.as_mut())
    }

    /// Clone `other` into `self`.
    ///
    /// This function will call `drop` on any values stored in `self`.
    #[inline]
    pub fn clone_from_other<'b>(&mut self, other: impl Into<ValueRef<'b, V>>) -> Result<(), Error>
    where
        V: HasClone + 'b,
    {
        let other = other.into();
        if self.value_type_id() == other.value_type_id() {
            unsafe {
                // We are cloning other.bytes into self.bytes.
                // This function will call the appropriate typed clone_from function, which will
                // automatically drop the previous value of self.bytes, so no manual drop call is
                // needed here.
                self.vtable.as_ref().clone_from_fn()(&mut self.bytes, other.bytes);
            }
            Ok(())
        } else {
            Err(Error::MismatchedTypes {
                expected: self.value_type_id(),
                actual: other.value_type_id(),
            })
        }
    }

    /// Clone the referenced value.
    ///
    /// Unlike the `Clone` trait, this function will produce an owned clone of the value pointed to
    /// by this value reference.
    #[inline]
    pub fn clone_value(&self) -> Value<Box<[MaybeUninit<u8>]>, V>
    where
        V: HasClone + Clone,
    {
        Value {
            bytes: ManuallyDrop::new(unsafe { self.vtable.as_ref().clone_fn()(&self.bytes) }),
            type_id: self.type_id,
            vtable: ManuallyDrop::new(Ptr::from(self.vtable.as_ref().clone())),
        }
    }

    /// Clone the referenced value.
    ///
    /// Unlike the `Clone` trait, this function will produce an owned clone of the value pointed to
    /// by this value reference.
    ///
    /// This version of `clone_value` tries to fit the underlying value into a `usize` sized value,
    /// and panics if that fails.
    #[inline]
    pub fn clone_small_value(&self) -> Value<MaybeUninit<usize>, V>
    where
        V: HasClone + Clone,
    {
        let mut bytes = MaybeUninit::uninit();
        // This is safe because clone_into_raw_fn will not attempt to drop the value at the
        // destination.
        unsafe {
            self.vtable.clone_into_raw_fn()(self.bytes.get_bytes_ref(), bytes.as_bytes_mut());
        }
        Value {
            bytes: ManuallyDrop::new(bytes),
            type_id: self.type_id,
            vtable: ManuallyDrop::new(Ptr::from(self.vtable.as_ref().clone())),
        }
    }

    /// Create a new `ValueMut` from a slice of bytes and an associated `TypeId`.
    ///
    /// # Safety
    ///
    /// The given bytes must be the correct representation of the type given `TypeId`.
    #[inline]
    pub(crate) unsafe fn from_raw_parts(
        bytes: &'a mut [MaybeUninit<u8>],
        type_id: TypeId,
        vtable: impl Into<VTableRef<'a, V>>,
    ) -> ValueMut<'a, V> {
        ValueMut {
            bytes,
            type_id,
            vtable: vtable.into(),
        }
    }

    /// Downcast this value reference into a borrowed `T` type. Return `None` if the downcast fails.
    #[inline]
    pub fn downcast<T: 'static>(self) -> Option<&'a mut T> {
        // This is safe since we check that self.bytes represent a `T`.
        self.downcast_with::<T, _, _>(|b| unsafe { Bytes::from_bytes_mut(b.bytes) })
    }

    /// A consuming upcast that carries the lifetime of the underlying value reference.
    #[inline]
    pub fn upcast<U: ?Sized + HasDrop + From<V>>(self) -> ValueMut<'a, U>
    where
        V: Clone,
    {
        ValueMut {
            bytes: self.bytes,
            type_id: self.type_id,
            vtable: VTableRef::Box(Box::new(U::from(self.vtable.take()))),
        }
    }

    /// Create a new mutable value reference upcast from the current one.
    #[inline]
    pub fn upcast_mut<U: ?Sized + HasDrop + From<V>>(&mut self) -> ValueMut<U>
    where
        V: Clone,
    {
        ValueMut {
            bytes: self.bytes,
            type_id: self.type_id,
            vtable: VTableRef::Box(Box::new(U::from((*self.vtable).clone()))),
        }
    }

    #[inline]
    pub fn reborrow(&self) -> ValueRef<V> {
        ValueRef {
            bytes: self.bytes,
            type_id: self.type_id,
            vtable: VTableRef::Ref(self.vtable.as_ref()),
        }
    }

    #[inline]
    pub fn reborrow_mut(&mut self) -> ValueMut<V> {
        ValueMut {
            bytes: self.bytes,
            type_id: self.type_id,
            vtable: VTableRef::Ref(self.vtable.as_ref()),
        }
    }
}

/// A generic value reference to a `Copy` type.
#[derive(Clone, Debug)]
pub struct CopyValueRef<'a, V = ()>
where
    V: ?Sized,
{
    pub(crate) bytes: &'a [MaybeUninit<u8>],
    pub(crate) type_id: TypeId,
    pub(crate) vtable: VTableRef<'a, V>,
}

impl<'a, V> CopyValueRef<'a, V> {
    /// Create a new `CopyValueRef` from a typed reference.
    #[inline]
    pub fn new<T: Elem>(typed: &'a T) -> CopyValueRef<'a, V>
    where
        V: VTable<T>,
    {
        CopyValueRef {
            bytes: typed.as_bytes(),
            type_id: TypeId::of::<T>(),
            vtable: VTableRef::Box(Box::new(V::build_vtable())),
        }
    }
}

impl<'a, V: ?Sized> CopyValueRef<'a, V> {
    impl_value_base!();

    /// Create a new `CopyValueref` from a slice of bytes and an associated `TypeId`.
    ///
    /// # Safety
    ///
    /// The given bytes must be the correct representation of the type given `TypeId`.
    #[inline]
    pub(crate) unsafe fn from_raw_parts(
        bytes: &'a [MaybeUninit<u8>],
        type_id: TypeId,
        vtable: impl Into<VTableRef<'a, V>>,
    ) -> CopyValueRef<'a, V> {
        CopyValueRef {
            bytes,
            type_id,
            vtable: vtable.into(),
        }
    }

    /// Downcast this value reference into a borrowed `T` type. Return `None` if the downcast fails.
    #[inline]
    pub fn downcast<T: Elem>(self) -> Option<&'a T> {
        // This is safe since we check that self.bytes represent a `T`.
        self.downcast_with::<T, _, _>(|b| unsafe { Bytes::from_bytes(b.bytes) })
    }

    #[inline]
    pub fn upcast<U: ?Sized + From<V>>(self) -> CopyValueRef<'a, U>
    where
        V: Clone,
    {
        CopyValueRef {
            bytes: self.bytes,
            type_id: self.type_id,
            vtable: VTableRef::Box(Box::new(U::from(self.vtable.take()))),
        }
    }

    #[inline]
    pub fn upcast_ref<U: ?Sized + From<V>>(&self) -> CopyValueRef<U>
    where
        V: Clone,
    {
        let vtable = self.vtable.as_ref();
        CopyValueRef {
            bytes: self.bytes,
            type_id: self.type_id,
            vtable: VTableRef::Box(Box::new(U::from((*vtable).clone()))),
        }
    }
}

/// A generic mutable `Copy` value reference.
#[derive(Debug)]
pub struct CopyValueMut<'a, V = ()>
where
    V: ?Sized,
{
    pub(crate) bytes: &'a mut [MaybeUninit<u8>],
    pub(crate) type_id: TypeId,
    pub(crate) vtable: VTableRef<'a, V>,
}

impl<'a, V> CopyValueMut<'a, V> {
    /// Create a new `CopyValueMut` from a typed mutable reference.
    #[inline]
    pub fn new<T: Elem>(typed: &'a mut T) -> CopyValueMut<'a, V>
    where
        V: VTable<T>,
    {
        CopyValueMut {
            bytes: typed.as_bytes_mut(),
            type_id: TypeId::of::<T>(),
            vtable: VTableRef::Box(Box::new(V::build_vtable())),
        }
    }
}

impl<'a, V: ?Sized> CopyValueMut<'a, V> {
    impl_value_base!();

    /// Create a new `CopyValueMut` from a slice of bytes and an associated `TypeId`.
    ///
    /// # Safety
    ///
    /// The given bytes must be the correct representation of the type given `TypeId`.
    #[inline]
    pub(crate) unsafe fn from_raw_parts(
        bytes: &'a mut [MaybeUninit<u8>],
        type_id: TypeId,
        vtable: impl Into<VTableRef<'a, V>>,
    ) -> CopyValueMut<'a, V> {
        CopyValueMut {
            bytes,
            type_id,
            vtable: vtable.into(),
        }
    }

    /// Copy value from `other` to `self` and return `Self`.
    ///
    /// This function returns `None` if the values have different types.
    #[inline]
    pub fn copy(self, other: CopyValueRef<'a, V>) -> Option<Self> {
        if self.value_type_id() == other.value_type_id() {
            self.bytes.copy_from_slice(other.bytes);
            Some(self)
        } else {
            None
        }
    }

    /// Swap the values between `other` and `self`.
    #[inline]
    pub fn swap(&mut self, other: &mut CopyValueMut<V>) {
        if self.value_type_id() == other.value_type_id() {
            self.bytes.swap_with_slice(&mut other.bytes);
            std::mem::swap(&mut self.type_id, &mut other.type_id);
        }
    }

    /// Downcast this value reference into a borrowed `T` type. Return `None` if the downcast fails.
    #[inline]
    pub fn downcast<T: Elem>(self) -> Option<&'a mut T> {
        // This is safe since we check that self.bytes represent a `T`.
        self.downcast_with::<T, _, _>(|b| unsafe { Bytes::from_bytes_mut(b.bytes) })
    }

    #[inline]
    pub fn upcast<U: From<V>>(&mut self) -> CopyValueMut<U>
    where
        V: Clone,
    {
        let vtable = self.vtable.as_ref();
        CopyValueMut {
            bytes: self.bytes,
            type_id: self.type_id,
            vtable: VTableRef::Box(Box::new(U::from(vtable.clone()))),
        }
    }
}

/*
 * Valid conversions.
 */

impl<'a, V: HasDrop> From<ValueMut<'a, V>> for ValueRef<'a, V> {
    #[inline]
    fn from(v: ValueMut<'a, V>) -> ValueRef<'a, V> {
        ValueRef {
            bytes: v.bytes,
            type_id: v.type_id,
            vtable: v.vtable,
        }
    }
}

impl<'a, V: HasDrop> From<CopyValueMut<'a, V>> for CopyValueRef<'a, V> {
    #[inline]
    fn from(v: CopyValueMut<'a, V>) -> CopyValueRef<'a, V> {
        CopyValueRef {
            bytes: v.bytes,
            type_id: v.type_id,
            vtable: v.vtable,
        }
    }
}

/// Implementation for dropping a copy.
///
/// This enables the following two conversions.
unsafe fn drop_copy(_: &mut [MaybeUninit<u8>]) {}

impl<'a, V: Any + Clone> From<CopyValueMut<'a, V>> for ValueMut<'a, (DropFn, V)> {
    #[inline]
    fn from(v: CopyValueMut<'a, V>) -> ValueMut<'a, (DropFn, V)> {
        ValueMut {
            bytes: v.bytes,
            type_id: v.type_id,
            vtable: VTableRef::Box(Box::new((drop_copy, v.vtable.take()))),
        }
    }
}

impl<'a, V: Any + Clone> From<CopyValueRef<'a, V>> for ValueRef<'a, (DropFn, V)> {
    #[inline]
    fn from(v: CopyValueRef<'a, V>) -> ValueRef<'a, (DropFn, V)> {
        ValueRef {
            bytes: v.bytes,
            type_id: v.type_id,
            vtable: VTableRef::Box(Box::new((drop_copy, v.vtable.take()))),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::dync_trait;
    use std::rc::Rc;

    #[dync_trait(dync_crate_name = "crate")]
    pub trait Val: Clone + PartialEq + Eq + std::hash::Hash + std::fmt::Debug + 'static {}
    impl<T> Val for T where T: Clone + PartialEq + Eq + std::hash::Hash + std::fmt::Debug + 'static {}

    #[test]
    #[should_panic]
    fn forbidden_value_compare() {
        let a = BoxValue::<ValVTable>::new(Rc::new("Hello"));
        let b = BoxValue::<ValVTable>::new(Rc::new(String::from("Hello")));
        assert_eq!(a, b);
    }

    #[test]
    #[should_panic]
    fn forbidden_value_ref_compare() {
        let a = BoxValue::<ValVTable>::new(Rc::new("Hello"));
        let b = BoxValue::<ValVTable>::new(Rc::new(String::from("Hello")));
        assert_eq!(a.as_ref(), b.as_ref());
    }

    #[test]
    #[should_panic]
    fn forbidden_value_mut_compare() {
        let mut a = BoxValue::<ValVTable>::new(Rc::new("Hello"));
        let mut b = BoxValue::<ValVTable>::new(Rc::new(String::from("Hello")));
        assert_eq!(a.as_mut(), b.as_mut());
    }

    #[test]
    fn value_equality() {
        let a = Rc::new(String::from("Hello"));
        let b = Rc::new(String::from("Hello"));
        assert_eq!(&a, &b);

        let a = BoxValue::<ValVTable>::new(Rc::new(String::from("Hello")));
        let b = BoxValue::<ValVTable>::new(Rc::new(String::from("Hello")));
        let c = b.clone();
        let c_rc = b.clone().downcast::<Rc<String>>().unwrap();
        let d = BoxValue::<ValVTable>::new(Rc::clone(&*c_rc));
        assert_eq!(&a, &b);
        assert_eq!(&a, &c);
        assert_eq!(&a, &d);
    }

    // This test checks that cloning and dropping clones works correctly.
    #[test]
    fn clone_test() {
        let val = BoxValue::<ValVTable>::new(Rc::new(1u8));
        assert_eq!(&val, &val.clone());
    }

    // This test checks that cloning and dropping clones works correctly.
    #[test]
    fn clone_small_test() {
        let val = SmallValue::<ValVTable>::new(Rc::new(1u8));
        assert_eq!(&val, &val.clone());
    }
}

/*
 * TESTING
 */

/*
#[derive(Clone, Debug)]
pub(crate) enum VTableRef2<'a, V> {
    Ref(&'a V),
    Box(Box<V>),
    Rc(Rc<V>),
}

impl<'a, V> From<&'a V> for VTableRef2<'a, V> {
    #[inline]
    fn from(v: &'a V) -> VTableRef2<'a, V> {
        VTableRef2::Ref(v)
    }
}

impl<'a, V> From<Box<V>> for VTableRef2<'a, V> {
    #[inline]
    fn from(v: Box<V>) -> VTableRef2<'a, V> {
        VTableRef2::Box(v)
    }
}

impl<'a, V> AsRef<V> for VTableRef2<'a, V> {
    #[inline]
    fn as_ref(&self) -> &V {
        match self {
            VTableRef2::Ref(v) => v,
            VTableRef2::Box(v) => &*v,
            VTableRef2::Rc(_) => unreachable!(),//&*v,
        }
    }
}
#[derive(Debug)]
pub struct CopyValueMutTest<'a, V> {
    pub(crate) bytes: &'a mut [u8],
    pub(crate) type_id: TypeId,
    pub(crate) vtable: VTableRef2<'a, V>,
}

impl<'a, V> CopyValueMutTest<'a, V> {
    impl_value_base!();

    /// Create a new `CopyValueMutTest` from a slice of bytes and an associated `TypeId`.
    ///
    /// # Safety
    ///
    /// The given bytes must be the correct representation of the type given `TypeId`.
    #[inline]
    pub(crate) unsafe fn from_raw_parts(bytes: &'a mut [u8], type_id: TypeId, vtable: impl Into<VTableRef2<'a, V>>) -> CopyValueMutTest<'a, V> {
        CopyValueMutTest { bytes, type_id, vtable: vtable.into() }
    }

    /// Downcast this value reference into a borrowed `T` type. Return `None` if the downcast fails.
    #[inline]
    pub fn downcast<T: Elem>(self) -> Option<&'a mut T> {
        // This is safe since we check that self.bytes represent a `T`.
        self.downcast_with::<T, _, _>(|b| unsafe { Bytes::from_bytes_mut(b.bytes) })
    }
}
*/