Skip to main content

get_size2/
lib.rs

1#![doc = include_str!("./lib.md")]
2#![cfg_attr(docsrs, feature(doc_cfg))]
3
4#[cfg(feature = "derive")]
5#[cfg_attr(docsrs, doc(cfg(feature = "derive")))]
6pub use get_size_derive2::*;
7
8mod impls;
9mod tracker;
10pub use tracker::*;
11#[cfg(test)]
12mod test;
13
14/// Determines how many bytes the object occupies inside the heap.
15pub fn heap_size<T: GetSize>(value: &T) -> usize {
16    value.get_heap_size()
17}
18
19/// Determine the size in bytes an object occupies inside RAM.
20pub trait GetSize: Sized {
21    /// Determines how may bytes this object occupies inside the stack.
22    ///
23    /// The default implementation uses [`std::mem::size_of`] and should work for almost all types.
24    #[must_use]
25    fn get_stack_size() -> usize {
26        std::mem::size_of::<Self>()
27    }
28
29    /// Determines how many bytes this object occupies inside the heap.
30    ///
31    /// The default implementation simply delegates to [`get_heap_size_with_tracker`](Self::get_heap_size_with_tracker)
32    /// with a noop tracker. This method is not meant to be implemented directly, and only exists for convenience.
33    fn get_heap_size(&self) -> usize {
34        let tracker = NoTracker::new(true);
35        Self::get_heap_size_with_tracker(self, tracker).0
36    }
37
38    /// Determines how many bytes this object occupies inside the heap while using a `tracker`.
39    ///
40    /// The default implementation returns 0, assuming the object is fully allocated on the stack.
41    /// It must be adjusted as appropriate for objects which hold data inside the heap.
42    fn get_heap_size_with_tracker<T: GetSizeTracker>(&self, tracker: T) -> (usize, T) {
43        (0, tracker)
44    }
45
46    /// Determines the total size of the object.
47    ///
48    /// The default implementation simply adds up the results of [`get_stack_size`](Self::get_stack_size)
49    /// and [`get_heap_size`](Self::get_heap_size) and is not meant to be changed.
50    fn get_size(&self) -> usize {
51        Self::get_stack_size() + GetSize::get_heap_size(self)
52    }
53
54    /// Determines the total size of the object while using a `tracker`.
55    ///
56    /// The default implementation simply adds up the results of [`get_stack_size`](Self::get_stack_size)
57    /// and [`get_heap_size_with_tracker`](Self::get_heap_size_with_tracker) and is not meant to
58    /// be changed.
59    fn get_size_with_tracker<T: GetSizeTracker>(&self, tracker: T) -> (usize, T) {
60        let stack_size = Self::get_stack_size();
61        let (heap_size, tracker) = Self::get_heap_size_with_tracker(self, tracker);
62        (stack_size + heap_size, tracker)
63    }
64}