Skip to main content

tor_memquota_cost/
if_enabled.rs

1//! Helper type for disabling memory tracking when not wanted
2
3/// Token indicating that memory quota tracking is enabled, at both compile and runtime
4///
5/// If support is compiled in this is a unit.
6///
7/// If the `memquota` cargo feature is not enabled, this type is uninhabited.
8/// Scattering values of this type around in relevant data structures
9/// and parameters lists
10/// allows the compiler to eliminate the unwanted code.
11#[derive(Clone, Copy, Debug, PartialEq)]
12pub struct EnabledToken {
13    /// Make non-exhaustive even within the crate
14    _hidden: (),
15
16    /// Uninhabited if the feature isn't enabled.
17    #[cfg(not(feature = "memquota"))]
18    _forbid: void::Void,
19}
20
21// Avoid unused crate warning.
22//
23// (We can't express the right dependency condition in Cargo.toml,
24// and anyway it's not worth trying to conditionally suppress the dependency.)
25#[cfg(feature = "memquota")]
26use void as _;
27
28impl Eq for EnabledToken {}
29
30impl EnabledToken {
31    /// Obtain an `EnabledToken` (only available if tracking is compiled in)
32    #[allow(clippy::new_without_default)] // a conditional Default impl would be rather odd
33    #[cfg(feature = "memquota")]
34    pub const fn new() -> Self {
35        EnabledToken { _hidden: () }
36    }
37
38    /// Obtain an `EnabledToken` if memory-tracking is compiled in, or `None` otherwise
39    #[allow(clippy::unnecessary_wraps)] // Will be None if compiled out
40    #[allow(unreachable_code)]
41    pub const fn new_if_compiled_in() -> Option<Self> {
42        Some(EnabledToken {
43            _hidden: (),
44
45            #[cfg(not(feature = "memquota"))]
46            _forbid: return None,
47        })
48    }
49}