Skip to content

Commit 0f9ae13

Browse files
authored
task: add LocalKey::try_get (#7666)
Signed-off-by: tison <[email protected]>
1 parent 9255d96 commit 0f9ae13

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

tokio/src/task/task_local.rs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -275,6 +275,16 @@ impl<T: Clone + 'static> LocalKey<T> {
275275
pub fn get(&'static self) -> T {
276276
self.with(|v| v.clone())
277277
}
278+
279+
/// Returns a copy of the task-local value
280+
/// if the task-local value implements `Clone`.
281+
///
282+
/// If the task-local with the associated key is not present, this
283+
/// method will return an `AccessError`. For a panicking variant,
284+
/// see `get`.
285+
pub fn try_get(&'static self) -> Result<T, AccessError> {
286+
self.try_with(|v| v.clone())
287+
}
278288
}
279289

280290
impl<T: 'static> fmt::Debug for LocalKey<T> {

tokio/tests/task_local.rs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,3 +145,27 @@ async fn poll_after_take_value_should_fail() {
145145
// Poll the future after `take_value` has been called
146146
fut.await;
147147
}
148+
149+
#[tokio::test]
150+
async fn get_value() {
151+
tokio::task_local! {
152+
static KEY: u32
153+
}
154+
155+
KEY.scope(1, async {
156+
assert_eq!(KEY.get(), 1);
157+
assert_eq!(KEY.try_get().unwrap(), 1);
158+
})
159+
.await;
160+
161+
let fut = KEY.scope(1, async {
162+
let result = KEY.try_get();
163+
// The task local value no longer exists.
164+
assert!(result.is_err());
165+
});
166+
let mut fut = Box::pin(fut);
167+
fut.as_mut().take_value();
168+
169+
// Poll the future after `take_value` has been called
170+
fut.await;
171+
}

0 commit comments

Comments
 (0)