parse_env

Macro parse_env 

Source
macro_rules! parse_env {
    ($var_name:literal as $typ:ident) => { ... };
    ($var_name:literal as $typ:ident else $default:expr) => { ... };
    ($var_name:literal as $typ:ident in $range:expr) => { ... };
    ($var_name:literal as $typ:ident (in $range:expr) else $default:expr) => { ... };
    (try $var_name:literal as $typ:ident) => { ... };
    (try $var_name:literal as $typ:ident in $range:expr) => { ... };
}
Expand description

Parse an environment variable into some value. The main entry-point of this library.

Here’s an example

const MAX_LEN: usize = envparse::parse_env!("MYCRATE_MAX_THING_LEN" as usize else 64);
struct Thing {
    len: [u8; MAX_LEN],
}

Here’s one that deliberately fails

const MAX_LEN: usize = envparse::parse_env!("MUST_BE_USER_PROVIDED" as usize);
struct Thing {
    len: [u8; MAX_LEN],
}

You can bound by ranges too. This one will fail because the MUST_BE_USER_PROVIDED var isn’t provided.

const MAX_LEN_LOG2: u32 = envparse::parse_env!("MUST_BE_USER_PROVIDED" as u32 in 1..32);
const MAX_LEN: usize = 1 << MAX_LEN_LOG2;
struct Thing {
    len: [u8; MAX_LEN],
}

If it’s optional and you want an Option out of it, you can use try:

const MAX_LEN: usize = match envparse::parse_env!(try "OPTIONAL_MAX_LEN_LOG2" as u32 in 1..32) {
    Some(v) => 1 << v,
    None => 0x80,
};
struct Thing {
    len: [u8; MAX_LEN],
}