rate_common/memory.rs
1//! General purpose data structures
2//!
3//! These are simply `std::vec::Vec` wrappers tuned for a specific purpose,
4//! so they are harder to misuse, or more efficient.
5//!
6//! For example:
7//!
8//! - The first template argument in `Array<I, T>` and `StackMapping<I, T>`
9//! requires to specify a type that will be used for indexing. This prevents
10//! us from accidentally using an index of the wrong type.
11//!
12//! - If we know a good upper bound for the size of a vector we prefer to
13//! use `Array<I, T>`, `BoundedVector<T>` or `StackMapping<Key, T>` as
14//! they never allocate after being constructed.
15//!
16//! - Bounds checking can be disabled for all these vectors.
17
18mod array;
19mod boundedvector;
20#[macro_use]
21mod vector;
22mod stackmapping;
23
24use std::convert::TryFrom;
25
26pub use crate::memory::{
27 array::Array,
28 boundedvector::BoundedVector,
29 stackmapping::StackMapping,
30 vector::{assert_in_bounds, Vector},
31};
32
33/// Trait for types that can be used as an array index.
34pub trait Offset {
35 fn as_offset(&self) -> usize;
36}
37
38impl Offset for usize {
39 fn as_offset(&self) -> usize {
40 *self
41 }
42}
43
44impl Offset for u64 {
45 fn as_offset(&self) -> usize {
46 requires!(usize::try_from(*self).is_ok());
47 *self as usize
48 }
49}
50
51impl Offset for i32 {
52 fn as_offset(&self) -> usize {
53 requires!(usize::try_from(*self).is_ok());
54 *self as usize
55 }
56}
57
58/// A trait for objects that can report their memory usage on the heap
59pub trait HeapSpace {
60 /// The number of bytes allocated on the heap that this owns.
61 fn heap_space(&self) -> usize;
62}
63
64impl<T: Copy> HeapSpace for T {
65 fn heap_space(&self) -> usize {
66 0
67 }
68}
69
70/// Convert bytes to megabytes for readability.
71pub fn format_memory_usage(bytes: usize) -> String {
72 format!("{:12}", bytes >> 20) // MB
73}