memuse 0.2.2

Traits for measuring dynamic memory usage of 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
//! Measure dynamic memory usage of your types!
//!
//! ## About
//!
//! Memory-tracking is a common activity in large applications, particularly ones
//! that receive data from a network and store it in memory. By monitoring how much
//! memory is used by different areas of the application, memory pressure can be
//! alleviated by ignoring new packets, or implementing random drop logic for DoS
//! mitigation.
//!
//! Measuring memory use on the stack is easy, with [`std::mem::size_of`] and
//! friends. Measuring memory allocated on the heap is more tricky. Applications can
//! use a custom global allocator to track the memory usage of different areas. This
//! isn't an option for reusable library code however, and the nearest alternative
//! (using custom allocators for individual types) is currently only an experimental
//! feature in nightly Rust ([`allocator_api`]).
//!
//! [`allocator_api`]: https://github.com/rust-lang/rust/issues/32838
//!
//! This crate takes a different approach: it provides traits that library authors
//! can use to expose dynamic memory usage information on their types. By composing
//! these implementations, we gain the ability to query the amount of heap-allocated
//! memory in use by specific instances of types at any point in time, without any
//! changes to the way in which these types are constructed.
//!
//! ## Minimum Supported Rust Version
//!
//! Requires Rust **1.51** or newer.
//!
//! In the future, we reserve the right to change MSRV (i.e. MSRV is out-of-scope for this
//! crate's SemVer guarantees), however when we do it will be accompanied by a minor
//! version bump.
//!
//! ## Usage
//!
//! ```
//! # #[cfg(feature = "std")]
//! # {
//! # use std::collections::HashMap;
//! use memuse::DynamicUsage;
//!
//! // Simple types don't allocate memory on the heap.
//! assert_eq!(7u64.dynamic_usage(), 0);
//! assert_eq!("I'm simple!".dynamic_usage(), 0);
//!
//! // When a type allocates memory, we can see it!
//! assert_eq!(vec![7u64; 2].dynamic_usage(), 16);
//!
//! // We see the memory the type has allocated, even if it isn't being used.
//! let empty: Vec<u32> = Vec::with_capacity(100);
//! assert_eq!(empty.len(), 0);
//! assert_eq!(empty.dynamic_usage(), 400);
//!
//! // For some types, we can't measure the exact memory usage, so we return a best
//! // estimate. If you need precision, call `dynamic_usage_bounds` which returns a
//! // lower bound, and (if known) an upper bound.
//! let map: HashMap<u8, u64> = HashMap::with_capacity(27);
//! let (lower, upper): (usize, Option<usize>) = map.dynamic_usage_bounds();
//! assert!(upper.is_none());
//! # }
//! ```

#![no_std]
#![forbid(unsafe_code)]
// Catch documentation errors caused by code changes.
#![deny(broken_intra_doc_links)]

#[cfg_attr(test, macro_use)]
extern crate alloc;

#[cfg(feature = "std")]
extern crate std;

use alloc::boxed::Box;
use alloc::collections::{BinaryHeap, LinkedList, VecDeque};
use alloc::string::String;
use alloc::vec::Vec;
use core::mem;

/// Trait for measuring the dynamic memory usage of types.
pub trait DynamicUsage {
    /// Returns a best estimate of the amount of heap-allocated memory used by this type.
    ///
    /// For most types, this will return an exact value. However, for types that use a
    /// complex allocation strategy (such as a `HashMap`), `memuse` cannot provide an
    /// exact heap allocation value, as it does not have access to the internal details
    /// and can only infer allocations from observable properties (such as the number of
    /// elements in a collection, or constants extracted from the implementation of the
    /// type). In those cases, this method returns a "best estimate" inferred from the
    /// implemented behaviour of the type. As more crates implement this trait themselves,
    /// the estimates will become more precise.
    ///
    /// The value returned by this method will always fall between the bounds returned by
    /// [`DynamicUsage::dynamic_usage_bounds`]:
    ///
    /// ```
    /// # #[cfg(feature = "std")]
    /// # {
    /// use std::collections::HashMap;
    /// use memuse::DynamicUsage;
    ///
    /// let a: HashMap<u8, u64> = HashMap::with_capacity(27);
    /// let usage = a.dynamic_usage();
    /// let (lower, upper) = a.dynamic_usage_bounds();
    ///
    /// assert!(lower <= usage);
    /// if let Some(upper) = upper {
    ///     assert!(usage <= upper);
    /// }
    /// # }
    /// ```
    fn dynamic_usage(&self) -> usize;

    /// Returns the lower and upper bounds on the amount of heap-allocated memory used by
    /// this type.
    ///
    /// The lower bound is always precise; a type cannot allocate fewer than zero bytes,
    /// and a collection cannot allocate fewer than the number of bytes required to store
    /// the entries it holds.
    ///
    /// The upper bound is only present if some property of the type ensures that its
    /// allocations do not exceed the bound, and is `None` otherwise (to indicate an
    /// unlimited upper bound).
    ///
    /// If the type's allocated memory is precisely known, then the lower and upper bounds
    /// will be equal.
    fn dynamic_usage_bounds(&self) -> (usize, Option<usize>);
}

//
// Helper macros
//

/// Helper to implement [`DynamicUsage`] for simple types that don't allocate.
///
/// # Examples
///
/// ```
/// // Must be imported so it is accessible to the macro.
/// use memuse::DynamicUsage;
///
/// struct RegisterByte(u8);
/// struct RegisterWord(u16);
///
/// memuse::impl_no_dynamic_usage!(RegisterByte, RegisterWord);
/// ```
///
/// The above is equivalent to:
/// ```
/// use memuse::DynamicUsage;
///
/// struct RegisterByte(u8);
/// struct RegisterWord(u16);
///
/// impl DynamicUsage for RegisterByte {
///     #[inline(always)]
///     fn dynamic_usage(&self) -> usize {
///         0
///     }
///
///     #[inline(always)]
///     fn dynamic_usage_bounds(&self) -> (usize, Option<usize>) {
///         (0, Some(0))
///     }
/// }
///
/// impl DynamicUsage for RegisterWord {
///     #[inline(always)]
///     fn dynamic_usage(&self) -> usize {
///         0
///     }
///
///     #[inline(always)]
///     fn dynamic_usage_bounds(&self) -> (usize, Option<usize>) {
///         (0, Some(0))
///     }
/// }
/// ```
#[macro_export]
macro_rules! impl_no_dynamic_usage {
    ($($type:ty),+) => {
        $(
            impl DynamicUsage for $type {
                #[inline(always)]
                fn dynamic_usage(&self) -> usize {
                    0
                }

                #[inline(always)]
                fn dynamic_usage_bounds(&self) -> (usize, Option<usize>) {
                    (0, Some(0))
                }
            }
        )+
    };
}

macro_rules! impl_iterable_dynamic_usage {
    ($type:ty, $base_usage:expr) => {
        impl<T: DynamicUsage> DynamicUsage for $type {
            fn dynamic_usage(&self) -> usize {
                $base_usage(self) + self.iter().map(DynamicUsage::dynamic_usage).sum::<usize>()
            }

            fn dynamic_usage_bounds(&self) -> (usize, Option<usize>) {
                let base = $base_usage(self);
                let (lower, upper) = self.iter().map(DynamicUsage::dynamic_usage_bounds).fold(
                    (0, Some(0)),
                    |(acc_lower, acc_upper), (lower, upper)| {
                        (acc_lower + lower, acc_upper.zip(upper).map(|(a, b)| a + b))
                    },
                );
                (base + lower, upper.map(|u| base + u))
            }
        }
    };
}

//
// Primitives
//

impl_no_dynamic_usage!(());
impl_no_dynamic_usage!(i8, i16, i32, i64, i128, isize);
impl_no_dynamic_usage!(u8, u16, u32, u64, u128, usize);
impl_no_dynamic_usage!(f32, f64, bool);
impl_no_dynamic_usage!(char, str);

// Tuples are handled below (so they render more nicely in docs)

impl<T: DynamicUsage, const N: usize> DynamicUsage for [T; N] {
    fn dynamic_usage(&self) -> usize {
        self.iter().map(DynamicUsage::dynamic_usage).sum::<usize>()
    }

    fn dynamic_usage_bounds(&self) -> (usize, Option<usize>) {
        self.iter().map(DynamicUsage::dynamic_usage_bounds).fold(
            (0, Some(0)),
            |(acc_lower, acc_upper), (lower, upper)| {
                (acc_lower + lower, acc_upper.zip(upper).map(|(a, b)| a + b))
            },
        )
    }
}

impl_iterable_dynamic_usage!([T], |_| 0);

//
// Structs
//

impl DynamicUsage for String {
    fn dynamic_usage(&self) -> usize {
        self.capacity()
    }

    fn dynamic_usage_bounds(&self) -> (usize, Option<usize>) {
        let usage = self.capacity();
        (usage, Some(usage))
    }
}

//
// Containers
//

impl<T: DynamicUsage> DynamicUsage for Box<T> {
    fn dynamic_usage(&self) -> usize {
        mem::size_of::<T>() + self.as_ref().dynamic_usage()
    }

    fn dynamic_usage_bounds(&self) -> (usize, Option<usize>) {
        let box_size = mem::size_of::<T>();
        let (inner_lower, inner_upper) = self.as_ref().dynamic_usage_bounds();
        (box_size + inner_lower, inner_upper.map(|u| box_size + u))
    }
}

impl<T: DynamicUsage> DynamicUsage for Option<T> {
    fn dynamic_usage(&self) -> usize {
        self.as_ref().map(DynamicUsage::dynamic_usage).unwrap_or(0)
    }

    fn dynamic_usage_bounds(&self) -> (usize, Option<usize>) {
        self.as_ref()
            .map(DynamicUsage::dynamic_usage_bounds)
            .unwrap_or((0, Some(0)))
    }
}

impl<T: DynamicUsage, E: DynamicUsage> DynamicUsage for Result<T, E> {
    fn dynamic_usage(&self) -> usize {
        match self {
            Ok(t) => t.dynamic_usage(),
            Err(e) => e.dynamic_usage(),
        }
    }

    fn dynamic_usage_bounds(&self) -> (usize, Option<usize>) {
        match self {
            Ok(t) => t.dynamic_usage_bounds(),
            Err(e) => e.dynamic_usage_bounds(),
        }
    }
}

//
// Collections
//

impl_iterable_dynamic_usage!(Vec<T>, |c: &Vec<T>| c.capacity() * mem::size_of::<T>());

impl_iterable_dynamic_usage!(BinaryHeap<T>, |c: &BinaryHeap<T>| {
    // BinaryHeap<T> is a wrapper around Vec<T>
    c.capacity() * mem::size_of::<T>()
});

impl_iterable_dynamic_usage!(LinkedList<T>, |c: &LinkedList<T>| {
    c.len() * mem::size_of::<T>()
});

impl_iterable_dynamic_usage!(VecDeque<T>, |c: &VecDeque<T>| {
    // +1 since the ringbuffer always leaves one space empty.
    (c.capacity() + 1) * mem::size_of::<T>()
});

#[cfg(feature = "std")]
mod hash;

//
// External crate types (provided for helpfulness, since `DynamicUsage` can only be
// implemented either here or in the external crate).
//

#[cfg(feature = "nonempty")]
impl_iterable_dynamic_usage!(nonempty::NonEmpty<T>, |c: &nonempty::NonEmpty<T>| {
    // NonEmpty<T> stores its head element separately from its tail Vec<T>.
    (c.capacity() - 1) * mem::size_of::<T>()
});

//
// Larger definitions (placed at the end so they render more nicely in docs).
//

mod tuple;

#[cfg(test)]
mod tests {
    use alloc::string::ToString;

    use super::*;

    #[test]
    fn standard_types() {
        assert_eq!(129u8.dynamic_usage(), 0);
        assert_eq!(3i128.dynamic_usage(), 0);
        assert_eq!(7.0f32.dynamic_usage(), 0);
        assert_eq!("foobar".dynamic_usage(), 0);

        assert_eq!(129u8.dynamic_usage_bounds(), (0, Some(0)));
        assert_eq!(3i128.dynamic_usage_bounds(), (0, Some(0)));
        assert_eq!(7.0f32.dynamic_usage_bounds(), (0, Some(0)));
        assert_eq!("foobar".dynamic_usage_bounds(), (0, Some(0)));
    }

    #[test]
    fn string() {
        assert_eq!(String::new().dynamic_usage(), 0);
        assert_eq!("foobar".to_string().dynamic_usage(), 6);

        assert_eq!(String::new().dynamic_usage_bounds(), (0, Some(0)));
        assert_eq!("foobar".to_string().dynamic_usage_bounds(), (6, Some(6)));
    }

    #[test]
    fn boxed() {
        let a: u64 = 7;
        assert_eq!(a.dynamic_usage(), 0);
        assert_eq!(a.dynamic_usage_bounds(), (0, Some(0)));

        let b: Box<u64> = Box::new(42);
        assert_eq!(b.dynamic_usage(), 8);
        assert_eq!(b.dynamic_usage_bounds(), (8, Some(8)));

        let capacity = 7;
        let c: Box<Vec<u16>> = Box::new(Vec::with_capacity(capacity));
        let expected = mem::size_of::<Vec<u16>>() + capacity * mem::size_of::<u16>();
        assert_eq!(c.dynamic_usage(), expected);
        assert_eq!(c.dynamic_usage_bounds(), (expected, Some(expected)));
    }

    #[test]
    fn option() {
        let a: Option<Vec<u8>> = None;
        let b: Option<Vec<u8>> = Some(vec![7u8; 4]);
        assert_eq!(a.dynamic_usage(), 0);
        assert_eq!(a.dynamic_usage_bounds(), (0, Some(0)));
        assert_eq!(b.dynamic_usage(), 4);
        assert_eq!(b.dynamic_usage_bounds(), (4, Some(4)));
    }

    #[test]
    fn array() {
        let a = [7; 42];
        assert_eq!(a.dynamic_usage(), 0);
        assert_eq!(a.dynamic_usage_bounds(), (0, Some(0)));

        let mut b = [None, None, None, None];
        assert_eq!(b.dynamic_usage(), 0);
        assert_eq!(b.dynamic_usage_bounds(), (0, Some(0)));

        b[0] = Some(vec![4u8; 20]);
        assert_eq!(b.dynamic_usage(), 20);
        assert_eq!(b.dynamic_usage_bounds(), (20, Some(20)));
    }

    #[test]
    fn vec() {
        let capacity = 7;
        let mut a = Vec::with_capacity(capacity);
        a.push(42u64);

        let expected = capacity * mem::size_of::<u64>();
        assert_eq!(a.dynamic_usage(), expected);
        assert_eq!(a.dynamic_usage_bounds(), (expected, Some(expected)));
    }

    #[cfg(feature = "nonempty")]
    #[test]
    fn nonempty() {
        let a = nonempty::NonEmpty::new(42);
        assert_eq!(a.dynamic_usage(), 0);
        assert_eq!(a.dynamic_usage_bounds(), (0, Some(0)));

        const CAPACITY: usize = 7;
        let b = nonempty::NonEmpty::from_slice(&[27u128; CAPACITY]).unwrap();

        let expected = (CAPACITY - 1) * mem::size_of::<u128>();
        assert_eq!(b.dynamic_usage(), expected);
        assert_eq!(b.dynamic_usage_bounds(), (expected, Some(expected)));
    }
}