From 1475448bdfa5f0bed35abb6e3d5620a22cc27f53 Mon Sep 17 00:00:00 2001 From: Pierre Krieger Date: Mon, 20 Jan 2020 17:09:52 +0100 Subject: [PATCH] runtime: add Handle::try_current (#2118) * runtime: add Handle::try_current Makes it possible to get a Handle only if a Runtime has been started, without panicing if that isn't the case * Use an error instead --- tokio/src/runtime/handle.rs | 27 +++++++++++++++++++++++++++ tokio/src/runtime/mod.rs | 2 +- 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/tokio/src/runtime/handle.rs b/tokio/src/runtime/handle.rs index ae7b416ee..3f2534553 100644 --- a/tokio/src/runtime/handle.rs +++ b/tokio/src/runtime/handle.rs @@ -1,4 +1,5 @@ use crate::runtime::{blocking, context, io, time, Spawner}; +use std::{error, fmt}; cfg_rt_core! { use crate::task::JoinHandle; @@ -61,6 +62,15 @@ impl Handle { pub fn current() -> Self { context::current().expect("not currently running on the Tokio runtime.") } + + /// Returns a Handle view over the currently running Runtime + /// + /// Returns an error if no Runtime has been started + /// + /// Contrary to `current`, this never panics + pub fn try_current() -> Result { + context::current().ok_or(TryCurrentError(())) + } } cfg_rt_core! { @@ -105,3 +115,20 @@ cfg_rt_core! { } } } + +/// Error returned by `try_current` when no Runtime has been started +pub struct TryCurrentError(()); + +impl fmt::Debug for TryCurrentError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("TryCurrentError").finish() + } +} + +impl fmt::Display for TryCurrentError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("no tokio Runtime has been initialized") + } +} + +impl error::Error for TryCurrentError {} diff --git a/tokio/src/runtime/mod.rs b/tokio/src/runtime/mod.rs index a29f69598..e656d4877 100644 --- a/tokio/src/runtime/mod.rs +++ b/tokio/src/runtime/mod.rs @@ -208,7 +208,7 @@ pub(crate) mod enter; use self::enter::enter; mod handle; -pub use self::handle::Handle; +pub use self::handle::{Handle, TryCurrentError}; mod io;