tor_memquota/memory_cost_derive.rs
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
//! Deriving `HasMemoryCost`
use crate::internal_prelude::*;
//---------- main public items ----------
/// Types whose `HasMemoryCost` is derived structurally
///
/// Usually implemented using
/// [`#[derive_deftly(HasMemoryCost)]`](crate::derive_deftly_template_HasMemoryCost).
///
/// For `Copy` types, it can also be implemented with
/// `memory_cost_structural_copy!`.
///
/// When this trait is implemented, a blanket impl provides [`HasMemoryCost`].
///
/// ### Structural memory cost
///
/// We call the memory cost "structural"
/// when it is derived from the type's structure.
///
/// The memory cost of a `HasMemoryCostStructural` type is:
///
/// - The number of bytes in its own size [`size_of`]; plus
///
/// - The (structural) memory cost of all the out-of-line data that it owns;
/// that's what's returned by
/// [`indirect_memory_cost`](HasMemoryCostStructural::indirect_memory_cost)
///
/// For example, `String`s out-of-line memory cost is just its capacity,
/// so its memory cost is the size of its three word layout plus its capacity.
///
/// This calculation is performed by the blanket impl of `HasMemoryCost`.
///
/// ### Shared data - non-`'static` types, `Arc`
///
/// It is probably a mistake to implement this trait (or `HasMemoryCost`)
/// for types with out-of-line data that they don't exclusively own.
/// After all, the memory cost must be known and fixed,
/// and if there is shared data it's not clear how it should be accounted.
pub trait HasMemoryCostStructural {
/// Memory cost of data stored out-of-line
///
/// The total memory cost is the cost of the layout of `self` plus this.
fn indirect_memory_cost(&self, _: EnabledToken) -> usize;
}
/// Compile-time check for `Copy + 'static` - helper for macros
///
/// Used by `#[deftly(has_memory_cost(copy))]`
/// and `memory_cost_structural_copy!`
/// to check that the type really is suitable.
pub fn assert_copy_static<T: Copy + 'static>(_: &T) {}
impl<T: HasMemoryCostStructural> HasMemoryCost for T {
fn memory_cost(&self, et: EnabledToken) -> usize {
size_of::<T>() //
.saturating_add(
//
<T as HasMemoryCostStructural>::indirect_memory_cost(self, et),
)
}
}
//---------- specific implementations ----------
/// Implement [`HasMemoryCostStructural`] for `Copy` types
///
/// The [`indirect_memory_cost`](HasMemoryCostStructural::indirect_memory_cost)
/// of a `Copy + 'static` type is zero.
///
/// This macro implements that.
///
/// Ideally, we would `impl <T: Copy + 'static> MemoryCostStructural for T`.
/// But that falls foul of trait coherence rules.
/// So instead we provide `memory_cost_structural_copy!`
/// and the `#[deftly(has_memory_cost(copy))]` attribute.
///
/// This macro can only be used within `tor-memquota`, or for types local to your crate.
/// For other types, use `#[deftly(has_memory_cost(copy))]` on each field of that type.
//
// Unfortunately we can't provide a blanket impl of `HasMemoryCostStructural`
// for all `Copy` types, because we want to provide `HasMemoryCostStructural`
// for `Vec` and `Box` -
// and rustic thinks that those might become `Copy` in the future.
#[macro_export]
macro_rules! memory_cost_structural_copy { { $($ty:ty),* $(,)? } => { $(
impl $crate::HasMemoryCostStructural for $ty {
fn indirect_memory_cost(&self, _et: $crate::EnabledToken) -> usize {
$crate::assert_copy_static::<$ty>(self);
0
}
}
)* } }
memory_cost_structural_copy! {
u8, u16, u32, u64, usize,
i8, i16, i32, i64, isize,
// TODO MSRV use std::num::NonZero<_> and avoid all these qualified names
std::num::NonZeroU8, std::num::NonZeroU16, std::num::NonZeroU32, std::num::NonZeroU64,
std::num::NonZeroI8, std::num::NonZeroI16, std::num::NonZeroI32, std::num::NonZeroI64,
std::num::NonZeroUsize,
std::num::NonZeroIsize,
std::net::IpAddr, std::net::Ipv4Addr, std::net::Ipv6Addr,
}
/// Implement HasMemoryCost for tuples
macro_rules! memory_cost_structural_tuples { {
// Recursive case: do base case for this input, and then the next inputs
$($T:ident)* - $U0:ident $($UN:ident)*
} => {
memory_cost_structural_tuples! { $($T)* - }
memory_cost_structural_tuples! { $($T)* $U0 - $($UN)* }
}; {
// Base case, implement for the tuple with contents types $T
$($T:ident)* -
} => { paste! {
impl < $(
$T: HasMemoryCostStructural,
)* > HasMemoryCostStructural for ( $(
$T,
)* ) {
fn indirect_memory_cost(&self, #[allow(unused)] et: EnabledToken) -> usize {
let ( $(
[< $T:lower >],
)* ) = self;
0_usize $(
.saturating_add([< $T:lower >].indirect_memory_cost(et))
)*
}
}
} } }
memory_cost_structural_tuples! { - A B C D E F G H I J K L M N O P Q R S T U V W X Y Z }
impl<T: HasMemoryCostStructural> HasMemoryCostStructural for Option<T> {
fn indirect_memory_cost(&self, et: EnabledToken) -> usize {
if let Some(t) = self {
<T as HasMemoryCostStructural>::indirect_memory_cost(t, et)
} else {
0
}
}
}
impl<T: HasMemoryCostStructural, const N: usize> HasMemoryCostStructural for [T; N] {
fn indirect_memory_cost(&self, et: EnabledToken) -> usize {
self.iter()
.map(|t| t.indirect_memory_cost(et))
.fold(0, usize::saturating_add)
}
}
impl<T: HasMemoryCostStructural> HasMemoryCostStructural for Box<T> {
fn indirect_memory_cost(&self, et: EnabledToken) -> usize {
<T as HasMemoryCost>::memory_cost(&**self, et)
}
}
impl<T: HasMemoryCostStructural> HasMemoryCostStructural for Vec<T> {
fn indirect_memory_cost(&self, et: EnabledToken) -> usize {
chain!(
[size_of::<T>().saturating_mul(self.capacity())],
self.iter().map(|t| t.indirect_memory_cost(et)),
)
.fold(0, usize::saturating_add)
}
}
impl HasMemoryCostStructural for String {
fn indirect_memory_cost(&self, _et: EnabledToken) -> usize {
self.capacity()
}
}
//------------------- derive macro ----------
define_derive_deftly! {
/// Derive `HasMemoryCost`
///
/// Each field must implement [`HasMemoryCostStructural`].
///
/// Valid for structs and enums.
///
/// ### Top-level attributes
///
/// * **`#[deftly(has_memory_cost(bounds = "BOUNDS"))]`**:
/// Additional bounds to apply to the implementation.
///
/// ### Field attributes
///
/// * **`#[deftly(has_memory_cost(copy))]`**:
/// This field is `Copy + 'static` so does not reference any data that should be accounted.
/// * **`#[deftly(has_memory_cost(indirect_fn = "FUNCTION"))]`**:
/// `FUNCTION` is a function with the signature and semantics of
/// [`HasMemoryCostStructural::indirect_memory_cost`],
/// * **`#[deftly(has_memory_cost(indirect_size = "EXPR"))]`**:
/// `EXPR` is an expression of type usize with the semantics of a return value from
/// [`HasMemoryCostStructural::indirect_memory_cost`].
///
/// With one of these, the field doesn't need to implement `HasMemoryCostStructural`.
///
/// # Example
///
/// ```
/// use derive_deftly::Deftly;
/// use std::mem::size_of;
/// use tor_memquota::{HasMemoryCost, HasMemoryCostStructural};
/// use tor_memquota::derive_deftly_template_HasMemoryCost;
///
/// #[derive(Deftly)]
/// #[derive_deftly(HasMemoryCost)]
/// #[deftly(has_memory_cost(bounds = "Data: HasMemoryCostStructural"))]
/// struct Struct<Data> {
/// data: Data,
///
/// #[deftly(has_memory_cost(indirect_size = "0"))] // this is a good guess
/// num: serde_json::Number,
///
/// #[deftly(has_memory_cost(copy))]
/// msg: &'static str,
///
/// #[deftly(has_memory_cost(indirect_fn = "|info, _et| String::capacity(info)"))]
/// info: safelog::Sensitive<String>,
/// }
///
/// let s = Struct {
/// data: String::with_capacity(33),
/// num: serde_json::Number::from_f64(0.0).unwrap(),
/// msg: "hello",
/// info: String::with_capacity(12).into(),
/// };
///
/// let Some(et) = tor_memquota::EnabledToken::new_if_compiled_in() else { return };
///
/// assert_eq!(
/// s.memory_cost(et),
/// size_of::<Struct<String>>() + 33 + 12,
/// );
/// ```
export HasMemoryCost expect items:
impl<$tgens> $crate::HasMemoryCostStructural for $ttype
where $twheres ${if tmeta(has_memory_cost(bounds)) {
${tmeta(has_memory_cost(bounds)) as token_stream}
}}
{
fn indirect_memory_cost(&self, #[allow(unused)] et: $crate::EnabledToken) -> usize {
${define F_INDIRECT_COST {
${select1
fmeta(has_memory_cost(copy)) {
{
$crate::assert_copy_static::<$ftype>(&$fpatname);
0
}
}
fmeta(has_memory_cost(indirect_fn)) {
${fmeta(has_memory_cost(indirect_fn)) as expr}(&$fpatname, et)
}
fmeta(has_memory_cost(indirect_size)) {
${fmeta(has_memory_cost(indirect_size)) as expr}
}
else {
<$ftype as $crate::HasMemoryCostStructural>::indirect_memory_cost(&$fpatname, et)
}
}
}}
match self {
$(
$vpat => {
0_usize
${for fields {
.saturating_add( $F_INDIRECT_COST )
}}
}
)
}
}
}
}
#[cfg(all(test, feature = "memquota"))]
mod test {
// @@ begin test lint list maintained by maint/add_warning @@
#![allow(clippy::bool_assert_comparison)]
#![allow(clippy::clone_on_copy)]
#![allow(clippy::dbg_macro)]
#![allow(clippy::mixed_attributes_style)]
#![allow(clippy::print_stderr)]
#![allow(clippy::print_stdout)]
#![allow(clippy::single_char_pattern)]
#![allow(clippy::unwrap_used)]
#![allow(clippy::unchecked_duration_subtraction)]
#![allow(clippy::useless_vec)]
#![allow(clippy::needless_pass_by_value)]
//! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
#![allow(clippy::arithmetic_side_effects)] // don't mind potential panicking ops in tests
use super::*;
#[derive(Deftly)]
#[derive_deftly(HasMemoryCost)]
enum E {
U(usize),
B(Box<u32>),
}
#[derive(Deftly, Default)]
#[derive_deftly(HasMemoryCost)]
struct S {
u: usize,
b: Box<u32>,
v: Vec<u32>,
ev: Vec<E>,
}
const ET: EnabledToken = EnabledToken::new();
// The size of a u32 is always 4 bytes, so we just write "4" rather than u32::SIZE.
#[test]
fn structs() {
assert_eq!(S::default().memory_cost(ET), size_of::<S>() + 4);
assert_eq!(E::U(0).memory_cost(ET), size_of::<E>());
assert_eq!(E::B(Box::default()).memory_cost(ET), size_of::<E>() + 4);
}
#[test]
fn values() {
let mut v: Vec<u32> = Vec::with_capacity(10);
v.push(1);
let s = S {
u: 0,
b: Box::new(42),
v,
ev: vec![],
};
assert_eq!(
s.memory_cost(ET),
size_of::<S>() + 4 /* b */ + 10 * 4, /* v buffer */
);
}
#[test]
#[allow(clippy::identity_op)]
fn nest() {
let mut ev = Vec::with_capacity(10);
ev.push(E::U(42));
ev.push(E::B(Box::new(42)));
let s = S { ev, ..S::default() };
assert_eq!(
s.memory_cost(ET),
size_of::<S>() + 4 /* b */ + 0 /* v */ + size_of::<E>() * 10 /* ev buffer */ + 4 /* E::B */
);
}
}