tetsy_memory_db/
malloc_size_of.rs

1// Copyright 2020 Parity Technologies
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! This module contains traits and structs related to the `MallocSizeOf` trait.
16
17use core::marker::PhantomData;
18use tetsy_util_mem::{malloc_size, MallocSizeOf};
19
20
21/// Used to implement incremental evaluation of `MallocSizeOf` for a collection.
22pub trait MemTracker<T> {
23	/// Update `malloc_size_of` when a value is removed.
24	fn on_remove(&mut self, _value: &T) {}
25	/// Update `malloc_size_of` when a value is inserted.
26	fn on_insert(&mut self, _value: &T) {}
27	/// Reset `malloc_size_of` to zero.
28	fn on_clear(&mut self) {}
29	/// Get the allocated size of the values.
30	fn get_size(&self) -> usize { 0 }
31}
32
33/// `MemTracker` implementation for types
34/// which implement `MallocSizeOf`.
35#[derive(Eq, PartialEq)]
36pub struct MemCounter<T> {
37	malloc_size_of_values: usize,
38	_phantom: PhantomData<T>,
39}
40
41impl<T> MemCounter<T> {
42	// Create a new instance of MemCounter<T>.
43	pub fn new() -> Self {
44		Self {
45			malloc_size_of_values: 0,
46			_phantom: PhantomData,
47		}
48	}
49}
50
51impl<T> Default for MemCounter<T> {
52	fn default() -> Self {
53		Self::new()
54	}
55}
56
57impl<T> Clone for MemCounter<T> {
58	fn clone(&self) -> Self {
59		Self {
60			malloc_size_of_values: self.malloc_size_of_values,
61			_phantom: PhantomData,
62		}
63	}
64}
65
66impl<T> Copy for MemCounter<T> {}
67
68impl<T: MallocSizeOf> MemTracker<T> for MemCounter<T> {
69	fn on_remove(&mut self, value: &T) {
70		self.malloc_size_of_values -= malloc_size(value);
71	}
72	fn on_insert(&mut self, value: &T) {
73		self.malloc_size_of_values += malloc_size(value);
74	}
75	fn on_clear(&mut self) {
76		self.malloc_size_of_values = 0;
77	}
78	fn get_size(&self) -> usize {
79		self.malloc_size_of_values
80	}
81}
82
83/// No-op `MemTracker` implementation for when we want to
84/// construct a `MemoryDB` instance that does not track memory usage.
85#[derive(PartialEq, Eq)]
86pub struct NoopTracker<T>(PhantomData<T>);
87
88impl<T> Default for NoopTracker<T> {
89	fn default() -> Self {
90		Self(PhantomData)
91	}
92}
93
94impl<T> Clone for NoopTracker<T> {
95	fn clone(&self) -> Self {
96        Self::default()
97	}
98}
99
100impl<T> Copy for NoopTracker<T> {}
101
102impl<T> MemTracker<T> for NoopTracker<T> {}