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
// 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;

/// `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 {}
}

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

/// 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, PartialEq)]
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,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn box_vtable() {
        let v = Box::new(());
        let from_box = VTableRef::from(v.clone());
        let box_vtable = VTableRef::Box(v);
        assert_eq!(&from_box, &box_vtable);

        assert_eq!(from_box.into_owned(), Box::new(()));
        assert_eq!(box_vtable.take(), ());
    }
}