From cc8c0534212e03c234fa2554df5ef51fa9870cc4 Mon Sep 17 00:00:00 2001 From: Tim Vilgot Mikael Fredenberg <26655508+vilgotf@users.noreply.github.com> Date: Fri, 7 Aug 2026 15:18:39 +0200 Subject: [PATCH] tokio: simplify `Option` handling with idiomatic combinators (#8336) --- benches/remote_spawn.rs | 4 +--- benches/spawn_blocking.rs | 4 +--- examples/tinyhttp.rs | 3 +-- tokio-macros/src/entry.rs | 10 +++++----- tokio-util/src/codec/length_delimited.rs | 2 +- tokio-util/src/time/delay_queue.rs | 7 +------ tokio-util/src/time/wheel/mod.rs | 3 +-- tokio/src/fs/file.rs | 2 +- tokio/src/io/stdio_common.rs | 2 +- tokio/src/runtime/context.rs | 4 ++-- tokio/src/runtime/metrics/runtime.rs | 21 +++++++-------------- tokio/src/runtime/scheduler/mod.rs | 2 +- tokio/src/runtime/task/trace/mod.rs | 4 +++- tokio/src/runtime/time/mod.rs | 3 +-- tokio/src/runtime/time/wheel/mod.rs | 3 +-- tokio/src/runtime/time_alt/wheel/mod.rs | 3 +-- tokio/src/task/local.rs | 4 +--- 17 files changed, 30 insertions(+), 51 deletions(-) diff --git a/benches/remote_spawn.rs b/benches/remote_spawn.rs index f9fbbe51a..390dcfd24 100644 --- a/benches/remote_spawn.rs +++ b/benches/remote_spawn.rs @@ -84,9 +84,7 @@ fn remote_spawn_contention(c: &mut Criterion) { } fn parallelism_levels() -> Vec { - let max_parallelism = std::thread::available_parallelism() - .map(|p| p.get()) - .unwrap_or(1); + let max_parallelism = std::thread::available_parallelism().map_or(1, |p| p.get()); [1, 2, 4, 8, 16, 32, 64] .into_iter() diff --git a/benches/spawn_blocking.rs b/benches/spawn_blocking.rs index ba55ab7f8..14c5edcf2 100644 --- a/benches/spawn_blocking.rs +++ b/benches/spawn_blocking.rs @@ -15,9 +15,7 @@ const NUM_BATCHES: usize = 100; const BATCH_SIZE: usize = 16; fn spawn_blocking_concurrency(c: &mut Criterion) { - let max_parallelism = std::thread::available_parallelism() - .map(|p| p.get()) - .unwrap_or(1); + let max_parallelism = std::thread::available_parallelism().map_or(1, |p| p.get()); let parallelism_levels: Vec = [1, 2, 4, 8, 16, 32, 64] .into_iter() diff --git a/examples/tinyhttp.rs b/examples/tinyhttp.rs index 7980a76c3..8a001f8b8 100644 --- a/examples/tinyhttp.rs +++ b/examples/tinyhttp.rs @@ -264,8 +264,7 @@ mod date { let now = SystemTime::now(); let now_unix = now .duration_since(SystemTime::UNIX_EPOCH) - .map(|since_epoch| since_epoch.as_secs()) - .unwrap_or(0); + .map_or(0, |since_epoch| since_epoch.as_secs()); if cache.unix_date != now_unix { cache.update(now, now_unix); } diff --git a/tokio-macros/src/entry.rs b/tokio-macros/src/entry.rs index 290888387..5ed8853a9 100644 --- a/tokio-macros/src/entry.rs +++ b/tokio-macros/src/entry.rs @@ -453,13 +453,13 @@ fn parse_knobs(mut input: ItemFn, is_test: bool, config: FinalConfig) -> TokenSt (start, end) }; - let crate_path = config - .crate_name - .map(ToTokens::into_token_stream) - .unwrap_or_else(|| { + let crate_path = config.crate_name.map_or_else( + || { Ident::new("tokio", Span::call_site().located_at(last_stmt_start_span)) .into_token_stream() - }); + }, + ToTokens::into_token_stream, + ); let use_builder = quote_spanned! {Span::call_site().located_at(last_stmt_start_span)=> use #crate_path::runtime::Builder; diff --git a/tokio-util/src/codec/length_delimited.rs b/tokio-util/src/codec/length_delimited.rs index ff40fe497..31799fdeb 100644 --- a/tokio-util/src/codec/length_delimited.rs +++ b/tokio-util/src/codec/length_delimited.rs @@ -1040,7 +1040,7 @@ impl Builder { fn num_head_bytes(&self) -> usize { let num = self.length_field_offset + self.length_field_len; - cmp::max(num, self.num_skip.unwrap_or(0)) + cmp::max(num, self.num_skip.unwrap_or_default()) } fn get_num_skip(&self) -> usize { diff --git a/tokio-util/src/time/delay_queue.rs b/tokio-util/src/time/delay_queue.rs index b327cc939..3c7d65ed4 100644 --- a/tokio-util/src/time/delay_queue.rs +++ b/tokio-util/src/time/delay_queue.rs @@ -580,12 +580,7 @@ impl DelayQueue { /// current task for wakeup if the value is not yet available, and returning /// `None` if the queue is exhausted. pub fn poll_expired(&mut self, cx: &mut task::Context<'_>) -> Poll>> { - if !self - .waker - .as_ref() - .map(|w| w.will_wake(cx.waker())) - .unwrap_or(false) - { + if !self.waker.as_ref().is_some_and(|w| w.will_wake(cx.waker())) { self.waker = Some(cx.waker().clone()); } diff --git a/tokio-util/src/time/wheel/mod.rs b/tokio-util/src/time/wheel/mod.rs index f310d10c1..e93c63626 100644 --- a/tokio-util/src/time/wheel/mod.rs +++ b/tokio-util/src/time/wheel/mod.rs @@ -111,8 +111,7 @@ where debug_assert!({ self.levels[level] .next_expiration(self.elapsed) - .map(|e| e.deadline >= self.elapsed) - .unwrap_or(true) + .map_or(true, |e| e.deadline >= self.elapsed) }); Ok(()) diff --git a/tokio/src/fs/file.rs b/tokio/src/fs/file.rs index 3829b609d..a172d2eee 100644 --- a/tokio/src/fs/file.rs +++ b/tokio/src/fs/file.rs @@ -1053,7 +1053,7 @@ impl Inner { if driver_handle .check_and_init(io_uring::opcode::Read::CODE) .await - .unwrap_or(false) + .unwrap_or_default() { let fd: crate::io::uring::utils::ArcFd = std; Self::uring_read(fd, buf, max_buf_size).await diff --git a/tokio/src/io/stdio_common.rs b/tokio/src/io/stdio_common.rs index a709bef31..72fd97d91 100644 --- a/tokio/src/io/stdio_common.rs +++ b/tokio/src/io/stdio_common.rs @@ -83,7 +83,7 @@ where .rev() .take(MAX_BYTES_PER_CHAR) .position(|byte| *byte < 0b1000_0000 || *byte >= 0b1100_0000) - .unwrap_or(0) + .unwrap_or_default() + 1; buf = &buf[..buf.len() - trailing_incomplete_char_size]; } diff --git a/tokio/src/runtime/context.rs b/tokio/src/runtime/context.rs index 09034c60f..d9863fe85 100644 --- a/tokio/src/runtime/context.rs +++ b/tokio/src/runtime/context.rs @@ -158,11 +158,11 @@ cfg_rt! { } pub(crate) fn set_current_task_id(id: Option) -> Option { - CONTEXT.try_with(|ctx| ctx.current_task_id.replace(id)).unwrap_or(None) + CONTEXT.try_with(|ctx| ctx.current_task_id.replace(id)).unwrap_or_default() } pub(crate) fn current_task_id() -> Option { - CONTEXT.try_with(|ctx| ctx.current_task_id.get()).unwrap_or(None) + CONTEXT.try_with(|ctx| ctx.current_task_id.get()).unwrap_or_default() } #[cfg(tokio_unstable)] diff --git a/tokio/src/runtime/metrics/runtime.rs b/tokio/src/runtime/metrics/runtime.rs index faf338701..ab586f5b7 100644 --- a/tokio/src/runtime/metrics/runtime.rs +++ b/tokio/src/runtime/metrics/runtime.rs @@ -474,8 +474,7 @@ impl RuntimeMetrics { .worker_metrics(0) .poll_count_histogram .as_ref() - .map(|histogram| histogram.num_buckets()) - .unwrap_or_default() + .map_or(0, |histogram| histogram.num_buckets()) } /// Deprecated. Use [`poll_time_histogram_num_buckets()`] instead. @@ -528,14 +527,13 @@ impl RuntimeMetrics { .worker_metrics(0) .poll_count_histogram .as_ref() - .map(|histogram| { + .map_or_else(Range::default, |histogram| { let range = histogram.bucket_range(bucket); std::ops::Range { start: Duration::from_nanos(range.start), end: Duration::from_nanos(range.end), } }) - .unwrap_or_default() } /// Deprecated. Use [`poll_time_histogram_bucket_range()`] instead. @@ -977,8 +975,7 @@ impl RuntimeMetrics { .worker_metrics(worker) .poll_count_histogram .as_ref() - .map(|histogram| histogram.get(bucket)) - .unwrap_or_default() + .map_or(0, |histogram| histogram.get(bucket)) } #[doc(hidden)] @@ -1096,8 +1093,7 @@ impl RuntimeMetrics { .worker_metrics(0) .schedule_latency_histogram .as_ref() - .map(|histogram| histogram.num_buckets()) - .unwrap_or_default() + .map_or(0, |histogram| histogram.num_buckets()) } /// Returns the range of task schedule latencies tracked by the given bucket. @@ -1140,14 +1136,13 @@ impl RuntimeMetrics { .worker_metrics(0) .schedule_latency_histogram .as_ref() - .map(|histogram| { + .map_or_else(Range::default, |histogram| { let range = histogram.bucket_range(bucket); std::ops::Range { start: Duration::from_nanos(range.start), end: Duration::from_nanos(range.end), } }) - .unwrap_or_default() } /// Returns the number of times the given worker polled tasks with a schedule @@ -1212,8 +1207,7 @@ impl RuntimeMetrics { .worker_metrics(worker) .schedule_latency_histogram .as_ref() - .map(|histogram| histogram.get(bucket)) - .unwrap_or_default() + .map_or(0, |histogram| histogram.get(bucket)) } } @@ -1303,8 +1297,7 @@ impl RuntimeMetrics { .driver() .io .as_ref() - .map(|h| f(&h.metrics)) - .unwrap_or(0) + .map_or(0, |h| f(&h.metrics)) } } } diff --git a/tokio/src/runtime/scheduler/mod.rs b/tokio/src/runtime/scheduler/mod.rs index 8bbd110cb..6175165cb 100644 --- a/tokio/src/runtime/scheduler/mod.rs +++ b/tokio/src/runtime/scheduler/mod.rs @@ -142,7 +142,7 @@ cfg_rt! { /// Returns true if this is a local runtime and the runtime is owned by the current thread. pub(crate) fn can_spawn_local_on_local_runtime(&self) -> bool { match self { - Handle::CurrentThread(h) => h.local_tid.map(|x| std::thread::current().id() == x).unwrap_or(false), + Handle::CurrentThread(h) => h.local_tid.is_some_and(|x| std::thread::current().id() == x), #[cfg(feature = "rt-multi-thread")] Handle::MultiThread(_) => false, diff --git a/tokio/src/runtime/task/trace/mod.rs b/tokio/src/runtime/task/trace/mod.rs index 8e088d5d4..de97a0938 100644 --- a/tokio/src/runtime/task/trace/mod.rs +++ b/tokio/src/runtime/task/trace/mod.rs @@ -147,7 +147,9 @@ impl Context { pub(crate) fn is_tracing() -> bool { // SAFETY: This call can only access the trace_leaf_fn field, so it cannot break the trace // frame linked list. - unsafe { Self::try_with_current(|ctx| ctx.trace_leaf_fn.get().is_some()).unwrap_or(false) } + unsafe { + Self::try_with_current(|ctx| ctx.trace_leaf_fn.get().is_some()).unwrap_or_default() + } } } diff --git a/tokio/src/runtime/time/mod.rs b/tokio/src/runtime/time/mod.rs index bbdb664c1..224d2ff46 100644 --- a/tokio/src/runtime/time/mod.rs +++ b/tokio/src/runtime/time/mod.rs @@ -425,8 +425,7 @@ impl Handle { Ok(when) => { if lock .next_wake - .map(|next_wake| when < next_wake.get()) - .unwrap_or(true) + .map_or(true, |next_wake| when < next_wake.get()) { unpark.unpark(); } diff --git a/tokio/src/runtime/time/wheel/mod.rs b/tokio/src/runtime/time/wheel/mod.rs index 5c6d8407e..ad1173619 100644 --- a/tokio/src/runtime/time/wheel/mod.rs +++ b/tokio/src/runtime/time/wheel/mod.rs @@ -105,8 +105,7 @@ impl Wheel { debug_assert!({ self.levels[level] .next_expiration(self.elapsed) - .map(|e| e.deadline >= self.elapsed) - .unwrap_or(true) + .map_or(true, |e| e.deadline >= self.elapsed) }); Ok(when) diff --git a/tokio/src/runtime/time_alt/wheel/mod.rs b/tokio/src/runtime/time_alt/wheel/mod.rs index 071ccbac6..b8fcbc801 100644 --- a/tokio/src/runtime/time_alt/wheel/mod.rs +++ b/tokio/src/runtime/time_alt/wheel/mod.rs @@ -84,8 +84,7 @@ impl Wheel { debug_assert!({ self.levels[level] .next_expiration(self.elapsed) - .map(|e| e.deadline >= self.elapsed) - .unwrap_or(true) + .map_or(true, |e| e.deadline >= self.elapsed) }); } diff --git a/tokio/src/task/local.rs b/tokio/src/task/local.rs index 4ad9c8329..4d467d0fb 100644 --- a/tokio/src/task/local.rs +++ b/tokio/src/task/local.rs @@ -1266,9 +1266,7 @@ impl LocalState { // if we couldn't get the thread ID because we're dropping the local // data, skip the assertion --- the `Drop` impl is not going to be // called from another thread, because `LocalSet` is `!Send` - context::thread_id() - .map(|id| id == self.owner) - .unwrap_or(true), + context::thread_id().map_or(true, |id| id == self.owner), "`LocalSet`'s local run queue must not be accessed by another thread!" ); }