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:
- |
rustc --version &&
cargo test
cargo test --all-features
matrix:
allow_failures:
- rust: nightly

View file

@ -43,14 +43,16 @@ config! {
),
APP {
static BASE_URL => "/api", // &'static str by default
ARTICLE {
PER_PAGE: u32 => 15,
static PER_PAGE: u32 => 15,
}
#[cfg(feature = "companies")]
COMPANY {
#[env_name = "INSTITUTIONS_PER_PAGE"]
PER_PAGE: u32 => 15,
static PER_PAGE: u32 => 15,
}
}
@ -117,30 +119,30 @@ cargo test
## Available features
* default = ["macro", "primitives"]
* macro = []
* array = ["serde_json"]
* primitives = ["numbers", "bool"]
* numbers = ["int", "uint", "float"]
* int = ["i8", "i16", "i32", "i64", "i128", "isize"]
* uint = ["u8", "u16", "u32", "u64", "u128", "usize"]
* float = ["f32", "f64"]
* i8 = []
* i16 = []
* i32 = []
* i64 = []
* i128 = []
* isize = []
* u8 = []
* u16 = []
* u32 = []
* u64 = []
* u128 = []
* usize = []
* f32 = []
* f64 = []
* bool = []
* **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
## License

View file

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

View file

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

View file

@ -422,3 +422,51 @@ fn concatenated_environment_variable_in_namespace() {
);
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]
name = "itconfig"
version = "0.10.2"
version = "0.11.0"
authors = ["Dmitriy Pleshevskiy <dmitriy@ideascup.me>"]
description = "Easy build a configs from environment variables and use it in globally."
categories = ["config", "web-programming"]
@ -16,11 +16,14 @@ readme = "README.md"
[dependencies]
failure = { version = "0.1.6", features = ["derive"]}
lazy_static = { version = "1.4.0", optional = true }
serde_json = { version = "1.0.44", optional = true }
[features]
default = ["macro", "primitives"]
macro = []
static = ["lazy_static"]
array = ["serde_json"]

View file

@ -30,14 +30,16 @@ config! {
),
APP {
static BASE_URL => "/api", // &'static str by default
ARTICLE {
PER_PAGE: u32 => 15,
static PER_PAGE: u32 => 15,
}
#[cfg(feature = "companies")]
COMPANY {
#[env_name = "INSTITUTIONS_PER_PAGE"]
PER_PAGE: u32 => 15,
static PER_PAGE: u32 => 15,
}
}
@ -98,29 +100,30 @@ fn main() {
## Available features
* default = ["macro", "primitives"]
* macro = []
* array = ["serde_json"]
* primitives = ["numbers", "bool"]
* numbers = ["int", "uint", "float"]
* int = ["i8", "i16", "i32", "i64", "i128", "isize"]
* uint = ["u8", "u16", "u32", "u64", "u128", "usize"]
* float = ["f32", "f64"]
* i8 = []
* i16 = []
* i32 = []
* i64 = []
* i128 = []
* isize = []
* u8 = []
* u16 = []
* u32 = []
* u64 = []
* u128 = []
* usize = []
* f32 = []
* f64 = []
* bool = []
* **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
## License

View file

@ -76,6 +76,7 @@ impl FromEnvString for bool {
#[cfg(feature = "array")]
#[derive(Debug)]
pub enum ArrayEnvError {
InvalidType,
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)]
#[derive(Debug, PartialEq, Clone)]
pub struct EnvString(String);

View file

@ -35,14 +35,16 @@
//! ),
//!
//! APP {
//! static BASE_URL => "/api", // &'static str by default
//!
//! ARTICLE {
//! PER_PAGE: u32 => 15,
//! static PER_PAGE: u32 => 15,
//! }
//!
//! #[cfg(feature = "companies")]
//! COMPANY {
//! #[env_name = "INSTITUTIONS_PER_PAGE"]
//! PER_PAGE: u32 => 15,
//! static PER_PAGE: u32 => 15,
//! }
//! }
//!
@ -62,6 +64,7 @@
//! cfg::init();
//! 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::APP::BASE_URL(), "/api");
//! assert_eq!(cfg::APP::ARTICLE::PER_PAGE(), 15);
//! 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.
#![deny(unused_imports)]
#![deny(
missing_debug_implementations,
unsafe_code,
unstable_features,
unused_imports,
unused_qualifications,
)]
/////////////////////////////////////////////////////////////////////////////
#[macro_use]
extern crate failure;
#[cfg(feature = "static")]
extern crate lazy_static;
mod enverr;
mod getenv;
@ -108,7 +146,7 @@ pub mod prelude {
#[cfg(feature = "macro")]
#[allow(unused_imports)]
//#[allow(unused_imports)]
#[macro_use]
mod r#macro;
#[cfg(feature = "macro")]

View file

@ -203,6 +203,49 @@
/// 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:
@ -258,6 +301,14 @@ macro_rules! __itconfig_invalid_syntax {
`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]
@ -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]
#[doc(hidden)]
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
(
tokens = [
@ -346,17 +433,47 @@ macro_rules! __itconfig_parse_variables {
concat = [],
name = $name,
ty = String,
is_static = false,
},
tokens = [$($rest)*],
$($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
(
tokens = [
$(#$meta:tt)*
$name:ident : $ty:ty$( => $default:expr)?,
$name:ident $(: $ty:ty)? $(=> $default:expr)?,
$($rest:tt)*
],
$($args:tt)*
@ -368,7 +485,8 @@ macro_rules! __itconfig_parse_variables {
unparsed_concat = [],
concat = [],
name = $name,
ty = $ty,
ty = __itconfig_get_ty_or_default!($($ty)?),
is_static = false,
$(default = $default,)?
},
tokens = [$($rest)*],
@ -523,6 +641,9 @@ macro_rules! __itconfig_impl_namespace {
meta = $var_meta:tt,
concat = $var_concat:tt,
name = $var_name:ident,
$(env_name = $env_name:expr,)?
ty = $ty:ty,
is_static = $is_static:ident,
$($variable:tt)*
},)*],
namespaces = [$({
@ -543,6 +664,8 @@ macro_rules! __itconfig_impl_namespace {
$(#$meta)*
pub mod $mod_name {
#![allow(non_snake_case)]
#[cfg(feature = "static")]
use lazy_static::lazy_static;
$(__itconfig_impl_namespace! {
variables = $ns_variable,
@ -567,6 +690,9 @@ macro_rules! __itconfig_impl_namespace {
concat = $var_concat,
name = $var_name,
env_prefix = $env_prefix,
$(env_name = $env_name,)?
ty = $ty,
is_static = $is_static,
$($variable)*
})*
}
@ -630,37 +756,74 @@ macro_rules! __itconfig_variable {
// Add method for env variable
(
meta = [$(#$meta:tt,)*],
meta = $meta:tt,
concat = $concat:tt,
name = $name:ident,
env_prefix = $env_prefix:expr,
env_name = $env_name:expr,
ty = $ty:ty,
is_static = $is_static:ident,
$(default = $default:expr,)?
) => {
$(#$meta)*
pub fn $name() -> $ty {
__itconfig_variable! {
__itconfig_variable!(
@wrap
is_static = $is_static,
meta = $meta,
name = $name,
ty = $ty,
value = __itconfig_variable!(
@inner
concat = $concat,
env_name = $env_name,
$(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
(
@inner
concat = [$($concat:expr,)+],
env_name = $env_name:expr,
$($args:tt)*
) => (
) => ({
let value_parts: Vec<String> = vec!($($concat),+);
let value = value_parts.join("");
std::env::set_var($env_name, value.as_str());
value
);
});
// Env without default
(