pub struct WorldCtx { /* private fields */ }Expand description
Copy handle for synchronous World access from async tasks.
§Safety Contract
- Single-threaded only. No concurrent
with_worldcalls. - World outlives tasks. The
Worldmust not be dropped while any task holds aWorldCtx.
Both invariants are enforced structurally by the single-threaded
executor: only one task polls at a time, and the user owns the
World alongside the executor in the same scope.
§Examples
use nexus_async_rt::{Executor, WorldCtx};
use nexus_rt::{WorldBuilder, Res, ResMut, IntoHandler, Handler};
let mut world = builder.build();
let ctx = WorldCtx::new(&mut world);
// Pre-resolve at setup — single HashMap lookup per type
let mut on_quote = (|mut books: ResMut<Books>, q: Quote| {
books.update(q);
}).into_handler(world.registry());
let mut executor = Executor::new(64);
executor.spawn_boxed(async move {
let data = read_socket().await;
// Single deref per resource at dispatch time
ctx.with_world(|world| on_quote.run(world, data));
});
while executor.task_count() > 0 { executor.poll(); }Implementations§
Source§impl WorldCtx
impl WorldCtx
Sourcepub fn new(world: &mut World) -> Self
pub fn new(world: &mut World) -> Self
Create a context handle from a mutable World reference.
§Safety Contract (enforced by caller, not by the type system)
- The
Worldmust outlive all tasks using this handle. - The caller must not use
&mut Worlddirectly while tasks hold aWorldCtx— all World access must go throughwith_world. - Single-threaded use only (no concurrent
with_worldcalls).
These invariants are structurally enforced by crate::Runtime:
the World is created before the runtime, block_on takes
&mut self preventing direct World access during execution,
and the single-threaded executor prevents concurrent polls.
Sourcepub fn current() -> WorldCtx
pub fn current() -> WorldCtx
Returns a WorldCtx for the currently running runtime.
Reads the world pointer installed by
Runtime::block_on. The returned handle
is the same shape as one constructed via WorldCtx::new — same
Copy semantics, same with_world /
with_world_ref methods. Mirrors
tokio::runtime::Handle::current().
Use WorldCtx::new explicitly when constructing a handle outside
the runtime context (e.g., capturing into a task before block_on).
Use current() when you’re already inside a task and want the
active runtime’s world.
§Panics
Panics if called outside a Runtime::block_on
context.
Sourcepub fn with_world<R>(&self, f: impl FnOnce(&mut World) -> R) -> R
pub fn with_world<R>(&self, f: impl FnOnce(&mut World) -> R) -> R
Run a closure with exclusive World access.
Executes synchronously inline — no await point. The closure has
&mut World for its duration. Use when you need to mutate
resources; see with_world_ref for
read-only access.
Sourcepub fn with_world_ref<R>(&self, f: impl FnOnce(&World) -> R) -> R
pub fn with_world_ref<R>(&self, f: impl FnOnce(&World) -> R) -> R
Run a closure with shared World access.
Use when you only need to read resources.