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
#![doc = include_str!("../README.md")]

use std::sync::atomic::{AtomicBool, AtomicI8, AtomicI16, AtomicI32, AtomicI64, AtomicIsize,
    AtomicU8, AtomicU16, AtomicU32, AtomicU64, AtomicUsize};

#[cfg(feature = "aligned-vec")] use aligned_vec;

/// Provides methods to get dynamic and total size of the variable.
pub trait GetSize {
    /// Returns approximate number of bytes occupied by dynamic (heap) part of `self`.
    /// Same as `self.size_bytes() - std::mem::size_of_val(self)`.
    #[inline] fn size_bytes_dyn(&self) -> usize { 0 }

    /// Returns approximate number of bytes occupied by dynamic (heap) part of `self` content.
    /// It usually equals to `size_bytes_dyn()`.
    /// However, sometimes it is smaller by the amount of memory reserved but not yet used
    /// (e.g., `size_bytes_content_dyn()` only takes into account the length of the vector and not its capacity).
    #[inline] fn size_bytes_content_dyn(&self) -> usize { self.size_bytes_dyn() }

    /// Returns approximate, total (including heap memory) number of bytes occupied by `self`.
    #[inline] fn size_bytes(&self) -> usize {
        std::mem::size_of_val(self) + self.size_bytes_dyn()
    }

    /// `true` if and only if the variables of this type can use dynamic (heap) memory.
    const USES_DYN_MEM: bool = false;
}

/// Implement GetSize for one or more types that do not use heap memory.
macro_rules! impl_nodyn_getsize_for {
    ($x:ty) => (impl self::GetSize for $x {});
    // `$x` followed by at least one `$y,`
    ($x:ty, $($y:ty),+) => (
        impl self::GetSize for $x {}
        impl_nodyn_getsize_for!($($y),+);
    )
}

impl_nodyn_getsize_for!(u8, u16, u32, u64, u128, usize,
    AtomicU8, AtomicU16, AtomicU32, AtomicU64, AtomicUsize,
    bool, AtomicBool,
    i8, i16, i32, i64, i128, isize,
    AtomicI8, AtomicI16, AtomicI32, AtomicI64, AtomicIsize,
    f32, f64, char, ());

//impl<T: GetSize> GetSize for [T] {    // this works also with slices, but is this sound?
impl<T: GetSize, const N: usize> GetSize for [T; N] {
    fn size_bytes_dyn(&self) -> usize {
        if T::USES_DYN_MEM {
            self.iter().map(self::GetSize::size_bytes_dyn).sum()
        } else {
            0
        }
    }
    fn size_bytes_content_dyn(&self) -> usize {
        if T::USES_DYN_MEM {
            self.iter().map(self::GetSize::size_bytes_content_dyn).sum()
        } else {
            0
        }
    }
    const USES_DYN_MEM: bool = T::USES_DYN_MEM;
}

macro_rules! impl_getsize_methods_for_pointer {
    () => (
        fn size_bytes_dyn(&self) -> ::std::primitive::usize {
            ::std::ops::Deref::deref(self).size_bytes()
        }
        const USES_DYN_MEM: bool = true;
    );
}

impl <T: GetSize> GetSize for Box<T> {
    impl_getsize_methods_for_pointer!();
}

#[cfg(feature = "aligned-vec")] impl <T: GetSize> GetSize for aligned_vec::ABox<T> {
    impl_getsize_methods_for_pointer!();
}

impl <T: GetSize> GetSize for ::std::rc::Rc<T> {
    fn size_bytes_dyn(&self) -> ::std::primitive::usize {
        // round((size of T + size of strong and weak reference counters) / number of strong references)
        let c = ::std::rc::Rc::strong_count(self);
        (::std::ops::Deref::deref(self).size_bytes() + 2*::std::mem::size_of::<usize>() + c/2) / c
    }
    const USES_DYN_MEM: bool = true;
}

macro_rules! impl_getsize_methods_for_dyn_arr {
    ($T:ty) => (
        fn size_bytes_dyn(&self) -> ::std::primitive::usize {
            if <$T>::USES_DYN_MEM {
                self.iter().map(self::GetSize::size_bytes).sum()
            } else {
                ::std::mem::size_of::<$T>() * self.len()
            }
        }
        const USES_DYN_MEM: bool = true;
    );
}

impl<T: GetSize> GetSize for Box<[T]> {
    impl_getsize_methods_for_dyn_arr!(T);
}

#[cfg(feature = "aligned-vec")] impl <T: GetSize> GetSize for aligned_vec::ABox<[T]> {
    impl_getsize_methods_for_dyn_arr!(T);
}

macro_rules! impl_getsize_methods_for_vec {
    ($T:ty) => (
        fn size_bytes_dyn(&self) -> usize {
            let c = ::std::mem::size_of::<$T>() * self.capacity();
            if <$T>::USES_DYN_MEM {
                c + self.iter().map(GetSize::size_bytes_dyn).sum::<usize>()
            } else {
                c
            }
        }
        fn size_bytes_content_dyn(&self) -> usize {
            let c = ::std::mem::size_of::<$T>() * self.len();
            if <$T>::USES_DYN_MEM {
                c + self.iter().map(GetSize::size_bytes_content_dyn).sum::<usize>()
            } else {
                c
            }
        }
        const USES_DYN_MEM: bool = true;
    );
}

impl<T: GetSize> GetSize for Vec<T> {
    impl_getsize_methods_for_vec!(T);
}

#[cfg(feature = "aligned-vec")] impl <T: GetSize> GetSize for aligned_vec::AVec<T> {
    impl_getsize_methods_for_vec!(T);
}

macro_rules! impl_getsize_for_tuple {
    ($( $T:ident ),+) => {
        impl<$( $T: self::GetSize ),+> self::GetSize for ($( $T, )+) {
            #[allow(non_snake_case)]
            fn size_bytes_dyn(&self) -> ::std::primitive::usize {
                let &($( ref $T, )+) = self;
                0 $( + $T.size_bytes_dyn() )+
            }
            #[allow(non_snake_case)]
            fn size_bytes_content_dyn(&self) -> ::std::primitive::usize {
                let &($( ref $T, )+) = self;
                0 $( + $T.size_bytes_content_dyn() )+
            }
            const USES_DYN_MEM: bool = $( $T::USES_DYN_MEM )|*;
        }
    }
}

impl_getsize_for_tuple!(A);
impl_getsize_for_tuple!(A, B);
impl_getsize_for_tuple!(A, B, C);
impl_getsize_for_tuple!(A, B, C, D);
impl_getsize_for_tuple!(A, B, C, D, E);
impl_getsize_for_tuple!(A, B, C, D, E, F);
impl_getsize_for_tuple!(A, B, C, D, E, F, G);
impl_getsize_for_tuple!(A, B, C, D, E, F, G, H);
impl_getsize_for_tuple!(A, B, C, D, E, F, G, H, I);
impl_getsize_for_tuple!(A, B, C, D, E, F, G, H, I, J);



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

    fn test_primitive<T: GetSize>(v: T) {
        assert_eq!(v.size_bytes_dyn(), 0);
        assert_eq!(v.size_bytes_content_dyn(), 0);
        assert_eq!(v.size_bytes(), std::mem::size_of_val(&v));
        assert!(!T::USES_DYN_MEM);
    }

    #[test]
    fn test_primitives() {
        test_primitive(1u32);
        test_primitive(1.0f32);
    }

    #[test]
    fn test_array() {
        assert_eq!([1u32, 2u32, 3u32].size_bytes(), 3*4);
        assert_eq!([[1u32, 2u32], [3u32, 4u32]].size_bytes(), 4*4);
        assert_eq!([vec![1u32, 2u32], vec![3u32, 4u32]].size_bytes_content_dyn(), 4*4);
    }

    #[test]
    fn test_vec() {
        assert_eq!(vec![1u32, 2u32, 3u32].size_bytes_content_dyn(), 3*4);
        assert_eq!(vec![[1u32, 2u32], [3u32, 4u32]].size_bytes_content_dyn(), 4*4);
        let v = vec![1u32, 2u32];
        assert_eq!(vec![v.clone(), v.clone()].size_bytes_dyn(), 2*v.size_bytes());
        assert_eq!(Vec::<u32>::with_capacity(3).size_bytes_dyn(), 3*4);
        assert_eq!(Vec::<u32>::with_capacity(3).size_bytes_content_dyn(), 0);
    }

    #[test]
    fn test_boxed_slice() {
        let bs = vec![1u32, 2u32, 3u32].into_boxed_slice();
        assert_eq!(bs.size_bytes_dyn(), 3*4);
        assert_eq!(bs.size_bytes(), 3*4 + std::mem::size_of_val(&bs));
    }

    #[test]
    fn test_tuple() {
        assert_eq!((1u32, 2u32).size_bytes_dyn(), 0);
        assert_eq!((1u32, vec![3u32, 4u32]).size_bytes_dyn(), 2*4);
        assert_eq!((vec![1u32, 2u32], vec![3u32, 4u32]).size_bytes_dyn(), 4*4);
    }

    #[test]
    #[allow(unused_allocation)]
    fn test_box() {
        assert_eq!(Box::new(1u32).size_bytes_dyn(), 4);
        assert_eq!(Box::new([1u32, 2u32]).size_bytes_dyn(), 2*4);
    }
}