add 'constnamemap' macro

to be able to define constant values but still have some mapping to
the name of it

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
This commit is contained in:
Dominik Csapak 2020-05-20 12:15:29 +02:00 committed by Dietmar Maurer
parent 34d09a5d07
commit 10012dcb17
2 changed files with 82 additions and 0 deletions

View File

@ -0,0 +1,81 @@
/// A macro to generate a list of pub const variabales and
/// an accompaning static array of a given name + value
/// (with doc comments)
///
/// Example:
/// ```
/// # use proxmox::constnamemap;
///
/// constnamemap! {
/// /// A list of privileges
/// PRIVS: u64 => {
/// /// Some comment for Priv1
/// PRIV1("Priv1") = 1;
/// PRIV2("Priv2") = 2;
/// }
/// }
/// ```
///
/// this will generate the following variables:
/// ```
/// /// Some comment for Priv1
/// pub const PRIV1: u64 = 1;
/// pub const PRIV2: u64 = 2;
///
/// /// A list of privileges
/// pub const PRIVS: &[(&str, u64)] = &[
/// ("Priv1", 1),
/// ("Priv2", 2),
/// ];
/// ```
#[macro_export(local_inner_macros)]
macro_rules! constnamemap {
(
$(#[$outer:meta])*
$name:ident : $type:ty => {
$($content:tt)+
}
) => {
__constnamemap_consts! {
$type => $($content)+
}
$(#[$outer])*
pub const $name: &[(&str, $type)] =
__constnamemap_entries! {
$($content)+
};
}
}
#[doc(hidden)]
#[macro_export(local_inner_macros)]
macro_rules! __constnamemap_consts {
(
$type:ty =>
$(
$(#[$outer:meta])*
$name:ident($text:expr) = $value:expr;
)+
) => {
$(
$(#[$outer])*
pub const $name: $type = $value;
)+
}
}
#[doc(hidden)]
#[macro_export(local_inner_macros)]
macro_rules! __constnamemap_entries {
(
$(
$(#[$outer:meta])*
$name:ident($text:expr) = $value:expr;
)*
) => {
&[
$(($text,$value),)*
]
}
}

View File

@ -14,6 +14,7 @@ pub mod serde;
pub mod uuid;
pub mod vec;
pub mod time;
pub mod constnamemap;
#[doc(inline)]
pub use uuid::Uuid;