From 1c7e825f66d38b1781fb0a749d239c9daa94c911 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Dr=C3=B6ge?= Date: Wed, 18 Jan 2023 13:03:06 +0200 Subject: [PATCH] glib: Add helper functions to spawn a non-`Send` future on the (thread-)default `MainContext` --- glib/src/lib.rs | 2 +- glib/src/main_context_futures.rs | 30 ++++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/glib/src/lib.rs b/glib/src/lib.rs index b9f8e27c0671..9ff6042f44af 100644 --- a/glib/src/lib.rs +++ b/glib/src/lib.rs @@ -199,7 +199,7 @@ pub use self::bridged_logging::{rust_log_handler, GlibLogger, GlibLoggerDomain, pub mod subclass; mod main_context_futures; -pub use main_context_futures::{JoinError, JoinHandle}; +pub use main_context_futures::{spawn, spawn_with_priority, JoinError, JoinHandle}; mod source_futures; pub use self::source_futures::*; diff --git a/glib/src/main_context_futures.rs b/glib/src/main_context_futures.rs index 6d00ac02b9b4..b6f2f4608d7c 100644 --- a/glib/src/main_context_futures.rs +++ b/glib/src/main_context_futures.rs @@ -552,6 +552,36 @@ impl Spawn for MainContext { } } +// rustdoc-stripper-ignore-next +/// Spawns an infallible, non-`Send` on the current thread-default [`MainContext`]. +/// +/// Panics if there is no thread-default main context on this thread and if this thread +/// does not own the global default main context. +pub fn spawn + 'static>(f: F) -> JoinHandle { + spawn_with_priority(crate::PRIORITY_DEFAULT, f) +} + +// rustdoc-stripper-ignore-next +/// Spawns an infallible, non-`Send` on the current thread-default [`MainContext`] with a +/// non-default priority. +/// +/// Panics if there is no thread-default main context on this thread and if this thread +/// does not own the global default main context. +pub fn spawn_with_priority + 'static>( + priority: Priority, + f: F, +) -> JoinHandle { + let ctx = MainContext::thread_default().unwrap_or_else(|| { + let ctx = MainContext::default(); + assert!( + ctx.is_owner(), + "Current thread does not own the default main context and has no thread-default main context", + ); + ctx + }); + ctx.spawn_local_with_priority(priority, f) +} + impl LocalSpawn for MainContext { fn spawn_local_obj(&self, f: LocalFutureObj<'static, ()>) -> Result<(), SpawnError> { let (tx, _) = oneshot::channel();