Skip to content

Commit

Permalink
Added ident_key convenience macro
Browse files Browse the repository at this point in the history
Summary:
Adds the `ident_key` macro which expands an ident to a `const` `Key`, which is a common necessity when manually implementing instances of `Allocative`.

X-link: facebookexperimental/allocative#7

Reviewed By: ndmitchell

Differential Revision: D52630097

Pulled By: stepancheg

fbshipit-source-id: 3d261921b29ba8bd4de218b410ac5aa24fccba8b
  • Loading branch information
JustusAdam authored and facebook-github-bot committed Jan 9, 2024
1 parent b50497c commit 57fa014
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions allocative/allocative/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,3 +73,37 @@ pub use crate::visitor::Visitor;
pub mod __macro_refs {
pub use ctor;
}

/// Create a `const` of type `Key` with the provided `ident` as the value and
/// return that value. This allows the keys to be placed conveniently inline
/// without any performance hit because unlike calling `Key::new` this is
/// guaranteed to be evaluated at compile time.
///
/// The main use case is manual implementations of [`Allocative`], like so:
///
/// ```
/// use allocative::ident_key;
/// use allocative::Allocative;
/// use allocative::Visitor;
///
/// struct MyStruct {
/// foo: usize,
/// bar: Vec<()>,
/// }
///
/// impl Allocative for MyStruct {
/// fn visit<'a, 'b: 'a>(&self, visitor: &'a mut Visitor<'b>) {
/// let mut visitor = visitor.enter_self(self);
/// visitor.visit_field(ident_key!(foo), &self.foo);
/// visitor.visit_field(ident_key!(bar), &self.bar);
/// visitor.exit();
/// }
/// }
/// ```
#[macro_export]
macro_rules! ident_key {
($name:ident) => {{
const KEY: $crate::Key = $crate::Key::new(stringify!(name));
KEY
}};
}

0 comments on commit 57fa014

Please sign in to comment.