Skip to content

Commit 9c1c0bf

Browse files
authored
Rollup merge of #123203 - jkarneges:context-ext, r=Amanieu
Add `Context::ext` This change enables `Context` to carry arbitrary extension data via a single `&mut dyn Any` field. ```rust #![feature(context_ext)] impl Context { fn ext(&mut self) -> &mut dyn Any; } impl ContextBuilder { fn ext(self, data: &'a mut dyn Any) -> Self; fn from(cx: &'a mut Context<'_>) -> Self; fn waker(self, waker: &'a Waker) -> Self; } ``` Basic usage: ```rust struct MyExtensionData { executor_name: String, } let mut ext = MyExtensionData { executor_name: "foo".to_string(), }; let mut cx = ContextBuilder::from_waker(&waker).ext(&mut ext).build(); if let Some(ext) = cx.ext().downcast_mut::<MyExtensionData>() { println!("{}", ext.executor_name); } ``` Currently, `Context` only carries a `Waker`, but there is interest in having it carry other kinds of data. Examples include [LocalWaker](#118959), [a reactor interface](rust-lang/libs-team#347), and [multiple arbitrary values by type](https://docs.rs/context-rs/latest/context_rs/). There is also a general practice in the ecosystem of sharing data between executors and futures via thread-locals or globals that would arguably be better shared via `Context`, if it were possible. The `ext` field would provide a low friction (to stabilization) solution to enable experimentation. It would enable experimenting with what kinds of data we want to carry as well as with what data structures we may want to use to carry such data. Dedicated fields for specific kinds of data could still be added directly on `Context` when we have sufficient experience or understanding about the problem they are solving, such as with `LocalWaker`. The `ext` field would be for data for which we don't have such experience or understanding, and that could be graduated to dedicated fields once proven. Both the provider and consumer of the extension data must be aware of the concrete type behind the `Any`. This means it is not possible for the field to carry an abstract interface. However, the field can carry a concrete type which in turn carries an interface. There are different ways one can imagine an interface-carrying concrete type to work, hence the benefit of being able to experiment with such data structures. ## Passing interfaces Interfaces can be placed in a concrete type, such as a struct, and then that type can be casted to `Any`. However, one gotcha is `Any` cannot contain non-static references. This means one cannot simply do: ```rust struct Extensions<'a> { interface1: &'a mut dyn Trait1, interface2: &'a mut dyn Trait2, } let mut ext = Extensions { interface1: &mut impl1, interface2: &mut impl2, }; let ext: &mut dyn Any = &mut ext; ``` To work around this without boxing, unsafe code can be used to create a safe projection using accessors. For example: ```rust pub struct Extensions { interface1: *mut dyn Trait1, interface2: *mut dyn Trait2, } impl Extensions { pub fn new<'a>( interface1: &'a mut (dyn Trait1 + 'static), interface2: &'a mut (dyn Trait2 + 'static), scratch: &'a mut MaybeUninit<Self>, ) -> &'a mut Self { scratch.write(Self { interface1, interface2, }) } pub fn interface1(&mut self) -> &mut dyn Trait1 { unsafe { self.interface1.as_mut().unwrap() } } pub fn interface2(&mut self) -> &mut dyn Trait2 { unsafe { self.interface2.as_mut().unwrap() } } } let mut scratch = MaybeUninit::uninit(); let ext: &mut Extensions = Extensions::new(&mut impl1, &mut impl2, &mut scratch); // ext can now be casted to `&mut dyn Any` and back, and used safely let ext: &mut dyn Any = ext; ``` ## Context inheritance Sometimes when futures poll other futures they want to provide their own `Waker` which requires creating their own `Context`. Unfortunately, polling sub-futures with a fresh `Context` means any properties on the original `Context` won't get propagated along to the sub-futures. To help with this, some additional methods are added to `ContextBuilder`. Here's how to derive a new `Context` from another, overriding only the `Waker`: ```rust let mut cx = ContextBuilder::from(parent_cx).waker(&new_waker).build(); ```
2 parents e41d7e7 + 036085d commit 9c1c0bf

File tree

3 files changed

+102
-9
lines changed

3 files changed

+102
-9
lines changed

library/core/src/task/wake.rs

+64-3
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
use crate::mem::transmute;
44

5+
use crate::any::Any;
56
use crate::fmt;
67
use crate::marker::PhantomData;
78
use crate::ptr;
@@ -220,6 +221,12 @@ impl RawWakerVTable {
220221
}
221222
}
222223

224+
#[derive(Debug)]
225+
enum ExtData<'a> {
226+
Some(&'a mut dyn Any),
227+
None(()),
228+
}
229+
223230
/// The context of an asynchronous task.
224231
///
225232
/// Currently, `Context` only serves to provide access to a [`&Waker`](Waker)
@@ -229,6 +236,7 @@ impl RawWakerVTable {
229236
pub struct Context<'a> {
230237
waker: &'a Waker,
231238
local_waker: &'a LocalWaker,
239+
ext: ExtData<'a>,
232240
// Ensure we future-proof against variance changes by forcing
233241
// the lifetime to be invariant (argument-position lifetimes
234242
// are contravariant while return-position lifetimes are
@@ -257,13 +265,25 @@ impl<'a> Context<'a> {
257265
pub const fn waker(&self) -> &'a Waker {
258266
&self.waker
259267
}
268+
260269
/// Returns a reference to the [`LocalWaker`] for the current task.
261270
#[inline]
262271
#[unstable(feature = "local_waker", issue = "118959")]
263272
#[rustc_const_unstable(feature = "const_waker", issue = "102012")]
264273
pub const fn local_waker(&self) -> &'a LocalWaker {
265274
&self.local_waker
266275
}
276+
277+
/// Returns a reference to the extension data for the current task.
278+
#[inline]
279+
#[unstable(feature = "context_ext", issue = "123392")]
280+
#[rustc_const_unstable(feature = "const_waker", issue = "102012")]
281+
pub const fn ext(&mut self) -> &mut dyn Any {
282+
match &mut self.ext {
283+
ExtData::Some(data) => *data,
284+
ExtData::None(unit) => unit,
285+
}
286+
}
267287
}
268288

269289
#[stable(feature = "futures_api", since = "1.36.0")]
@@ -300,6 +320,7 @@ impl fmt::Debug for Context<'_> {
300320
pub struct ContextBuilder<'a> {
301321
waker: &'a Waker,
302322
local_waker: &'a LocalWaker,
323+
ext: ExtData<'a>,
303324
// Ensure we future-proof against variance changes by forcing
304325
// the lifetime to be invariant (argument-position lifetimes
305326
// are contravariant while return-position lifetimes are
@@ -318,7 +339,39 @@ impl<'a> ContextBuilder<'a> {
318339
pub const fn from_waker(waker: &'a Waker) -> Self {
319340
// SAFETY: LocalWaker is just Waker without thread safety
320341
let local_waker = unsafe { transmute(waker) };
321-
Self { waker: waker, local_waker, _marker: PhantomData, _marker2: PhantomData }
342+
Self {
343+
waker: waker,
344+
local_waker,
345+
ext: ExtData::None(()),
346+
_marker: PhantomData,
347+
_marker2: PhantomData,
348+
}
349+
}
350+
351+
/// Create a ContextBuilder from an existing Context.
352+
#[inline]
353+
#[rustc_const_unstable(feature = "const_waker", issue = "102012")]
354+
#[unstable(feature = "context_ext", issue = "123392")]
355+
pub const fn from(cx: &'a mut Context<'_>) -> Self {
356+
let ext = match &mut cx.ext {
357+
ExtData::Some(ext) => ExtData::Some(*ext),
358+
ExtData::None(()) => ExtData::None(()),
359+
};
360+
Self {
361+
waker: cx.waker,
362+
local_waker: cx.local_waker,
363+
ext,
364+
_marker: PhantomData,
365+
_marker2: PhantomData,
366+
}
367+
}
368+
369+
/// This method is used to set the value for the waker on `Context`.
370+
#[inline]
371+
#[unstable(feature = "context_ext", issue = "123392")]
372+
#[rustc_const_unstable(feature = "const_waker", issue = "102012")]
373+
pub const fn waker(self, waker: &'a Waker) -> Self {
374+
Self { waker, ..self }
322375
}
323376

324377
/// This method is used to set the value for the local waker on `Context`.
@@ -329,13 +382,21 @@ impl<'a> ContextBuilder<'a> {
329382
Self { local_waker, ..self }
330383
}
331384

385+
/// This method is used to set the value for the extension data on `Context`.
386+
#[inline]
387+
#[unstable(feature = "context_ext", issue = "123392")]
388+
#[rustc_const_unstable(feature = "const_waker", issue = "102012")]
389+
pub const fn ext(self, data: &'a mut dyn Any) -> Self {
390+
Self { ext: ExtData::Some(data), ..self }
391+
}
392+
332393
/// Builds the `Context`.
333394
#[inline]
334395
#[unstable(feature = "local_waker", issue = "118959")]
335396
#[rustc_const_unstable(feature = "const_waker", issue = "102012")]
336397
pub const fn build(self) -> Context<'a> {
337-
let ContextBuilder { waker, local_waker, _marker, _marker2 } = self;
338-
Context { waker, local_waker, _marker, _marker2 }
398+
let ContextBuilder { waker, local_waker, ext, _marker, _marker2 } = self;
399+
Context { waker, local_waker, ext, _marker, _marker2 }
339400
}
340401
}
341402

tests/ui/async-await/async-is-unwindsafe.rs

+1
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ fn main() {
1111

1212
is_unwindsafe(async {
1313
//~^ ERROR the type `&mut Context<'_>` may not be safely transferred across an unwind boundary
14+
//~| ERROR the type `&mut (dyn Any + 'static)` may not be safely transferred across an unwind boundary
1415
use std::ptr::null;
1516
use std::task::{Context, RawWaker, RawWakerVTable, Waker};
1617
let waker = unsafe {

tests/ui/async-await/async-is-unwindsafe.stderr

+37-6
Original file line numberDiff line numberDiff line change
@@ -6,19 +6,18 @@ LL | is_unwindsafe(async {
66
| |_____|
77
| ||
88
LL | ||
9+
LL | ||
910
LL | || use std::ptr::null;
10-
LL | || use std::task::{Context, RawWaker, RawWakerVTable, Waker};
1111
... ||
1212
LL | || drop(cx_ref);
1313
LL | || });
1414
| ||_____-^ `&mut Context<'_>` may not be safely transferred across an unwind boundary
1515
| |_____|
16-
| within this `{async block@$DIR/async-is-unwindsafe.rs:12:19: 29:6}`
16+
| within this `{async block@$DIR/async-is-unwindsafe.rs:12:19: 30:6}`
1717
|
18-
= help: within `{async block@$DIR/async-is-unwindsafe.rs:12:19: 29:6}`, the trait `UnwindSafe` is not implemented for `&mut Context<'_>`, which is required by `{async block@$DIR/async-is-unwindsafe.rs:12:19: 29:6}: UnwindSafe`
19-
= note: `UnwindSafe` is implemented for `&Context<'_>`, but not for `&mut Context<'_>`
18+
= help: within `{async block@$DIR/async-is-unwindsafe.rs:12:19: 30:6}`, the trait `UnwindSafe` is not implemented for `&mut Context<'_>`, which is required by `{async block@$DIR/async-is-unwindsafe.rs:12:19: 30:6}: UnwindSafe`
2019
note: future does not implement `UnwindSafe` as this value is used across an await
21-
--> $DIR/async-is-unwindsafe.rs:25:18
20+
--> $DIR/async-is-unwindsafe.rs:26:18
2221
|
2322
LL | let cx_ref = &mut cx;
2423
| ------ has type `&mut Context<'_>` which does not implement `UnwindSafe`
@@ -31,6 +30,38 @@ note: required by a bound in `is_unwindsafe`
3130
LL | fn is_unwindsafe(_: impl std::panic::UnwindSafe) {}
3231
| ^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_unwindsafe`
3332

34-
error: aborting due to 1 previous error
33+
error[E0277]: the type `&mut (dyn Any + 'static)` may not be safely transferred across an unwind boundary
34+
--> $DIR/async-is-unwindsafe.rs:12:5
35+
|
36+
LL | is_unwindsafe(async {
37+
| _____^_____________-
38+
| |_____|
39+
| ||
40+
LL | ||
41+
LL | ||
42+
LL | || use std::ptr::null;
43+
... ||
44+
LL | || drop(cx_ref);
45+
LL | || });
46+
| ||_____-^ `&mut (dyn Any + 'static)` may not be safely transferred across an unwind boundary
47+
| |_____|
48+
| within this `{async block@$DIR/async-is-unwindsafe.rs:12:19: 30:6}`
49+
|
50+
= help: within `{async block@$DIR/async-is-unwindsafe.rs:12:19: 30:6}`, the trait `UnwindSafe` is not implemented for `&mut (dyn Any + 'static)`, which is required by `{async block@$DIR/async-is-unwindsafe.rs:12:19: 30:6}: UnwindSafe`
51+
note: future does not implement `UnwindSafe` as this value is used across an await
52+
--> $DIR/async-is-unwindsafe.rs:26:18
53+
|
54+
LL | let mut cx = Context::from_waker(&waker);
55+
| ------ has type `Context<'_>` which does not implement `UnwindSafe`
56+
...
57+
LL | async {}.await; // this needs an inner await point
58+
| ^^^^^ await occurs here, with `mut cx` maybe used later
59+
note: required by a bound in `is_unwindsafe`
60+
--> $DIR/async-is-unwindsafe.rs:3:26
61+
|
62+
LL | fn is_unwindsafe(_: impl std::panic::UnwindSafe) {}
63+
| ^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `is_unwindsafe`
64+
65+
error: aborting due to 2 previous errors
3566

3667
For more information about this error, try `rustc --explain E0277`.

0 commit comments

Comments
 (0)