use im::hashmap::HashMap;
use std::any::TypeId;
use std::fmt;
use std::hash::{BuildHasherDefault, Hasher};
use std::mem;
use std::sync::Arc;
use std::ops::Deref;
use ctx::ExecutionContext;
#[macro_export]
macro_rules! flow_local {
(static $NAME:ident : $t:ty = $e:expr) => {
static $NAME: $crate::FlowLocal<$t> = {
fn __init() -> $t {
$e
}
fn __key() -> ::std::any::TypeId {
struct __A;
::std::any::TypeId::of::<__A>()
}
$crate::FlowLocal {
__init: __init,
__key: __key,
}
};
};
}
#[derive(Clone)]
pub struct FlowBox<T: ?Sized>(Arc<Box<T>>);
pub(crate) type LocalMap = HashMap<TypeId, Box<Opaque>, BuildHasherDefault<IdHasher>>;
pub(crate) trait Opaque: Send + Sync {}
impl<T: Send + Sync> Opaque for T {}
pub struct FlowLocal<T> {
#[doc(hidden)]
pub __key: fn() -> TypeId,
#[doc(hidden)]
pub __init: fn() -> T,
}
impl<T> fmt::Debug for FlowLocal<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "FlowLocal")
}
}
pub(crate) struct IdHasher {
id: u64,
}
impl Default for IdHasher {
fn default() -> IdHasher {
IdHasher { id: 0 }
}
}
impl Hasher for IdHasher {
fn write(&mut self, _bytes: &[u8]) {
panic!("can only hash u64");
}
fn write_u64(&mut self, u: u64) {
self.id = u;
}
fn finish(&self) -> u64 {
self.id
}
}
impl<T: Send + 'static> FlowLocal<T> {
pub fn get(&self) -> FlowBox<T> {
let key = (self.__key)();
if let Some(rv) = ExecutionContext::get_local_value(key) {
return unsafe { mem::transmute(rv) };
};
let arc = Arc::new(Box::new((self.__init)()));
ExecutionContext::set_local_value(key, unsafe {
mem::forget(arc.clone());
mem::transmute(arc.clone())
});
FlowBox(arc)
}
pub fn set(&self, value: T) {
let key = (self.__key)();
let arc = Arc::new(Box::new(value));
ExecutionContext::set_local_value(key, unsafe {
mem::forget(arc.clone());
mem::transmute(arc.clone())
});
}
}
impl<T: fmt::Display + ?Sized> fmt::Display for FlowBox<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Display::fmt(&**self, f)
}
}
impl<T: fmt::Debug + ?Sized> fmt::Debug for FlowBox<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&**self, f)
}
}
impl<T: ?Sized> fmt::Pointer for FlowBox<T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let ptr: *const T = &**self;
fmt::Pointer::fmt(&ptr, f)
}
}
impl<T: ?Sized> Deref for FlowBox<T> {
type Target = T;
fn deref(&self) -> &T {
&*self.0
}
}