Skip to content
This repository has been archived by the owner on Nov 15, 2023. It is now read-only.

environmental! handles generics #307

Merged
merged 2 commits into from
Jul 12, 2018
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 39 additions & 12 deletions substrate/environmental/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -190,33 +190,36 @@ macro_rules! environmental {
}
}
};
($name:ident : trait $t:ident) => {
#[allow(non_camel_case_types)]
struct $name { __private_field: () }
($name:ident : trait @$t:ident [$($args:ty,)*]) => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

whitespaces 🤫

#[allow(non_camel_case_types, dead_code)]
struct $name { __private_field: () }

thread_local_impl!(static GLOBAL: $crate::imp::RefCell<Option<*mut ($t + 'static)>>
thread_local_impl!(static GLOBAL: $crate::imp::RefCell<Option<*mut ($t<$($args),*> + 'static)>>
= $crate::imp::RefCell::new(None));

impl $name {
#[allow(unused_imports)]
impl $name {
#[allow(unused_imports)]

pub fn using<R, F: FnOnce() -> R>(
protected: &mut $t,
protected: &mut $t<$($args),*>,
f: F
) -> R {
let lifetime_extended = unsafe {
$crate::imp::transmute::<&mut $t, &mut ($t + 'static)>(protected)
$crate::imp::transmute::<&mut $t<$($args),*>, &mut ($t<$($args),*> + 'static)>(protected)
};
$crate::using(&GLOBAL, lifetime_extended, f)
}
}

pub fn with<R, F: for<'a> FnOnce(&'a mut ($t + 'a)) -> R>(
pub fn with<R, F: for<'a> FnOnce(&'a mut ($t<$($args),*> + 'a)) -> R>(
f: F
) -> Option<R> {
$crate::with(&GLOBAL, |x| f(x))
}
}
}
}
};
($name:ident : trait $t:ident <>) => { environmental! { $name : trait @$t [] } };
($name:ident : trait $t:ident < $($args:ty),* $(,)* >) => { environmental! { $name : trait @$t [$($args,)*] } };
($name:ident : trait $t:ident) => { environmental! { $name : trait @$t [] } };
}

#[cfg(test)]
Expand Down Expand Up @@ -322,4 +325,28 @@ mod tests {

assert_eq!(got_sum, 15);
}

#[test]
fn use_generic_trait() {
trait Plus { fn plus42() -> usize; }
struct ConcretePlus;
impl Plus for ConcretePlus {
fn plus42() -> usize { 42 }
}
trait Multiplier<T: Plus> { fn mul_and_add(&self) -> usize; }
impl<'a, P: Plus> Multiplier<P> for &'a [usize] {
fn mul_and_add(&self) -> usize {
self.iter().fold(1, |a, c| a * c) + P::plus42()
}
}

let numbers = vec![1, 2, 3];
let mut numbers = &numbers[..];
let out = foo::using(&mut numbers, || {
foo::with(|x| x.mul_and_add() )
}).unwrap();

assert_eq!(out, 6 + 42);
environmental!(foo: trait Multiplier<ConcretePlus>);
}
}