pub trait HeapSize {
    fn heap_size(&self) -> usize;
}
Expand description

A trait for types whose size on the heap can be determined at runtime. Note for all Sized types, it is sufficient to implement this trait, as a blanket implementation of MemSize is alread provided. The latter is required for the LruCache to track the size of its entries. It has implementations for most common data types and containers.

Note that reference-counting smart pointers deliberately do not implement this trait, as it is not clear whether a pointer will drop the referenced content when it is ejected from the cache.

Example

For simple types which are stored completely in one memory location, such as primitive types or structs of such types, it usually suffices to implement this as a constant 0.

use lru_mem::HeapSize;
use std::mem;

struct Vector2f {
    x: f32,
    y: f32
}

impl HeapSize for Vector2f {
    fn heap_size(&self) -> usize {
        0
    }
}

For more complicated types, it may be necessary to account for any referenced data that is owned by the instance. If the memory is owned by some field, which already implements HeapSize, you can rely on that implementation to estimate the required heap memory. See below for an example of this.

use lru_mem::HeapSize;

struct Person {
    name: String,
    address: String
}

impl HeapSize for Person {
    fn heap_size(&self) -> usize {
        // Both members may have allocated data, which is accounted for by
        // calling heap_size.
        self.name.heap_size() + self.address.heap_size()
    }
}

In case the previous examples do not apply, consider the implementation on String provided by this library. It demonstrates how to manually account for any owned referenced data.

use lru_mem::HeapSize;
use std::mem;

impl HeapSize for String {
    fn heap_size(&self) -> usize {
        // The number of bytes reserved on the heap for UTF-8 data.
        self.capacity()
    }
}

Required methods

The size of the referenced data that is owned by this value, usually allocated on the heap (such as the value of a Box or the elements and reserved memory of a Vec).

Example
use lru_mem::HeapSize;

assert_eq!(0, 1u64.heap_size());
assert_eq!(12, "hello world!".to_owned().heap_size());

Implementations on Foreign Types

Implementors