File tree Expand file tree Collapse file tree 2 files changed +34
-0
lines changed Expand file tree Collapse file tree 2 files changed +34
-0
lines changed Original file line number Diff line number Diff 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
280290impl < T : ' static > fmt:: Debug for LocalKey < T > {
Original file line number Diff line number Diff 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+ }
You can’t perform that action at this time.
0 commit comments