aboutsummaryrefslogtreecommitdiff
path: root/src/runtime/context.rs
diff options
context:
space:
mode:
authorJoel Galenson <jgalenson@google.com>2020-10-05 08:16:15 -0700
committerJoel Galenson <jgalenson@google.com>2020-10-05 08:16:15 -0700
commitf03b3ba785a6d336884bfc525046906f8c2a9904 (patch)
tree14e2bd707d8d152ea0476ec9e686deb2a2f55b34 /src/runtime/context.rs
parent40b8b369b069afb314a9d4bb92be1bdd038979f8 (diff)
downloadtokio-f03b3ba785a6d336884bfc525046906f8c2a9904.tar.gz
Import tokio-0.2.22
Test: None Change-Id: Iea7ee5e62819c9b16dbfad05a6146775df72506a
Diffstat (limited to 'src/runtime/context.rs')
-rw-r--r--src/runtime/context.rs73
1 files changed, 73 insertions, 0 deletions
diff --git a/src/runtime/context.rs b/src/runtime/context.rs
new file mode 100644
index 0000000..1b267f4
--- /dev/null
+++ b/src/runtime/context.rs
@@ -0,0 +1,73 @@
+//! Thread local runtime context
+use crate::runtime::Handle;
+
+use std::cell::RefCell;
+
+thread_local! {
+ static CONTEXT: RefCell<Option<Handle>> = RefCell::new(None)
+}
+
+pub(crate) fn current() -> Option<Handle> {
+ CONTEXT.with(|ctx| ctx.borrow().clone())
+}
+
+cfg_io_driver! {
+ pub(crate) fn io_handle() -> crate::runtime::io::Handle {
+ CONTEXT.with(|ctx| match *ctx.borrow() {
+ Some(ref ctx) => ctx.io_handle.clone(),
+ None => Default::default(),
+ })
+ }
+}
+
+cfg_time! {
+ pub(crate) fn time_handle() -> crate::runtime::time::Handle {
+ CONTEXT.with(|ctx| match *ctx.borrow() {
+ Some(ref ctx) => ctx.time_handle.clone(),
+ None => Default::default(),
+ })
+ }
+
+ cfg_test_util! {
+ pub(crate) fn clock() -> Option<crate::runtime::time::Clock> {
+ CONTEXT.with(|ctx| match *ctx.borrow() {
+ Some(ref ctx) => Some(ctx.clock.clone()),
+ None => None,
+ })
+ }
+ }
+}
+
+cfg_rt_core! {
+ pub(crate) fn spawn_handle() -> Option<crate::runtime::Spawner> {
+ CONTEXT.with(|ctx| match *ctx.borrow() {
+ Some(ref ctx) => Some(ctx.spawner.clone()),
+ None => None,
+ })
+ }
+}
+
+/// Set this [`Handle`] as the current active [`Handle`].
+///
+/// [`Handle`]: Handle
+pub(crate) fn enter<F, R>(new: Handle, f: F) -> R
+where
+ F: FnOnce() -> R,
+{
+ struct DropGuard(Option<Handle>);
+
+ impl Drop for DropGuard {
+ fn drop(&mut self) {
+ CONTEXT.with(|ctx| {
+ *ctx.borrow_mut() = self.0.take();
+ });
+ }
+ }
+
+ let _guard = CONTEXT.with(|ctx| {
+ let old = ctx.borrow_mut().replace(new);
+ DropGuard(old)
+ });
+
+ f()
+}