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

generic hash #683

Merged
merged 1 commit into from
Sep 11, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
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
32 changes: 29 additions & 3 deletions substrate/environmental/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,32 @@ macro_rules! environmental {
}
}
};
($name:ident<$traittype:ident> : trait $t:ident <$concretetype:ty>) => {
#[allow(non_camel_case_types, dead_code)]
struct $name <H: $traittype> { _private_field: $crate::imp::PhantomData<H> }

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

impl<H: $traittype> $name<H> {
#[allow(unused_imports)]
pub fn using<R, F: FnOnce() -> R>(
protected: &mut $t<H>,
f: F
) -> R {
let lifetime_extended = unsafe {
$crate::imp::transmute::<&mut $t<H>, &mut ($t<$concretetype> + 'static)>(protected)
};
$crate::using(&GLOBAL, lifetime_extended, f)
}

pub fn with<R, F: for<'a> FnOnce(&'a mut ($t<$concretetype> + '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 [] } };
Expand Down Expand Up @@ -345,11 +371,11 @@ mod tests {

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

assert_eq!(out, 6 + 42);
environmental!(foo: trait Multiplier<ConcretePlus>);
environmental!(foo<Plus>: trait Multiplier<ConcretePlus>);
}
}
1 change: 1 addition & 0 deletions substrate/environmental/with_std.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ pub mod imp {
pub use std::thread::LocalKey;
pub use std::mem::transmute;
pub use std::mem::replace;
pub use std::marker::PhantomData;
}

#[doc(hidden)]
Expand Down
1 change: 1 addition & 0 deletions substrate/environmental/without_std.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ pub mod imp {
pub use core::cell::RefCell;
pub use core::mem::transmute;
pub use core::mem::replace;
pub use core::marker::PhantomData;

// This code is a simplified version of [`LocalKey`] and it's wasm32 specialization: [`statik::Key`].
// [`LocalKey`]: https://github.com/alexcrichton/rust/blob/98931165a23a1c2860d99759385f45d6807c8982/src/libstd/thread/local.rs#L89
Expand Down