diff options
Diffstat (limited to 'src/util')
-rw-r--r-- | src/util/mod.rs | 7 | ||||
-rw-r--r-- | src/util/promise.rs | 160 | ||||
-rw-r--r-- | src/util/static_cfg.rs | 147 | ||||
-rw-r--r-- | src/util/template.rs | 362 | ||||
-rw-r--r-- | src/util/trait_impls.rs | 17 |
5 files changed, 0 insertions, 693 deletions
diff --git a/src/util/mod.rs b/src/util/mod.rs deleted file mode 100644 index dd5087a55558..000000000000 --- a/src/util/mod.rs +++ /dev/null @@ -1,7 +0,0 @@ -#[macro_use] -pub mod static_cfg; -#[macro_use] -pub mod template; -pub mod promise; -#[macro_use] -pub mod trait_impls; diff --git a/src/util/promise.rs b/src/util/promise.rs deleted file mode 100644 index 22f1e8b47f58..000000000000 --- a/src/util/promise.rs +++ /dev/null @@ -1,160 +0,0 @@ -use std::future::Future; -use std::pin::Pin; -use std::sync::{Arc, RwLock}; -use std::task::{Context, Poll, Waker}; - -type Waiter<Env, T> = Box<dyn Fn(&mut Env, &T)>; - -pub struct Promise<Env, T> { - inner: Arc<RwLock<Inner<T>>>, - waiters: Arc<RwLock<Vec<Waiter<Env, T>>>>, -} - -pub struct Complete<T> { - inner: Arc<RwLock<Inner<T>>>, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Cancelled; - -struct Inner<T> { - value: Option<Arc<T>>, - waker: Option<Waker>, -} - -pub fn promise<Env, T>() -> (Complete<T>, Promise<Env, T>) { - let inner = Arc::new(RwLock::new(Inner { - value: None, - waker: None, - })); - let promise = Promise { - inner: inner.clone(), - waiters: Arc::new(RwLock::new(Vec::new())), - }; - let complete = Complete { inner }; - (complete, promise) -} - -impl<T> Complete<T> { - pub fn fulfill(&self, val: T) { - let mut inner = self.inner.write().unwrap(); - inner.value = Some(Arc::new(val)); - if let Some(waker) = inner.waker.take() { - waker.wake() - } - } -} - -impl<T> Complete<Result<T, Cancelled>> { - pub fn cancel(&mut self) { - self.fulfill(Err(Cancelled)) - } -} - -impl<E, T> Complete<Result<T, E>> { - pub fn ok(&mut self, val: T) { - self.fulfill(Ok(val)) - } - - pub fn err(&mut self, e: E) { - self.fulfill(Err(e)) - } -} - -impl<Env, T> Promise<Env, T> { - pub fn on_fulfill<F: Fn(&mut Env, &T) + 'static>(&mut self, f: F) { - let mut waiters = self.waiters.write().unwrap(); - waiters.push(Box::new(f)); - } -} - -impl<Env, T> Promise<Env, Result<T, Cancelled>> { - pub fn on_cancel<F: Fn(&mut Env) + 'static>(&mut self, f: F) { - self.on_err(move |env, _| f(env)) - } -} - -impl<Env, E, T> Promise<Env, Result<T, E>> { - pub fn on_ok<F: Fn(&mut Env, &T) + 'static>(&mut self, f: F) { - self.on_fulfill(move |env, r| { - if let Ok(val) = r { - f(env, val) - } - }) - } - - pub fn on_err<F: Fn(&mut Env, &E) + 'static>(&mut self, f: F) { - self.on_fulfill(move |env, r| { - if let Err(e) = r { - f(env, e) - } - }) - } -} - -pub trait Give<Env> { - fn give(&self, env: &mut Env) -> bool; -} - -impl<Env, T> Give<Env> for Promise<Env, T> { - fn give(&self, env: &mut Env) -> bool { - let inner = self.inner.read().unwrap(); - if let Some(value) = &inner.value { - let mut waiters = self.waiters.write().unwrap(); - for waiter in waiters.iter() { - waiter(env, value); - } - waiters.clear(); - true - } else { - false - } - } -} - -impl<Env, T> Clone for Promise<Env, T> { - fn clone(&self) -> Self { - Promise { - inner: self.inner.clone(), - waiters: self.waiters.clone(), - } - } -} - -impl<Env, P: Give<Env>> Give<Env> for &P { - fn give(&self, env: &mut Env) -> bool { - (*self).give(env) - } -} - -impl<Env, T> Future for Promise<Env, T> { - type Output = Arc<T>; - fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { - let mut inner = self.inner.write().unwrap(); - match inner.value { - Some(ref v) => Poll::Ready(v.clone()), - None => { - inner.waker = Some(cx.waker().clone()); - Poll::Pending - } - } - } -} - -pub struct Promises<'a, Env> { - ps: Vec<Box<dyn Give<Env> + 'a>>, -} - -impl<'a, Env> Promises<'a, Env> { - pub fn new() -> Self { - Promises { ps: Vec::new() } - } - - pub fn push(&mut self, p: Box<dyn Give<Env> + 'a>) { - self.ps.push(p); - } - - pub fn give_all(&mut self, env: &mut Env) { - self.ps.retain(|p| !p.give(env)); - } -} diff --git a/src/util/static_cfg.rs b/src/util/static_cfg.rs deleted file mode 100644 index b20456fb3bd4..000000000000 --- a/src/util/static_cfg.rs +++ /dev/null @@ -1,147 +0,0 @@ -use include_dir::Dir; -use serde::de; - -macro_rules! __static_cfg_include { - (toml_file, $filename:expr) => { - include_str!($filename) - }; - (toml_dir, $filename:expr) => { - include_dir!($filename) - }; - (json_file, $filename:expr) => { - include_str!($filename) - }; - (json_dir, $filename:expr) => { - include_dir!($filename) - }; - (cfg_dir, $filename:expr) => { - include_dir!($filename) - }; -} - -macro_rules! __static_cfg_type { - (toml_file) => (&'static str); - (json_file) => (&'static str); - (toml_dir) => (include_dir::Dir<'static>); - (json_dir) => (include_dir::Dir<'static>); - (cfg_dir) => (include_dir::Dir<'static>); -} - -macro_rules! __static_cfg_parse { - (toml_file, $e:expr) => { - toml::from_str($e).unwrap() - }; - - (json_file, $e:expr) => { - serde_json::from_str($e).unwrap() - }; - - (toml_dir, $e:expr) => { - crate::util::static_cfg::parse_toml_dir($e) - }; - - (json_dir, $e:expr) => { - crate::util::static_cfg::parse_json_dir($e) - }; - - (cfg_dir, $e:expr) => { - crate::util::static_cfg::parse_cfg_dir($e); - }; -} - -macro_rules! __static_cfg_inner { - ($(#[$attr:meta])* ($($vis:tt)*) static ref $N:ident : $T:ty = $kind:ident($filename:expr); $($t:tt)*) => { - // static RAW: &'static str = __static_cfg_include!($kind, $filename); - static RAW: __static_cfg_type!($kind) = __static_cfg_include!($kind, $filename); - lazy_static! { - $(#[$attr])* static ref $N: $T = __static_cfg_parse!($kind, RAW); - } - - static_cfg!($($t)*); - } -} - -#[macro_export] -macro_rules! static_cfg { - ($(#[$attr:meta])* static ref $N:ident : $T:ty = $kind:ident($filename:expr); $($t:tt)*) => { - __static_cfg_inner!($(#[$attr])* () static ref $N : $T = $kind($filename); $($t)*); - }; - - ($(#[$attr:meta])* pub static ref $N:ident : $T:ty = $kind:ident($filename:expr); $($t:tt)*) => { - __static_cfg_inner!($(#[$attr])* (pub) static ref $N : $T = $kind($filename); $($t)*); - }; - - ($(#[$attr:meta])* pub ($($vis:tt)+) static ref $N:ident : $T:ty = $kind:ident($filename:expr); $($t:tt)*) => { - __static_cfg_inner!($(#[$attr])* (pub ($($vis)+)) static ref $N : $T = $kind($filename); $($t)*); - }; - - () => () -} - -pub fn parse_cfg_dir<'a, T>(d: Dir<'a>) -> Vec<T> -where - T: de::Deserialize<'a>, -{ - d.files() - .iter() - .filter_map(|f| { - let path = f.path(); - let contents = f.contents_utf8().unwrap(); - match path.extension().and_then(|e| e.to_str()) { - Some("toml") => { - Some(toml::from_str(contents).unwrap_or_else(|e| { - panic!( - "Error parsing TOML file {}: {}", - path.display(), - e - ) - })) - } - Some("json") => { - Some(serde_json::from_str(contents).unwrap_or_else(|e| { - panic!( - "Error parsing JSON file {}: {}", - path.display(), - e - ) - })) - } - // > YAML currently does not support zero-copy deserialization - // Some("yaml") => { - // Some(serde_yaml::from_str(contents).unwrap_or_else(|e| { - // panic!( - // "Error parsing YAML file {}: {}", - // path.display(), - // e - // ) - // })) - // } - _ => None, - } - }) - .collect() -} - -pub fn parse_toml_dir<'a, T>(d: Dir<'a>) -> Vec<T> -where - T: de::Deserialize<'a>, -{ - d.files() - .iter() - .map(|f| { - toml::from_str(f.contents_utf8().unwrap()).unwrap_or_else(|e| { - panic!("Error parsing TOML file {}: {}", f.path, e) - }) - }) - .collect() -} - -pub fn parse_json_dir<'a, T>(d: Dir<'a>) -> Vec<T> -where - T: de::Deserialize<'a>, -{ - d.files() - .iter() - .map(|f| serde_json::from_str(f.contents_utf8().unwrap()).unwrap()) - .collect() -} diff --git a/src/util/template.rs b/src/util/template.rs deleted file mode 100644 index bb77f9b4d610..000000000000 --- a/src/util/template.rs +++ /dev/null @@ -1,362 +0,0 @@ -use nom::combinator::rest; -use nom::error::ErrorKind; -use nom::{Err, IResult}; -use std::collections::HashMap; -use std::fmt::{self, Display}; -use std::marker::PhantomData; - -#[derive(Debug, PartialEq, Eq, Clone)] -pub struct Path<'a> { - head: &'a str, - tail: Vec<&'a str>, -} - -impl<'a> Path<'a> { - fn new(head: &'a str, tail: Vec<&'a str>) -> Self { - Path { head, tail } - } -} - -impl<'a> Display for Path<'a> { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}", self.head)?; - for part in &self.tail { - write!(f, ".{}", part)?; - } - Ok(()) - } -} - -// named!(path_ident, map_res!(is_not!(".}"), std::str::from_utf8)); -fn path_ident<'a>(input: &'a str) -> IResult<&'a str, &'a str> { - take_till!(input, |c| c == '.' || c == '}') -} - -fn path<'a>(input: &'a str) -> IResult<&'a str, Path<'a>> { - map!( - input, - tuple!( - path_ident, - many0!(complete!(preceded!(char!('.'), path_ident))) - ), - |(h, t)| Path::new(h, t) - ) -} - -#[derive(Debug, PartialEq, Eq, Clone)] -pub enum TemplateToken<'a> { - Literal(&'a str), - Substitution(Path<'a>), -} - -fn token_substitution<'a>( - input: &'a str, -) -> IResult<&'a str, TemplateToken<'a>> { - map!( - input, - delimited!(tag!("{{"), path, tag!("}}")), - TemplateToken::Substitution - ) -} - -fn template_token<'a>(input: &'a str) -> IResult<&'a str, TemplateToken<'a>> { - alt!( - input, - token_substitution - | map!( - alt!(complete!(take_until!("{{")) | complete!(rest)), - TemplateToken::Literal - ) - ) -} - -#[derive(Debug, PartialEq, Eq, Clone)] -pub struct Template<'a> { - tokens: Vec<TemplateToken<'a>>, -} - -impl<'a> Template<'a> { - pub fn new(tokens: Vec<TemplateToken<'a>>) -> Self { - Template { tokens } - } -} - -pub struct TemplateVisitor<'a> { - marker: PhantomData<fn() -> Template<'a>>, -} - -impl<'a> TemplateVisitor<'a> { - pub fn new() -> Self { - TemplateVisitor { - marker: PhantomData, - } - } -} - -impl<'a> serde::de::Visitor<'a> for TemplateVisitor<'a> { - type Value = Template<'a>; - - fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { - formatter.write_str("a valid template string") - } - - fn visit_borrowed_str<E: serde::de::Error>( - self, - v: &'a str, - ) -> Result<Self::Value, E> { - Template::parse(v).map_err(|_| { - serde::de::Error::invalid_value( - serde::de::Unexpected::Str(v), - &"a valid template string", - ) - }) - } -} - -impl<'a> serde::Deserialize<'a> for Template<'a> { - fn deserialize<D: serde::Deserializer<'a>>( - deserializer: D, - ) -> Result<Self, D::Error> { - deserializer.deserialize_str(TemplateVisitor::new()) - } -} - -impl<'a> Template<'a> { - pub fn parse( - input: &'a str, - ) -> Result<Template<'a>, Err<(&'a str, ErrorKind)>> { - let (remaining, res) = template(input)?; - if !remaining.is_empty() { - unreachable!(); - } - Ok(res) - } - - pub fn format( - &self, - params: &TemplateParams<'a>, - ) -> Result<String, TemplateError<'a>> { - use TemplateToken::*; - let mut res = String::new(); - for token in &self.tokens { - match token { - Literal(s) => res.push_str(s), - Substitution(p) => match params.get(p.clone()) { - Some(s) => res.push_str(s), - None => return Err(TemplateError::MissingParam(p.clone())), - }, - } - } - Ok(res) - } -} - -#[derive(Debug, PartialEq, Eq)] -pub enum TemplateError<'a> { - MissingParam(Path<'a>), -} - -impl<'a> Display for TemplateError<'a> { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - use TemplateError::*; - match self { - MissingParam(path) => { - write!(f, "Missing template parameter: {}", path) - } - } - } -} - -#[derive(Debug, PartialEq, Eq)] -pub enum TemplateParams<'a> { - Direct(&'a str), - Nested(HashMap<&'a str, TemplateParams<'a>>), -} - -impl<'a> TemplateParams<'a> { - fn get(&self, path: Path<'a>) -> Option<&'a str> { - use TemplateParams::*; - match self { - Direct(_) => None, - Nested(m) => m.get(path.head).and_then(|next| { - if path.tail.is_empty() { - match next { - Direct(s) => Some(*s), - _ => None, - } - } else { - next.get(Path { - head: path.tail[0], - tail: path.tail[1..].to_vec(), - }) - } - }), - } - } -} - -#[macro_export] -macro_rules! template_params { - (@count $head: expr => $hv: tt, $($rest:tt)+) => { 1 + template_params!(@count $($rest)+) }; - (@count $one:expr => $($ov: tt)*) => { 1 }; - (@inner $ret: ident, ($key: expr => {$($v:tt)*}, $($r:tt)*)) => { - $ret.insert($key, template_params!({ $($v)* })); - template_params!(@inner $ret, ($($r)*)); - }; - (@inner $ret: ident, ($key: expr => $value: expr, $($r:tt)*)) => { - $ret.insert($key, template_params!($value)); - template_params!(@inner $ret, ($($r)*)); - }; - (@inner $ret: ident, ()) => {}; - - ({ $($body: tt)* }) => {{ - let _cap = template_params!(@count $($body)*); - let mut _m = ::std::collections::HashMap::with_capacity(_cap); - template_params!(@inner _m, ($($body)*)); - TemplateParams::Nested(_m) - }}; - - ($direct:expr) => { TemplateParams::Direct($direct) }; - - () => { TemplateParams::Nested(::std::collections::HashMap::new()) }; -} - -fn template<'a>(input: &'a str) -> IResult<&'a str, Template<'a>> { - complete!( - input, - map!(many1!(complete!(template_token)), Template::new) - ) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn test_parse_path_ident() { - assert_eq!(path_ident("foo}}"), Ok(("}}", "foo"))); - assert_eq!(path_ident("foo.bar}}"), Ok((".bar}}", "foo"))); - } - - #[test] - fn test_parse_path() { - assert_eq!(path("foo}}"), Ok(("}}", Path::new("foo", vec![])))); - assert_eq!( - path("foo.bar}}"), - Ok(("}}", Path::new("foo", vec!["bar"]))) - ); - assert_eq!( - path("foo.bar.baz}}"), - Ok(("}}", Path::new("foo", vec!["bar", "baz"]))) - ); - } - - #[test] - fn test_parse_template_token() { - assert_eq!( - template_token("foo bar"), - Ok(("", TemplateToken::Literal("foo bar"))) - ); - - assert_eq!( - template_token("foo bar {{baz}}"), - Ok(("{{baz}}", TemplateToken::Literal("foo bar "))) - ); - - assert_eq!( - template_token("{{baz}}"), - Ok(( - "", - TemplateToken::Substitution(Path::new("baz", Vec::new())) - )) - ); - - assert_eq!( - template_token("{{baz}} foo bar"), - Ok(( - " foo bar", - TemplateToken::Substitution(Path::new("baz", Vec::new())) - )) - ); - } - - #[test] - fn test_parse_template() { - assert_eq!( - template("foo bar"), - Ok(( - "", - Template { - tokens: vec![TemplateToken::Literal("foo bar")] - } - )) - ); - - assert_eq!( - template("foo bar {{baz}} qux"), - Ok(( - "", - Template { - tokens: vec![ - TemplateToken::Literal("foo bar "), - TemplateToken::Substitution(Path::new( - "baz", - Vec::new() - )), - TemplateToken::Literal(" qux"), - ] - } - )) - ); - } - - #[test] - fn test_template_params_literal() { - // trace_macros!(true); - let expected = template_params!({ - "direct" => "hi", - "other" => "here", - "nested" => { - "one" => "1", - "two" => "2", - "double" => { - "three" => "3", - }, - }, - }); - // trace_macros!(false); - assert_eq!( - TemplateParams::Nested(hashmap! { - "direct" => TemplateParams::Direct("hi"), - "other" => TemplateParams::Direct("here"), - "nested" => TemplateParams::Nested(hashmap!{ - "one" => TemplateParams::Direct("1"), - "two" => TemplateParams::Direct("2"), - "double" => TemplateParams::Nested(hashmap!{ - "three" => TemplateParams::Direct("3"), - }) - }) - }), - expected, - ) - } - - #[test] - fn test_format_template() { - assert_eq!( - "foo bar baz qux", - Template::parse("foo {{x}} {{y.z}} {{y.w.z}}") - .unwrap() - .format(&template_params!({ - "x" => "bar", - "y" => { - "z" => "baz", - "w" => { - "z" => "qux", - }, - }, - })) - .unwrap() - ) - } -} diff --git a/src/util/trait_impls.rs b/src/util/trait_impls.rs deleted file mode 100644 index ba15f7119d26..000000000000 --- a/src/util/trait_impls.rs +++ /dev/null @@ -1,17 +0,0 @@ -macro_rules! ref_impl { - (impl<T: $traitb: ident $(+ $bound:ident)*> $traiti:ident for &T { - $($body:tt)* - }) => { - impl<'a, T: $traitb $(+ $bound)*> $traiti for &'a T { - $($body)* - } - - impl<'a, T: $traitb $(+ $bound)*> $traiti for &'a mut T { - $($body)* - } - - impl<T: $traitb $(+ $bound)*> $traiti for ::std::boxed::Box<T> { - $($body)* - } - }; -} |