Skip to content

Instantly share code, notes, and snippets.

@lachlansneff
Last active May 3, 2019 22:04
Show Gist options
  • Save lachlansneff/6a507dcac94103263f7ddadbf57c7f7c to your computer and use it in GitHub Desktop.
Save lachlansneff/6a507dcac94103263f7ddadbf57c7f7c to your computer and use it in GitHub Desktop.
#![feature(const_type_id, gen_future, const_fn)]
use std::any::TypeId;
use std::future::get_task_context;
// ...
// /// Information about the currently-running task.
// ///
// /// Contexts are always tied to the stack, since they are set up specifically
// /// when performing a single `poll` step on a task.
// pub struct Context<'a> {
// waker: &'a Waker,
// map: &'a mut LocalMap,
// executor: Option<&'a mut Executor>,
// }
// impl<'a> Context<'a> {
// // ...
// // Private method.
// #[inline]
// fn task_local_data<T: Send + 'static>(&mut self, key: TypeId, init: fn() -> T) -> &'a T {
// }
// }
// ...
pub struct LocalKey<T: Send + 'static> {
key: TypeId,
init: fn() -> T,
}
impl<T: Send + 'static> LocalKey<T> {
#[doc(hidden)]
pub const fn __new(key: TypeId, init: fn() -> T) -> Self {
Self {
key,
init,
}
}
pub fn with<F, R>(&'static self, f: F) -> R
where
F: FnOnce(&T) -> R,
{
get_task_context(|cx| {
// let data = cx. /* private */ task_local_data(self.key, self.init);
// f(data)
unimplemented!()
})
}
}
macro_rules! task_local {
($( $(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = $init:expr; )*) => (
$(
$(#[$attr])* $vis const $name: $crate::LocalKey<$t> = {
struct UniqueT;
#[inline]
fn __init() -> $t {
$init
}
$crate::LocalKey::__new(TypeId::of::<UniqueT>(), __init)
};
)*
);
}
task_local! {
pub static TEST_LOCAL: i32 = 0;
}
fn main() {
TEST_LOCAL.with(|i| {
println!("i: {}", i)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment