From 0b3087a8cbe6c0b9428d33c3a2c92155a3bbc558 Mon Sep 17 00:00:00 2001 From: Ryan Leckey Date: Fri, 27 Jan 2017 11:19:36 -0800 Subject: Use RWLock on the global config instance --- src/lib.rs | 32 +++++++++++++++++++------------- 1 file changed, 19 insertions(+), 13 deletions(-) (limited to 'src') diff --git a/src/lib.rs b/src/lib.rs index 0fa3d70..ad527e2 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -14,7 +14,7 @@ mod env; mod config; use std::error::Error; -use std::sync::{Once, ONCE_INIT}; +use std::sync::{Once, ONCE_INIT, RwLock}; pub use source::{Source, SourceBuilder}; pub use file::{File, FileFormat}; @@ -25,11 +25,11 @@ pub use value::Value; pub use config::Config; // Global configuration -static mut CONFIG: Option = None; +static mut CONFIG: Option> = None; static CONFIG_INIT: Once = ONCE_INIT; // Get the global configuration instance -fn global() -> &'static mut Config { +fn global() -> &'static RwLock { unsafe { CONFIG_INIT.call_once(|| { CONFIG = Some(Default::default()); }); @@ -40,37 +40,43 @@ fn global() -> &'static mut Config { pub fn merge(source: T) -> Result<(), Box> where T: SourceBuilder { - global().merge(source) + global().write()?.merge(source) } -pub fn set_default(key: &str, value: T) +pub fn set_default(key: &str, value: T) -> Result<(), Box> where T: Into { - global().set_default(key, value) + global().write()?.set_default(key, value); + + // TODO: `set_default` will be able to fail soon so this will not be needed + Ok(()) } -pub fn set(key: &str, value: T) +pub fn set(key: &str, value: T) -> Result<(), Box> where T: Into { - global().set(key, value) + global().write()?.set(key, value); + + // TODO: `set_default` will be able to fail soon so this will not be needed + Ok(()) } pub fn get(key: &str) -> Option { - global().get(key) + global().read().unwrap().get(key) } pub fn get_str(key: &str) -> Option { - global().get_str(key) + global().read().unwrap().get_str(key) } pub fn get_int(key: &str) -> Option { - global().get_int(key) + global().read().unwrap().get_int(key) } pub fn get_float(key: &str) -> Option { - global().get_float(key) + global().read().unwrap().get_float(key) } pub fn get_bool(key: &str) -> Option { - global().get_bool(key) + global().read().unwrap().get_bool(key) } -- cgit v1.2.3