Merge pull request #14 from icetemple/task-13

feat: add lazy static
This commit is contained in:
Dmitriy Pleshevskiy 2020-02-08 20:58:42 +03:00 committed by GitHub
commit a9df98ae61
10 changed files with 385 additions and 82 deletions

View file

@ -12,7 +12,7 @@ before_cache:
script: script:
- | - |
rustc --version && rustc --version &&
cargo test cargo test --all-features
matrix: matrix:
allow_failures: allow_failures:
- rust: nightly - rust: nightly

View file

@ -43,14 +43,16 @@ config! {
), ),
APP { APP {
static BASE_URL => "/api", // &'static str by default
ARTICLE { ARTICLE {
PER_PAGE: u32 => 15, static PER_PAGE: u32 => 15,
} }
#[cfg(feature = "companies")] #[cfg(feature = "companies")]
COMPANY { COMPANY {
#[env_name = "INSTITUTIONS_PER_PAGE"] #[env_name = "INSTITUTIONS_PER_PAGE"]
PER_PAGE: u32 => 15, static PER_PAGE: u32 => 15,
} }
} }
@ -117,30 +119,30 @@ cargo test
## Available features ## Available features
* default = ["macro", "primitives"] * **default** - ["macro", "primitives"]
* macro = [] * **macro** - Activates `config!` macros for easy configure web application.
* array = ["serde_json"] * **static** - Add `static` option to `config!` macros (uses optional `lazy_static` package).
* primitives = ["numbers", "bool"] * **array** - Add EnvString impl for vector type (uses optional `serde_json` package).
* numbers = ["int", "uint", "float"] * **primitives** - Group for features: `numbers` and `bool`.
* int = ["i8", "i16", "i32", "i64", "i128", "isize"] * **numbers** - Group for features: `int`, `uint` and `float`.
* uint = ["u8", "u16", "u32", "u64", "u128", "usize"] * **int** - Group for features: `i8`, `i16`, `i32`, `i64`, `i128` and `isize`.
* float = ["f32", "f64"] * **uint** - Group for features: `u8`, `u16`, `u32`, `u64`, `u128` and `usize`.
* i8 = [] * **float** - Group for features: `f32` and `f64`
* i16 = [] * **i8** - impl EnvString for i8 type
* i32 = [] * **i16** - impl EnvString for i16 type
* i64 = [] * **i32** - impl EnvString for i32 type
* i128 = [] * **i64** - impl EnvString for i64 type
* isize = [] * **i128** - impl EnvString for i128 type
* u8 = [] * **isize** - impl EnvString for isize type
* u16 = [] * **u8** - impl EnvString for u8 type
* u32 = [] * **u16** - impl EnvString for u16 type
* u64 = [] * **u32** - impl EnvString for u32 type
* u128 = [] * **u64** - impl EnvString for u64 type
* usize = [] * **u128** - impl EnvString for u128 type
* f32 = [] * **usize** - impl EnvString for usize type
* f64 = [] * **f32** - impl EnvString for f32 type
* bool = [] * **f64** - impl EnvString for f64 type
* **bool** - impl EnvString for bool type
## License ## License

View file

@ -14,8 +14,9 @@ criterion = "0.3.1"
lazy_static = "1.4.0" lazy_static = "1.4.0"
[features] [features]
default = ["meta_namespace"] default = ["meta_namespace", "static"]
meta_namespace = [] meta_namespace = []
static = ["itconfig/static"]
[[bench]] [[bench]]
name = "main_benches" name = "main_benches"

View file

@ -3,11 +3,13 @@ use std::env;
#[macro_use] #[macro_use]
extern crate lazy_static; extern crate lazy_static;
#[macro_use]
extern crate itconfig;
fn setup_env_var(initial: &String) { fn setup_env_var(key: &'static str, initial: String) {
env::set_var("TEST", initial); env::set_var(key, initial);
} }
@ -26,33 +28,66 @@ fn lazy_get_env() -> u32 {
fn source_vs_lazy(c: &mut Criterion) { fn source_vs_lazy(c: &mut Criterion) {
let source = Fun::new("source", |b, initial: &String| { setup_env_var("TEST", "1".to_string());
setup_env_var(initial);
let int: u32 = initial.parse().unwrap();
let source = Fun::new("source", |b, _| {
b.iter(move || { b.iter(move || {
assert_eq!(source_get_env(), int) assert_eq!(source_get_env(), 1)
}) })
}); });
let lazy = Fun::new("lazy", |b, initial: &String| { let lazy = Fun::new("lazy", |b, _| {
setup_env_var(initial);
let int: u32 = initial.parse().unwrap();
b.iter(move || { b.iter(move || {
assert_eq!(lazy_get_env(), int); assert_eq!(lazy_get_env(), 1);
}) })
}); });
let funcs = vec![source, lazy]; c.bench_functions("get_env", vec![source, lazy], 0);
c.bench_functions("get_env", funcs, "1".to_string());
} }
fn source_macro_vs_lazy_macro(c: &mut Criterion) {
config! {
TEST: &'static str,
TEST_WITH_DEFAULT: &'static str => "default",
static LAZY_TEST: &'static str,
static LAZY_TEST_WITH_DEFAULT: &'static str => "default",
}
setup_env_var("TEST", "test".to_string());
setup_env_var("LAZY_TEST", "test".to_string());
let source = Fun::new("source", |b, _| {
b.iter(move || {
assert_eq!(cfg::TEST(), "test");
})
});
let lazy = Fun::new("lazy", |b, _| {
b.iter(move || {
assert_eq!(cfg::LAZY_TEST(), "test");
})
});
let source_with_default = Fun::new("source_with_default", |b, _| {
b.iter(move || {
assert_eq!(cfg::TEST_WITH_DEFAULT(), "default");
})
});
let lazy_with_default = Fun::new("lazy_with_default", |b, _| {
b.iter(move || {
assert_eq!(cfg::LAZY_TEST_WITH_DEFAULT(), "default");
})
});
let funcs = vec![source, lazy, source_with_default, lazy_with_default];
c.bench_functions("macro", funcs, 0);
}
criterion_group! { criterion_group! {
benches, benches,
source_vs_lazy, source_vs_lazy,
source_macro_vs_lazy_macro,
} }
criterion_main!(benches); criterion_main!(benches);

View file

@ -422,3 +422,51 @@ fn concatenated_environment_variable_in_namespace() {
); );
assert_eq!(env::var("CONCAT_ENVVAR"), Err(VarError::NotPresent)); assert_eq!(env::var("CONCAT_ENVVAR"), Err(VarError::NotPresent));
} }
#[test]
#[cfg(feature = "static")]
fn static_variables() {
config! {
static STATIC_STR => "test",
static STATIC_STRING: String => "test",
static STATIC_I8: i8 => 1,
static STATIC_I16: i16 => 1,
static STATIC_I32: i32 => 1,
static STATIC_I64: i64 => 1,
static STATIC_I128: i128 => 1,
static STATIC_ISIZE: isize => 1,
static STATIC_U8: u8 => 1,
static STATIC_U16: u16 => 1,
static STATIC_U32: u32 => 1,
static STATIC_U64: u64 => 1,
static STATIC_U128: u128 => 1,
static STATIC_USIZE: usize => 1,
static STATIC_F32: f32 => 1,
static STATIC_F64: f64 => 1,
static STATIC_CONCAT_VARIABLE < (
"static ",
STATIC_CONCAT_PART => "part",
),
}
cfg::init();
assert_eq!(cfg::STATIC_STR(), "test");
assert_eq!(cfg::STATIC_STRING(), "test".to_string());
assert_eq!(cfg::STATIC_I8(), 1);
assert_eq!(cfg::STATIC_I16(), 1);
assert_eq!(cfg::STATIC_I32(), 1);
assert_eq!(cfg::STATIC_I64(), 1);
assert_eq!(cfg::STATIC_I128(), 1);
assert_eq!(cfg::STATIC_ISIZE(), 1);
assert_eq!(cfg::STATIC_U8(), 1);
assert_eq!(cfg::STATIC_U16(), 1);
assert_eq!(cfg::STATIC_U32(), 1);
assert_eq!(cfg::STATIC_U64(), 1);
assert_eq!(cfg::STATIC_U128(), 1);
assert_eq!(cfg::STATIC_USIZE(), 1);
assert_eq!(cfg::STATIC_F32(), 1.0);
assert_eq!(cfg::STATIC_F64(), 1.0);
assert_eq!(cfg::STATIC_CONCAT_VARIABLE(), "static part".to_string())
}

View file

@ -1,6 +1,6 @@
[package] [package]
name = "itconfig" name = "itconfig"
version = "0.10.2" version = "0.11.0"
authors = ["Dmitriy Pleshevskiy <dmitriy@ideascup.me>"] authors = ["Dmitriy Pleshevskiy <dmitriy@ideascup.me>"]
description = "Easy build a configs from environment variables and use it in globally." description = "Easy build a configs from environment variables and use it in globally."
categories = ["config", "web-programming"] categories = ["config", "web-programming"]
@ -16,11 +16,14 @@ readme = "README.md"
[dependencies] [dependencies]
failure = { version = "0.1.6", features = ["derive"]} failure = { version = "0.1.6", features = ["derive"]}
lazy_static = { version = "1.4.0", optional = true }
serde_json = { version = "1.0.44", optional = true } serde_json = { version = "1.0.44", optional = true }
[features] [features]
default = ["macro", "primitives"] default = ["macro", "primitives"]
macro = [] macro = []
static = ["lazy_static"]
array = ["serde_json"] array = ["serde_json"]

View file

@ -30,14 +30,16 @@ config! {
), ),
APP { APP {
static BASE_URL => "/api", // &'static str by default
ARTICLE { ARTICLE {
PER_PAGE: u32 => 15, static PER_PAGE: u32 => 15,
} }
#[cfg(feature = "companies")] #[cfg(feature = "companies")]
COMPANY { COMPANY {
#[env_name = "INSTITUTIONS_PER_PAGE"] #[env_name = "INSTITUTIONS_PER_PAGE"]
PER_PAGE: u32 => 15, static PER_PAGE: u32 => 15,
} }
} }
@ -98,29 +100,30 @@ fn main() {
## Available features ## Available features
* default = ["macro", "primitives"] * **default** - ["macro", "primitives"]
* macro = [] * **macro** - Activates `config!` macros for easy configure web application.
* array = ["serde_json"] * **static** - Add `static` option to `config!` macros (uses optional `lazy_static` package).
* primitives = ["numbers", "bool"] * **array** - Add EnvString impl for vector type (uses optional `serde_json` package).
* numbers = ["int", "uint", "float"] * **primitives** - Group for features: `numbers` and `bool`.
* int = ["i8", "i16", "i32", "i64", "i128", "isize"] * **numbers** - Group for features: `int`, `uint` and `float`.
* uint = ["u8", "u16", "u32", "u64", "u128", "usize"] * **int** - Group for features: `i8`, `i16`, `i32`, `i64`, `i128` and `isize`.
* float = ["f32", "f64"] * **uint** - Group for features: `u8`, `u16`, `u32`, `u64`, `u128` and `usize`.
* i8 = [] * **float** - Group for features: `f32` and `f64`
* i16 = [] * **i8** - impl EnvString for i8 type
* i32 = [] * **i16** - impl EnvString for i16 type
* i64 = [] * **i32** - impl EnvString for i32 type
* i128 = [] * **i64** - impl EnvString for i64 type
* isize = [] * **i128** - impl EnvString for i128 type
* u8 = [] * **isize** - impl EnvString for isize type
* u16 = [] * **u8** - impl EnvString for u8 type
* u32 = [] * **u16** - impl EnvString for u16 type
* u64 = [] * **u32** - impl EnvString for u32 type
* u128 = [] * **u64** - impl EnvString for u64 type
* usize = [] * **u128** - impl EnvString for u128 type
* f32 = [] * **usize** - impl EnvString for usize type
* f64 = [] * **f32** - impl EnvString for f32 type
* bool = [] * **f64** - impl EnvString for f64 type
* **bool** - impl EnvString for bool type
## License ## License

View file

@ -76,6 +76,7 @@ impl FromEnvString for bool {
#[cfg(feature = "array")] #[cfg(feature = "array")]
#[derive(Debug)]
pub enum ArrayEnvError { pub enum ArrayEnvError {
InvalidType, InvalidType,
FailedToParse, FailedToParse,
@ -119,6 +120,15 @@ impl FromEnvString for String {
} }
impl FromEnvString for &'static str {
type Err = ();
fn from_env_string(s: &EnvString) -> Result<Self, Self::Err> {
Ok(Box::leak(s.0.clone().into_boxed_str()))
}
}
#[doc(hidden)] #[doc(hidden)]
#[derive(Debug, PartialEq, Clone)] #[derive(Debug, PartialEq, Clone)]
pub struct EnvString(String); pub struct EnvString(String);

View file

@ -35,14 +35,16 @@
//! ), //! ),
//! //!
//! APP { //! APP {
//! static BASE_URL => "/api", // &'static str by default
//!
//! ARTICLE { //! ARTICLE {
//! PER_PAGE: u32 => 15, //! static PER_PAGE: u32 => 15,
//! } //! }
//! //!
//! #[cfg(feature = "companies")] //! #[cfg(feature = "companies")]
//! COMPANY { //! COMPANY {
//! #[env_name = "INSTITUTIONS_PER_PAGE"] //! #[env_name = "INSTITUTIONS_PER_PAGE"]
//! PER_PAGE: u32 => 15, //! static PER_PAGE: u32 => 15,
//! } //! }
//! } //! }
//! //!
@ -62,6 +64,7 @@
//! cfg::init(); //! cfg::init();
//! assert_eq!(cfg::HOST(), String::from("127.0.0.1")); //! assert_eq!(cfg::HOST(), String::from("127.0.0.1"));
//! assert_eq!(cfg::DATABASE_URL(), String::from("postgres://user:pass@localhost:5432/test")); //! assert_eq!(cfg::DATABASE_URL(), String::from("postgres://user:pass@localhost:5432/test"));
//! assert_eq!(cfg::APP::BASE_URL(), "/api");
//! assert_eq!(cfg::APP::ARTICLE::PER_PAGE(), 15); //! assert_eq!(cfg::APP::ARTICLE::PER_PAGE(), 15);
//! assert_eq!(cfg::FEATURE::NEW_MENU(), true); //! assert_eq!(cfg::FEATURE::NEW_MENU(), true);
//! } //! }
@ -84,15 +87,50 @@
//! } //! }
//! ``` //! ```
//! //!
//! ## Available features
//!
//! * **default** - ["macro", "primitives"]
//! * **macro** - Activates `config!` macros for easy configure web application.
//! * **static** - Add `static` option to `config!` macros (uses optional `lazy_static` package).
//! * **array** - Add EnvString impl for vector type (uses optional `serde_json` package).
//! * **primitives** - Group for features: `numbers` and `bool`.
//! * **numbers** - Group for features: `int`, `uint` and `float`.
//! * **int** - Group for features: `i8`, `i16`, `i32`, `i64`, `i128` and `isize`.
//! * **uint** - Group for features: `u8`, `u16`, `u32`, `u64`, `u128` and `usize`.
//! * **float** - Group for features: `f32` and `f64`
//! * **i8** - impl EnvString for i8 type
//! * **i16** - impl EnvString for i16 type
//! * **i32** - impl EnvString for i32 type
//! * **i64** - impl EnvString for i64 type
//! * **i128** - impl EnvString for i128 type
//! * **isize** - impl EnvString for isize type
//! * **u8** - impl EnvString for u8 type
//! * **u16** - impl EnvString for u16 type
//! * **u32** - impl EnvString for u32 type
//! * **u64** - impl EnvString for u64 type
//! * **u128** - impl EnvString for u128 type
//! * **usize** - impl EnvString for usize type
//! * **f32** - impl EnvString for f32 type
//! * **f64** - impl EnvString for f64 type
//! * **bool** - impl EnvString for bool type
//!a
// Rustc lints. // Rustc lints.
#![deny(unused_imports)] #![deny(
missing_debug_implementations,
unsafe_code,
unstable_features,
unused_imports,
unused_qualifications,
)]
///////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////
#[macro_use] #[macro_use]
extern crate failure; extern crate failure;
#[cfg(feature = "static")]
extern crate lazy_static;
mod enverr; mod enverr;
mod getenv; mod getenv;
@ -108,7 +146,7 @@ pub mod prelude {
#[cfg(feature = "macro")] #[cfg(feature = "macro")]
#[allow(unused_imports)] //#[allow(unused_imports)]
#[macro_use] #[macro_use]
mod r#macro; mod r#macro;
#[cfg(feature = "macro")] #[cfg(feature = "macro")]

View file

@ -203,6 +203,49 @@
/// cfg::init(); /// cfg::init();
/// ``` /// ```
/// ///
/// Static
/// ------
///
/// `with feauter = "static"`
///
/// Starting with 0.11 version you can use lazy static for improve speed of variable. This is very
/// useful, if you use variable more than once.
///
/// ```rust
/// # #[macro_use] extern crate itconfig;
/// # use std::env;
/// env::set_var("APP_BASE_URL", "/api/v1");
///
/// config! {
/// static APP_BASE_URL => "/api",
/// }
///
/// cfg::init();
/// assert_eq!(cfg::APP_BASE_URL(), "/api/v1");
/// ```
///
/// You also can use static with concat variables
///
/// ```rust
/// # #[macro_use] extern crate itconfig;
/// config! {
/// static CONNECTION_STRING < (
/// "postgres://",
/// NOT_DEFINED_PG_USERNAME => "user",
/// ":",
/// NOT_DEFINED_PG_PASSWORD => "pass",
/// "@",
/// NOT_DEFINED_PG_HOST => "localhost:5432",
/// "/",
/// NOT_DEFINED_PG_DB => "test",
/// ),
/// }
///
/// cfg::init();
/// assert_eq!(cfg::CONNECTION_STRING(), "postgres://user:pass@localhost:5432/test".to_string());
/// ```
///
///
/// --- /// ---
/// ///
/// This module will also contain helper method: /// This module will also contain helper method:
@ -258,6 +301,14 @@ macro_rules! __itconfig_invalid_syntax {
`https://docs.rs/itconfig/latest/itconfig/macro.config.html`" `https://docs.rs/itconfig/latest/itconfig/macro.config.html`"
); );
}; };
(feature "static") => {
compile_error!(
"Feature `static` is required for enable this macro function.\
Please see the `config!` macro docs for more info.\
`https://docs.rs/itconfig/latest/itconfig/macro.config.html`"
);
};
} }
#[macro_export] #[macro_export]
@ -301,6 +352,14 @@ macro_rules! __itconfig_parse_module {
} }
#[macro_export]
#[doc(hidden)]
macro_rules! __itconfig_get_ty_or_default {
() => { &'static str };
($ty:ty) => { $ty };
}
#[macro_export] #[macro_export]
#[doc(hidden)] #[doc(hidden)]
macro_rules! __itconfig_parse_variables { macro_rules! __itconfig_parse_variables {
@ -329,6 +388,34 @@ macro_rules! __itconfig_parse_variables {
} }
}; };
// Find static concatenated variable
(
tokens = [
$(#$meta:tt)*
static $name:ident < ($($inner:tt)+),
$($rest:tt)*
],
$($args:tt)*
) => {
#[cfg(feature = "static")]
__itconfig_parse_variables! {
current_variable = {
unparsed_meta = [$(#$meta)*],
meta = [],
unparsed_concat = [$($inner)+],
concat = [],
name = $name,
ty = String,
is_static = true,
},
tokens = [$($rest)*],
$($args)*
}
#[cfg(not(feature = "static"))]
__itconfig_invalid_syntax!(feature "static");
};
// Find concatenated variable // Find concatenated variable
( (
tokens = [ tokens = [
@ -346,17 +433,47 @@ macro_rules! __itconfig_parse_variables {
concat = [], concat = [],
name = $name, name = $name,
ty = String, ty = String,
is_static = false,
}, },
tokens = [$($rest)*], tokens = [$($rest)*],
$($args)* $($args)*
} }
}; };
// Find static variable
(
tokens = [
$(#$meta:tt)*
static $name:ident $(: $ty:ty)? $(=> $default:expr)?,
$($rest:tt)*
],
$($args:tt)*
) => {
#[cfg(feature = "static")]
__itconfig_parse_variables! {
current_variable = {
unparsed_meta = [$(#$meta)*],
meta = [],
unparsed_concat = [],
concat = [],
name = $name,
ty = __itconfig_get_ty_or_default!($($ty)?),
is_static = true,
$(default = $default,)?
},
tokens = [$($rest)*],
$($args)*
}
#[cfg(not(feature = "static"))]
__itconfig_invalid_syntax!(feature "static");
};
// Find variable // Find variable
( (
tokens = [ tokens = [
$(#$meta:tt)* $(#$meta:tt)*
$name:ident : $ty:ty$( => $default:expr)?, $name:ident $(: $ty:ty)? $(=> $default:expr)?,
$($rest:tt)* $($rest:tt)*
], ],
$($args:tt)* $($args:tt)*
@ -368,7 +485,8 @@ macro_rules! __itconfig_parse_variables {
unparsed_concat = [], unparsed_concat = [],
concat = [], concat = [],
name = $name, name = $name,
ty = $ty, ty = __itconfig_get_ty_or_default!($($ty)?),
is_static = false,
$(default = $default,)? $(default = $default,)?
}, },
tokens = [$($rest)*], tokens = [$($rest)*],
@ -523,6 +641,9 @@ macro_rules! __itconfig_impl_namespace {
meta = $var_meta:tt, meta = $var_meta:tt,
concat = $var_concat:tt, concat = $var_concat:tt,
name = $var_name:ident, name = $var_name:ident,
$(env_name = $env_name:expr,)?
ty = $ty:ty,
is_static = $is_static:ident,
$($variable:tt)* $($variable:tt)*
},)*], },)*],
namespaces = [$({ namespaces = [$({
@ -543,6 +664,8 @@ macro_rules! __itconfig_impl_namespace {
$(#$meta)* $(#$meta)*
pub mod $mod_name { pub mod $mod_name {
#![allow(non_snake_case)] #![allow(non_snake_case)]
#[cfg(feature = "static")]
use lazy_static::lazy_static;
$(__itconfig_impl_namespace! { $(__itconfig_impl_namespace! {
variables = $ns_variable, variables = $ns_variable,
@ -567,6 +690,9 @@ macro_rules! __itconfig_impl_namespace {
concat = $var_concat, concat = $var_concat,
name = $var_name, name = $var_name,
env_prefix = $env_prefix, env_prefix = $env_prefix,
$(env_name = $env_name,)?
ty = $ty,
is_static = $is_static,
$($variable)* $($variable)*
})* })*
} }
@ -630,37 +756,74 @@ macro_rules! __itconfig_variable {
// Add method for env variable // Add method for env variable
( (
meta = [$(#$meta:tt,)*], meta = $meta:tt,
concat = $concat:tt, concat = $concat:tt,
name = $name:ident, name = $name:ident,
env_prefix = $env_prefix:expr, env_prefix = $env_prefix:expr,
env_name = $env_name:expr, env_name = $env_name:expr,
ty = $ty:ty, ty = $ty:ty,
is_static = $is_static:ident,
$(default = $default:expr,)? $(default = $default:expr,)?
) => { ) => {
$(#$meta)* __itconfig_variable!(
pub fn $name() -> $ty { @wrap
__itconfig_variable! { is_static = $is_static,
meta = $meta,
name = $name,
ty = $ty,
value = __itconfig_variable!(
@inner @inner
concat = $concat, concat = $concat,
env_name = $env_name, env_name = $env_name,
$(default = $default,)? $(default = $default,)?
} ),
} );
}; };
// Wrap static variables
(
@wrap
is_static = true,
meta = [$(#$meta:tt,)*],
name = $name:ident,
ty = $ty:ty,
value = $value:expr,
) => (
$(#$meta)*
pub fn $name() -> $ty {
lazy_static! {
static ref $name: $ty = $value;
}
(*$name).clone()
}
);
// Wrap functions
(
@wrap
is_static = false,
meta = [$(#$meta:tt,)*],
name = $name:ident,
ty = $ty:ty,
value = $value:expr,
) => (
$(#$meta)*
pub fn $name() -> $ty { $value }
);
// Concatenate function body // Concatenate function body
( (
@inner @inner
concat = [$($concat:expr,)+], concat = [$($concat:expr,)+],
env_name = $env_name:expr, env_name = $env_name:expr,
$($args:tt)* $($args:tt)*
) => ( ) => ({
let value_parts: Vec<String> = vec!($($concat),+); let value_parts: Vec<String> = vec!($($concat),+);
let value = value_parts.join(""); let value = value_parts.join("");
std::env::set_var($env_name, value.as_str()); std::env::set_var($env_name, value.as_str());
value value
); });
// Env without default // Env without default
( (