diff --git a/.cirrus.yml b/.cirrus.yml index a7ce0d9d456..ec99c872d15 100644 --- a/.cirrus.yml +++ b/.cirrus.yml @@ -7,9 +7,9 @@ env: RUST_NIGHTLY: nightly-2024-05-05 RUSTFLAGS: -D warnings -# Test FreeBSD in a full VM on cirrus-ci.com. Test the i686 target too, in the -# same VM. The binary will be built in 32-bit mode, but will execute on a -# 64-bit kernel and in a 64-bit environment. Our tests don't execute any of +# Test FreeBSD in a full VM on cirrus-ci.com. Test the i686 target too, in the +# same VM. The binary will be built in 32-bit mode, but will execute on a +# 64-bit kernel and in a 64-bit environment. Our tests don't execute any of # the system's binaries, so the environment shouldn't matter. task: name: FreeBSD 64-bit diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ad7239f4476..08f4865318a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -560,7 +560,7 @@ _Adapted from the [Node.js contributing guide][node]_. The Tokio GitHub repository has a lot of issues and PRs to keep track of. This section explains the meaning of various labels, as well as our [GitHub -project][project]. The section is primarily targeted at maintainers. Most +project][project]. The section is primarily targeted at maintainers. Most contributors aren't able to set these labels. ### Area diff --git a/README.md b/README.md index fb567dd6a23..1d936f9cea7 100644 --- a/README.md +++ b/README.md @@ -196,7 +196,7 @@ release. The MSRV history for past minor releases can be found below: * 1.27 to 1.29 - Rust 1.56 * 1.17 to 1.26 - Rust 1.49 * 1.15 to 1.16 - Rust 1.46 - * 1.0 to 1.14 - Rust 1.45 + * 1.0 to 1.14 - Rust 1.45 Note that although we try to avoid the situation where a dependency transitively increases the MSRV of Tokio, we do not guarantee that this does not happen. diff --git a/benches/copy.rs b/benches/copy.rs index 5c4eab48943..cbe877b09f3 100644 --- a/benches/copy.rs +++ b/benches/copy.rs @@ -186,7 +186,7 @@ fn copy_mem_to_mem(c: &mut Criterion) { }; rt.block_on(task()); - }) + }); }); } @@ -202,7 +202,7 @@ fn copy_mem_to_slow_hdd(c: &mut Criterion) { }; rt.block_on(task()); - }) + }); }); } @@ -219,7 +219,7 @@ fn copy_chunk_to_mem(c: &mut Criterion) { }; rt.block_on(task()); - }) + }); }); } @@ -236,7 +236,7 @@ fn copy_chunk_to_slow_hdd(c: &mut Criterion) { }; rt.block_on(task()); - }) + }); }); } diff --git a/benches/fs.rs b/benches/fs.rs index 2964afbd46e..8289b458149 100644 --- a/benches/fs.rs +++ b/benches/fs.rs @@ -39,7 +39,7 @@ fn async_read_codec(c: &mut Criterion) { }; rt.block_on(task()); - }) + }); }); } @@ -98,7 +98,7 @@ fn sync_read(c: &mut Criterion) { for _i in 0..BLOCK_COUNT { file.read_exact(&mut buffer).unwrap(); } - }) + }); }); } diff --git a/benches/rt_current_thread.rs b/benches/rt_current_thread.rs index c62fd152fe6..f043708fa95 100644 --- a/benches/rt_current_thread.rs +++ b/benches/rt_current_thread.rs @@ -23,7 +23,7 @@ fn rt_curr_spawn_many_local(c: &mut Criterion) { handle.await.unwrap(); } }); - }) + }); }); } @@ -43,7 +43,7 @@ fn rt_curr_spawn_many_remote_idle(c: &mut Criterion) { handle.await.unwrap(); } }); - }) + }); }); } @@ -57,7 +57,7 @@ fn rt_curr_spawn_many_remote_busy(c: &mut Criterion) { tokio::spawn(async { iter() }); } - iter() + iter(); }); c.bench_function("spawn_many_remote_busy", |b| { @@ -71,7 +71,7 @@ fn rt_curr_spawn_many_remote_busy(c: &mut Criterion) { handle.await.unwrap(); } }); - }) + }); }); } diff --git a/benches/rt_multi_threaded.rs b/benches/rt_multi_threaded.rs index d333ebdaaae..8e6591045d5 100644 --- a/benches/rt_multi_threaded.rs +++ b/benches/rt_multi_threaded.rs @@ -40,7 +40,7 @@ fn rt_multi_spawn_many_local(c: &mut Criterion) { rx.recv().unwrap(); }); - }) + }); }); } @@ -60,7 +60,7 @@ fn rt_multi_spawn_many_remote_idle(c: &mut Criterion) { handle.await.unwrap(); } }); - }) + }); }); } @@ -94,7 +94,7 @@ fn rt_multi_spawn_many_remote_busy1(c: &mut Criterion) { handle.await.unwrap(); } }); - }) + }); }); flag.store(false, Relaxed); @@ -137,7 +137,7 @@ fn rt_multi_spawn_many_remote_busy2(c: &mut Criterion) { handle.await.unwrap(); } }); - }) + }); }); flag.store(false, Relaxed); @@ -167,7 +167,7 @@ fn rt_multi_yield_many(c: &mut Criterion) { for _ in 0..TASKS { rx.recv().unwrap(); } - }) + }); }); } @@ -212,7 +212,7 @@ fn rt_multi_ping_pong(c: &mut Criterion) { done_rx.recv().unwrap(); }); - }) + }); }); } @@ -243,7 +243,7 @@ fn rt_multi_chained_spawn(c: &mut Criterion) { done_rx.recv().unwrap(); }); - }) + }); }); } diff --git a/benches/signal.rs b/benches/signal.rs index af9fc1f3b97..92e30e3a9f2 100644 --- a/benches/signal.rs +++ b/benches/signal.rs @@ -88,7 +88,7 @@ fn many_signals(c: &mut Criterion) { rx.recv().await.expect("channel closed"); } }); - }) + }); }); } diff --git a/benches/spawn.rs b/benches/spawn.rs index 628a9b2c86f..c15ebb393cd 100644 --- a/benches/spawn.rs +++ b/benches/spawn.rs @@ -21,7 +21,7 @@ fn basic_scheduler_spawn(c: &mut Criterion) { let h = tokio::spawn(work()); assert_eq!(h.await.unwrap(), 2); }); - }) + }); }); } @@ -41,7 +41,7 @@ fn basic_scheduler_spawn10(c: &mut Criterion) { assert_eq!(handle.await.unwrap(), 2); } }); - }) + }); }); } @@ -56,7 +56,7 @@ fn threaded_scheduler_spawn(c: &mut Criterion) { let h = tokio::spawn(work()); assert_eq!(h.await.unwrap(), 2); }); - }) + }); }); } @@ -76,7 +76,7 @@ fn threaded_scheduler_spawn10(c: &mut Criterion) { assert_eq!(handle.await.unwrap(), 2); } }); - }) + }); }); } diff --git a/benches/sync_broadcast.rs b/benches/sync_broadcast.rs index a7dc2e37259..8a826bc45a1 100644 --- a/benches/sync_broadcast.rs +++ b/benches/sync_broadcast.rs @@ -63,8 +63,8 @@ fn contention_impl(g: &mut BenchmarkGroup) { } } } - }) - }) + }); + }); }); } diff --git a/benches/sync_mpsc.rs b/benches/sync_mpsc.rs index 1a3f37cab81..e4a7de8b8f3 100644 --- a/benches/sync_mpsc.rs +++ b/benches/sync_mpsc.rs @@ -30,21 +30,21 @@ fn create_medium(g: &mut BenchmarkGroup) { g.bench_function(SIZE.to_string(), |b| { b.iter(|| { black_box(&mpsc::channel::(SIZE)); - }) + }); }); } fn send_data(g: &mut BenchmarkGroup, prefix: &str) { let rt = rt(); - g.bench_function(format!("{}_{}", prefix, SIZE), |b| { + g.bench_function(format!("{prefix}_{SIZE}"), |b| { b.iter(|| { let (tx, mut rx) = mpsc::channel::(SIZE); let _ = rt.block_on(tx.send(T::default())); rt.block_on(rx.recv()).unwrap(); - }) + }); }); } @@ -68,8 +68,8 @@ fn contention_bounded(g: &mut BenchmarkGroup) { for _ in 0..1_000 * 5 { let _ = rx.recv().await; } - }) - }) + }); + }); }); } @@ -95,8 +95,8 @@ fn contention_bounded_recv_many(g: &mut BenchmarkGroup) { while total < 1_000 * 5 { total += rx.recv_many(&mut buffer, 5_000).await; } - }) - }) + }); + }); }); } @@ -120,8 +120,8 @@ fn contention_bounded_full(g: &mut BenchmarkGroup) { for _ in 0..1_000 * 5 { let _ = rx.recv().await; } - }) - }) + }); + }); }); } @@ -147,8 +147,8 @@ fn contention_bounded_full_recv_many(g: &mut BenchmarkGroup) { while total < 1_000 * 5 { total += rx.recv_many(&mut buffer, 5_000).await; } - }) - }) + }); + }); }); } @@ -172,8 +172,8 @@ fn contention_unbounded(g: &mut BenchmarkGroup) { for _ in 0..1_000 * 5 { let _ = rx.recv().await; } - }) - }) + }); + }); }); } @@ -199,8 +199,8 @@ fn contention_unbounded_recv_many(g: &mut BenchmarkGroup) { while total < 1_000 * 5 { total += rx.recv_many(&mut buffer, 5_000).await; } - }) - }) + }); + }); }); } @@ -219,8 +219,8 @@ fn uncontented_bounded(g: &mut BenchmarkGroup) { for _ in 0..5_000 { let _ = rx.recv().await; } - }) - }) + }); + }); }); } @@ -241,8 +241,8 @@ fn uncontented_bounded_recv_many(g: &mut BenchmarkGroup) { while total < 1_000 * 5 { total += rx.recv_many(&mut buffer, 5_000).await; } - }) - }) + }); + }); }); } @@ -261,8 +261,8 @@ fn uncontented_unbounded(g: &mut BenchmarkGroup) { for _ in 0..5_000 { let _ = rx.recv().await; } - }) - }) + }); + }); }); } @@ -283,8 +283,8 @@ fn uncontented_unbounded_recv_many(g: &mut BenchmarkGroup) { while total < 1_000 * 5 { total += rx.recv_many(&mut buffer, 5_000).await; } - }) - }) + }); + }); }); } diff --git a/benches/sync_mpsc_oneshot.rs b/benches/sync_mpsc_oneshot.rs index a0712c1e424..8e1e2e334d1 100644 --- a/benches/sync_mpsc_oneshot.rs +++ b/benches/sync_mpsc_oneshot.rs @@ -42,8 +42,8 @@ fn request_reply(b: &mut Criterion, rt: Runtime) { task_tx.send(o_tx).await.unwrap(); let _ = o_rx.await; } - }) - }) + }); + }); }); } diff --git a/benches/sync_notify.rs b/benches/sync_notify.rs index a50ad1efb38..264a6438d77 100644 --- a/benches/sync_notify.rs +++ b/benches/sync_notify.rs @@ -40,7 +40,7 @@ fn notify_waiters(g: &mut BenchmarkGroup) { break; } } - }) + }); }); } @@ -71,7 +71,7 @@ fn notify_one(g: &mut BenchmarkGroup) { break; } } - }) + }); }); } diff --git a/benches/sync_rwlock.rs b/benches/sync_rwlock.rs index 9b4c1ee49be..6548ffcb812 100644 --- a/benches/sync_rwlock.rs +++ b/benches/sync_rwlock.rs @@ -19,8 +19,8 @@ fn read_uncontended(g: &mut BenchmarkGroup) { let read = lock.read().await; let _read = black_box(read); } - }) - }) + }); + }); }); } @@ -49,8 +49,8 @@ fn read_concurrent_uncontended_multi(g: &mut BenchmarkGroup) { task::spawn(task(lock.clone())) }; j.unwrap(); - }) - }) + }); + }); }); } @@ -77,8 +77,8 @@ fn read_concurrent_uncontended(g: &mut BenchmarkGroup) { task(lock.clone()), task(lock.clone()) }; - }) - }) + }); + }); }); } @@ -108,8 +108,8 @@ fn read_concurrent_contended_multi(g: &mut BenchmarkGroup) { task::spawn(task(lock.clone())), }; j.unwrap(); - }) - }) + }); + }); }); } @@ -137,8 +137,8 @@ fn read_concurrent_contended(g: &mut BenchmarkGroup) { task(lock.clone()), task(lock.clone()), }; - }) - }) + }); + }); }); } diff --git a/benches/sync_semaphore.rs b/benches/sync_semaphore.rs index e664e64c94b..ed6ed39592b 100644 --- a/benches/sync_semaphore.rs +++ b/benches/sync_semaphore.rs @@ -30,8 +30,8 @@ fn uncontended(g: &mut BenchmarkGroup) { let permit = s.acquire().await; drop(permit); } - }) - }) + }); + }); }); } @@ -57,8 +57,8 @@ fn uncontended_concurrent_multi(g: &mut BenchmarkGroup) { task::spawn(task(s.clone())) }; j.unwrap(); - }) - }) + }); + }); }); } @@ -78,8 +78,8 @@ fn uncontended_concurrent_single(g: &mut BenchmarkGroup) { task(s.clone()), task(s.clone()) }; - }) - }) + }); + }); }); } @@ -100,8 +100,8 @@ fn contended_concurrent_multi(g: &mut BenchmarkGroup) { task::spawn(task(s.clone())) }; j.unwrap(); - }) - }) + }); + }); }); } @@ -121,8 +121,8 @@ fn contended_concurrent_single(g: &mut BenchmarkGroup) { task(s.clone()), task(s.clone()) }; - }) - }) + }); + }); }); } diff --git a/benches/sync_watch.rs b/benches/sync_watch.rs index 94f3339fbec..5cb71275688 100644 --- a/benches/sync_watch.rs +++ b/benches/sync_watch.rs @@ -67,7 +67,7 @@ fn contention_resubscribe(g: &mut BenchmarkGroup .unwrap(); } }); - }) + }); }); } diff --git a/benches/time_now.rs b/benches/time_now.rs index d87db2121f1..30524af06f5 100644 --- a/benches/time_now.rs +++ b/benches/time_now.rs @@ -14,8 +14,8 @@ fn time_now_current_thread(c: &mut Criterion) { b.iter(|| { rt.block_on(async { black_box(tokio::time::Instant::now()); - }) - }) + }); + }); }); } diff --git a/benches/time_timeout.rs b/benches/time_timeout.rs index 9dedee9ddcd..3c96f3354d1 100644 --- a/benches/time_timeout.rs +++ b/benches/time_timeout.rs @@ -43,7 +43,7 @@ fn do_timeout_test(c: &mut Criterion, workers: usize, name: &str) { black_box(spawn_timeout_job(iters as usize, workers)).await; }); start.elapsed() - }) + }); }); } @@ -80,7 +80,7 @@ fn do_sleep_test(c: &mut Criterion, workers: usize, name: &str) { black_box(spawn_sleep_job(iters as usize, workers)).await; }); start.elapsed() - }) + }); }); } diff --git a/examples/chat.rs b/examples/chat.rs index c4959d38ead..f0e3ba28517 100644 --- a/examples/chat.rs +++ b/examples/chat.rs @@ -138,8 +138,8 @@ impl Shared { /// Send a `LineCodec` encoded message to every peer, except /// for the sender. - async fn broadcast(&mut self, sender: SocketAddr, message: &str) { - for peer in self.peers.iter_mut() { + fn broadcast(&mut self, sender: SocketAddr, message: &str) { + for peer in &mut self.peers { if *peer.0 != sender { let _ = peer.1.send(message.into()); } @@ -178,13 +178,10 @@ async fn process( lines.send("Please enter your username:").await?; // Read the first line from the `LineCodec` stream to get the username. - let username = match lines.next().await { - Some(Ok(line)) => line, + let Some(Ok(username)) = lines.next().await else { // We didn't get a line so we return early here. - _ => { - tracing::error!("Failed to get username from {}. Client disconnected.", addr); - return Ok(()); - } + tracing::error!("Failed to get username from {}. Client disconnected.", addr); + return Ok(()); }; // Register our peer with state which internally sets up some channels. @@ -193,9 +190,9 @@ async fn process( // A client has connected, let's let everyone know. { let mut state = state.lock().await; - let msg = format!("{} has joined the chat", username); + let msg = format!("{username} has joined the chat"); tracing::info!("{}", msg); - state.broadcast(addr, &msg).await; + state.broadcast(addr, &msg); } // Process incoming messages until our stream is exhausted by a disconnect. @@ -210,9 +207,9 @@ async fn process( // broadcast this message to the other users. Some(Ok(msg)) => { let mut state = state.lock().await; - let msg = format!("{}: {}", username, msg); + let msg = format!("{username}: {msg}"); - state.broadcast(addr, &msg).await; + state.broadcast(addr, &msg); } // An error occurred. Some(Err(e)) => { @@ -234,9 +231,9 @@ async fn process( let mut state = state.lock().await; state.peers.remove(&addr); - let msg = format!("{} has left the chat", username); + let msg = format!("{username} has left the chat"); tracing::info!("{}", msg); - state.broadcast(addr, &msg).await; + state.broadcast(addr, &msg); } Ok(()) diff --git a/examples/connect.rs b/examples/connect.rs index 836d7f8f2e3..3111e2e3c36 100644 --- a/examples/connect.rs +++ b/examples/connect.rs @@ -16,6 +16,7 @@ #![warn(rust_2018_idioms)] +use bytes::BytesMut; use futures::StreamExt; use tokio::io; use tokio_util::codec::{BytesCodec, FramedRead, FramedWrite}; @@ -43,7 +44,7 @@ async fn main() -> Result<(), Box> { let addr = addr.parse::()?; let stdin = FramedRead::new(io::stdin(), BytesCodec::new()); - let stdin = stdin.map(|i| i.map(|bytes| bytes.freeze())); + let stdin = stdin.map(|i| i.map(BytesMut::freeze)); let stdout = FramedWrite::new(io::stdout(), BytesCodec::new()); if tcp { @@ -77,7 +78,7 @@ mod tcp { //BytesMut into Bytes Ok(i) => future::ready(Some(i.freeze())), Err(e) => { - println!("failed to read from socket; error={}", e); + println!("failed to read from socket; error={e}"); future::ready(None) } }) diff --git a/examples/dump.rs b/examples/dump.rs index 6f744713f7c..eb133a2328a 100644 --- a/examples/dump.rs +++ b/examples/dump.rs @@ -89,5 +89,5 @@ async fn main() -> Result<(), Box> { any(target_arch = "aarch64", target_arch = "x86", target_arch = "x86_64") )))] fn main() { - println!("task dumps are not available") + println!("task dumps are not available"); } diff --git a/examples/echo-udp.rs b/examples/echo-udp.rs index 3027c869696..8f9ed7088eb 100644 --- a/examples/echo-udp.rs +++ b/examples/echo-udp.rs @@ -38,7 +38,7 @@ impl Server { if let Some((size, peer)) = to_send { let amt = socket.send_to(&buf[..size], &peer).await?; - println!("Echoed {}/{} bytes to {}", amt, size, peer); + println!("Echoed {amt}/{size} bytes to {peer}"); } // If we're here then `to_send` is `None`, so we take a look for the diff --git a/examples/echo.rs b/examples/echo.rs index aece8dc6593..045950ade25 100644 --- a/examples/echo.rs +++ b/examples/echo.rs @@ -40,7 +40,7 @@ async fn main() -> Result<(), Box> { // connections. This TCP listener is bound to the address we determined // above and must be associated with an event loop. let listener = TcpListener::bind(&addr).await?; - println!("Listening on: {}", addr); + println!("Listening on: {addr}"); loop { // Asynchronously wait for an inbound socket. diff --git a/examples/print_each_packet.rs b/examples/print_each_packet.rs index 087f9cf03eb..3e568bd62ea 100644 --- a/examples/print_each_packet.rs +++ b/examples/print_each_packet.rs @@ -75,7 +75,7 @@ async fn main() -> Result<(), Box> { // to our event loop. After the socket's created we inform that we're ready // to go and start accepting connections. let listener = TcpListener::bind(&addr).await?; - println!("Listening on: {}", addr); + println!("Listening on: {addr}"); loop { // Asynchronously wait for an inbound socket. @@ -96,8 +96,8 @@ async fn main() -> Result<(), Box> { // The stream will return None once the client disconnects. while let Some(message) = framed.next().await { match message { - Ok(bytes) => println!("bytes: {:?}", bytes), - Err(err) => println!("Socket closed with error: {:?}", err), + Ok(bytes) => println!("bytes: {bytes:?}"), + Err(err) => println!("Socket closed with error: {err:?}"), } } println!("Socket received FIN packet and closed connection"); diff --git a/examples/proxy.rs b/examples/proxy.rs index 9260a12fb56..2059bacb415 100644 --- a/examples/proxy.rs +++ b/examples/proxy.rs @@ -38,8 +38,8 @@ async fn main() -> Result<(), Box> { .nth(2) .unwrap_or_else(|| "127.0.0.1:8080".to_string()); - println!("Listening on: {}", listen_addr); - println!("Proxying to: {}", server_addr); + println!("Listening on: {listen_addr}"); + println!("Proxying to: {server_addr}"); let listener = TcpListener::bind(listen_addr).await?; @@ -50,10 +50,10 @@ async fn main() -> Result<(), Box> { copy_bidirectional(&mut inbound, &mut outbound) .map(|r| { if let Err(e) = r { - println!("Failed to transfer; error={}", e); + println!("Failed to transfer; error={e}"); } }) - .await + .await; }); } diff --git a/examples/tinydb.rs b/examples/tinydb.rs index 5a1983df6b4..b6fd0a90744 100644 --- a/examples/tinydb.rs +++ b/examples/tinydb.rs @@ -90,7 +90,7 @@ async fn main() -> Result<(), Box> { .unwrap_or_else(|| "127.0.0.1:8080".to_string()); let listener = TcpListener::bind(&addr).await?; - println!("Listening on: {}", addr); + println!("Listening on: {addr}"); // Create the shared state of this server that will be shared amongst all // clients. We populate the initial database and then create the `Database` @@ -131,11 +131,11 @@ async fn main() -> Result<(), Box> { let response = response.serialize(); if let Err(e) = lines.send(response.as_str()).await { - println!("error on sending response; error = {:?}", e); + println!("error on sending response; error = {e:?}"); } } Err(e) => { - println!("error on decoding from socket; error = {:?}", e); + println!("error on decoding from socket; error = {e:?}"); } } } @@ -143,7 +143,7 @@ async fn main() -> Result<(), Box> { // The connection will be closed at this point as `lines.next()` has returned `None`. }); } - Err(e) => println!("error accepting socket; error = {:?}", e), + Err(e) => println!("error accepting socket; error = {e:?}"), } } } @@ -162,7 +162,7 @@ fn handle_request(line: &str, db: &Arc) -> Response { value: value.clone(), }, None => Response::Error { - msg: format!("no key {}", key), + msg: format!("no key {key}"), }, }, Request::Set { key, value } => { @@ -190,20 +190,18 @@ impl Request { }) } Some("SET") => { - let key = match parts.next() { - Some(key) => key, - None => return Err("SET must be followed by a key".into()), + let Some(key) = parts.next() else { + return Err("SET must be followed by a key".into()); }; - let value = match parts.next() { - Some(value) => value, - None => return Err("SET needs a value".into()), + let Some(value) = parts.next() else { + return Err("SET needs a value".into()); }; Ok(Request::Set { key: key.to_string(), value: value.to_string(), }) } - Some(cmd) => Err(format!("unknown command: {}", cmd)), + Some(cmd) => Err(format!("unknown command: {cmd}")), None => Err("empty input".into()), } } @@ -212,13 +210,13 @@ impl Request { impl Response { fn serialize(&self) -> String { match *self { - Response::Value { ref key, ref value } => format!("{} = {}", key, value), + Response::Value { ref key, ref value } => format!("{key} = {value}"), Response::Set { ref key, ref value, ref previous, - } => format!("set {} = `{}`, previous: {:?}", key, value, previous), - Response::Error { ref msg } => format!("error: {}", msg), + } => format!("set {key} = `{value}`, previous: {previous:?}"), + Response::Error { ref msg } => format!("error: {msg}"), } } } diff --git a/examples/tinyhttp.rs b/examples/tinyhttp.rs index dceccf47a89..66a242af42e 100644 --- a/examples/tinyhttp.rs +++ b/examples/tinyhttp.rs @@ -31,13 +31,13 @@ async fn main() -> Result<(), Box> { .nth(1) .unwrap_or_else(|| "127.0.0.1:8080".to_string()); let server = TcpListener::bind(&addr).await?; - println!("Listening on: {}", addr); + println!("Listening on: {addr}"); loop { let (stream, _) = server.accept().await?; tokio::spawn(async move { if let Err(e) = process(stream).await { - println!("failed to process connection; error = {}", e); + println!("failed to process connection; error = {e}"); } }); } @@ -49,7 +49,7 @@ async fn process(stream: TcpStream) -> Result<(), Box> { while let Some(request) = transport.next().await { match request { Ok(request) => { - let response = respond(request).await?; + let response = respond(request)?; transport.send(response).await?; } Err(e) => return Err(e.into()), @@ -59,7 +59,7 @@ async fn process(stream: TcpStream) -> Result<(), Box> { Ok(()) } -async fn respond(req: Request<()>) -> Result, Box> { +fn respond(req: Request<()>) -> Result, Box> { let mut response = Response::builder(); let body = match req.uri().path() { "/plaintext" => { @@ -159,7 +159,7 @@ impl Decoder for Http { let mut parsed_headers = [httparse::EMPTY_HEADER; 16]; let mut r = httparse::Request::new(&mut parsed_headers); let status = r.parse(src).map_err(|e| { - let msg = format!("failed to parse http request: {:?}", e); + let msg = format!("failed to parse http request: {e:?}"); io::Error::new(io::ErrorKind::Other, msg) })?; @@ -203,20 +203,19 @@ impl Decoder for Http { let s = unsafe { String::from_utf8_unchecked(Vec::from(s.as_ref())) }; ret = ret.uri(s); ret = ret.version(http::Version::HTTP_11); - for header in headers.iter() { - let (k, v) = match *header { - Some((ref k, ref v)) => (k, v), - None => break, + for header in &headers { + let Some((k, v)) = header else { + break; }; let value = HeaderValue::from_bytes(data.slice(v.0..v.1).as_ref()) .map_err(|_| io::Error::new(io::ErrorKind::Other, "header decode error"))?; ret = ret.header(&data[k.0..k.1], value); } - let req = ret + let request = ret .body(()) .map_err(|e| io::Error::new(io::ErrorKind::Other, e))?; - Ok(Some(req)) + Ok(Some(request)) } } diff --git a/examples/udp-codec.rs b/examples/udp-codec.rs index c587be9abfd..7f0a9080ca2 100644 --- a/examples/udp-codec.rs +++ b/examples/udp-codec.rs @@ -46,7 +46,7 @@ async fn main() -> Result<(), Box> { // Run both futures simultaneously of `a` and `b` sending messages back and forth. match tokio::try_join!(a, b) { - Err(e) => println!("an error occurred; error = {:?}", e), + Err(e) => println!("an error occurred; error = {e:?}"), _ => println!("done!"), } diff --git a/tests-integration/tests/macros_main.rs b/tests-integration/tests/macros_main.rs index 31442805141..d66f714704d 100644 --- a/tests-integration/tests/macros_main.rs +++ b/tests-integration/tests/macros_main.rs @@ -24,5 +24,5 @@ fn main_with_spawn() { #[test] fn shell() { assert_eq!(1, basic_main()); - assert_eq!(bool::default(), generic_fun::()) + assert_eq!(bool::default(), generic_fun::()); } diff --git a/tests-integration/tests/macros_pin.rs b/tests-integration/tests/macros_pin.rs index 37d8f70f413..0c283f94482 100644 --- a/tests-integration/tests/macros_pin.rs +++ b/tests-integration/tests/macros_pin.rs @@ -7,6 +7,6 @@ fn pin() { block_on(async { let future = my_async_fn(); tokio::pin!(future); - (&mut future).await + (&mut future).await; }); } diff --git a/tests-integration/tests/process_stdio.rs b/tests-integration/tests/process_stdio.rs index 526fd9ca607..c39355c3657 100644 --- a/tests-integration/tests/process_stdio.rs +++ b/tests-integration/tests/process_stdio.rs @@ -24,7 +24,7 @@ async fn feed_cat(mut cat: Child, n: usize) -> io::Result { // Produce n lines on the child's stdout. let write = async { for i in 0..n { - let bytes = format!("line {}\n", i).into_bytes(); + let bytes = format!("line {i}\n").into_bytes(); stdin.write_all(&bytes).await.unwrap(); } @@ -51,7 +51,7 @@ async fn feed_cat(mut cat: Child, n: usize) -> io::Result { (false, 0) => panic!("broken pipe"), (true, n) if n != 0 => panic!("extraneous data"), _ => { - let expected = format!("line {}", num_lines); + let expected = format!("line {num_lines}"); assert_eq!(expected, data); } }; diff --git a/tokio-macros/src/entry.rs b/tokio-macros/src/entry.rs index acdc2610f44..d2e4d67ac39 100644 --- a/tokio-macros/src/entry.rs +++ b/tokio-macros/src/entry.rs @@ -20,7 +20,7 @@ impl RuntimeFlavor { "single_thread" => Err("The single threaded runtime flavor is called `current_thread`.".to_string()), "basic_scheduler" => Err("The `basic_scheduler` runtime flavor has been renamed to `current_thread`.".to_string()), "threaded_scheduler" => Err("The `threaded_scheduler` runtime flavor has been renamed to `multi_thread`.".to_string()), - _ => Err(format!("No such runtime flavor `{}`. The runtime flavors are `current_thread` and `multi_thread`.", s)), + _ => Err(format!("No such runtime flavor `{s}`. The runtime flavors are `current_thread` and `multi_thread`.")), } } } @@ -36,7 +36,7 @@ impl UnhandledPanic { match s { "ignore" => Ok(UnhandledPanic::Ignore), "shutdown_runtime" => Ok(UnhandledPanic::ShutdownRuntime), - _ => Err(format!("No such unhandled panic behavior `{}`. The unhandled panic behaviors are `ignore` and `shutdown_runtime`.", s)), + _ => Err(format!("No such unhandled panic behavior `{s}`. The unhandled panic behaviors are `ignore` and `shutdown_runtime`.")), } } @@ -239,12 +239,12 @@ fn parse_int(int: syn::Lit, span: Span, field: &str) -> Result Ok(value), Err(e) => Err(syn::Error::new( span, - format!("Failed to parse value of `{}` as integer: {}", field, e), + format!("Failed to parse value of `{field}` as integer: {e}"), )), }, _ => Err(syn::Error::new( span, - format!("Failed to parse value of `{}` as integer.", field), + format!("Failed to parse value of `{field}` as integer."), )), } } @@ -255,7 +255,7 @@ fn parse_string(int: syn::Lit, span: Span, field: &str) -> Result Ok(s.to_string()), _ => Err(syn::Error::new( span, - format!("Failed to parse value of `{}` as string.", field), + format!("Failed to parse value of `{field}` as string."), )), } } @@ -275,7 +275,7 @@ fn parse_path(lit: syn::Lit, span: Span, field: &str) -> Result Err(syn::Error::new( span, - format!("Failed to parse value of `{}` as path.", field), + format!("Failed to parse value of `{field}` as path."), )), } } @@ -285,7 +285,7 @@ fn parse_bool(bool: syn::Lit, span: Span, field: &str) -> Result Ok(b.value), _ => Err(syn::Error::new( span, - format!("Failed to parse value of `{}` as bool.", field), + format!("Failed to parse value of `{field}` as bool."), )), } } @@ -342,8 +342,7 @@ fn build_config( } name => { let msg = format!( - "Unknown attribute {} is specified; expected one of: `flavor`, `worker_threads`, `start_paused`, `crate`, `unhandled_panic`", - name, + "Unknown attribute {name} is specified; expected one of: `flavor`, `worker_threads`, `start_paused`, `crate`, `unhandled_panic`" ); return Err(syn::Error::new_spanned(namevalue, msg)); } @@ -357,22 +356,18 @@ fn build_config( .to_lowercase(); let msg = match name.as_str() { "threaded_scheduler" | "multi_thread" => { - format!( - "Set the runtime flavor with #[{}(flavor = \"multi_thread\")].", - macro_name - ) + format!("Set the runtime flavor with #[{macro_name}(flavor = \"multi_thread\")].") } "basic_scheduler" | "current_thread" | "single_threaded" => { format!( - "Set the runtime flavor with #[{}(flavor = \"current_thread\")].", - macro_name + "Set the runtime flavor with #[{macro_name}(flavor = \"current_thread\")]." ) } "flavor" | "worker_threads" | "start_paused" | "crate" | "unhandled_panic" => { - format!("The `{}` attribute requires an argument.", name) + format!("The `{name}` attribute requires an argument.") } name => { - format!("Unknown attribute {} is specified; expected one of: `flavor`, `worker_threads`, `start_paused`, `crate`, `unhandled_panic`.", name) + format!("Unknown attribute {name} is specified; expected one of: `flavor`, `worker_threads`, `start_paused`, `crate`, `unhandled_panic`.") } }; return Err(syn::Error::new_spanned(path, msg)); @@ -516,9 +511,8 @@ pub(crate) fn main(args: TokenStream, item: TokenStream, rt_multi_thread: bool) // * `#[core::prelude::*::test]` or `#[::core::prelude::*::test]` // * `#[std::prelude::*::test]` or `#[::std::prelude::*::test]` fn is_test_attribute(attr: &Attribute) -> bool { - let path = match &attr.meta { - syn::Meta::Path(path) => path, - _ => return false, + let syn::Meta::Path(path) = &attr.meta else { + return false; }; let candidates = [ ["core", "prelude", "*", "test"], diff --git a/tokio-macros/src/select.rs b/tokio-macros/src/select.rs index 324b8f942e3..0ef6cfbee2f 100644 --- a/tokio-macros/src/select.rs +++ b/tokio-macros/src/select.rs @@ -11,7 +11,7 @@ pub(crate) fn declare_output_enum(input: TokenStream) -> TokenStream { }; let variants = (0..branches) - .map(|num| Ident::new(&format!("_{}", num), Span::call_site())) + .map(|num| Ident::new(&format!("_{num}"), Span::call_site())) .collect::>(); // Use a bitfield to track which futures completed diff --git a/tokio-stream/src/stream_ext/collect.rs b/tokio-stream/src/stream_ext/collect.rs index 60b94d3fd0e..f0a5cfc452d 100644 --- a/tokio-stream/src/stream_ext/collect.rs +++ b/tokio-stream/src/stream_ext/collect.rs @@ -68,11 +68,8 @@ where loop { let me = self.as_mut().project(); - let item = match ready!(me.stream.poll_next(cx)) { - Some(item) => item, - None => { - return Ready(U::finalize(sealed::Internal, me.collection)); - } + let Some(item) = ready!(me.stream.poll_next(cx)) else { + return Ready(U::finalize(sealed::Internal, me.collection)); }; if !U::extend(sealed::Internal, me.collection, item) { diff --git a/tokio-stream/src/wrappers/broadcast.rs b/tokio-stream/src/wrappers/broadcast.rs index 711066466a0..f8af6e46a70 100644 --- a/tokio-stream/src/wrappers/broadcast.rs +++ b/tokio-stream/src/wrappers/broadcast.rs @@ -30,7 +30,7 @@ pub enum BroadcastStreamRecvError { impl fmt::Display for BroadcastStreamRecvError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - BroadcastStreamRecvError::Lagged(amt) => write!(f, "channel lagged by {}", amt), + BroadcastStreamRecvError::Lagged(amt) => write!(f, "channel lagged by {amt}"), } } } diff --git a/tokio-stream/src/wrappers/watch.rs b/tokio-stream/src/wrappers/watch.rs index a1ea646035a..998fdb5a0e2 100644 --- a/tokio-stream/src/wrappers/watch.rs +++ b/tokio-stream/src/wrappers/watch.rs @@ -103,16 +103,13 @@ impl Stream for WatchStream { fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { let (result, mut rx) = ready!(self.inner.poll(cx)); - match result { - Ok(_) => { - let received = (*rx.borrow_and_update()).clone(); - self.inner.set(make_future(rx)); - Poll::Ready(Some(received)) - } - Err(_) => { - self.inner.set(make_future(rx)); - Poll::Ready(None) - } + if result.is_ok() { + let received = (*rx.borrow_and_update()).clone(); + self.inner.set(make_future(rx)); + Poll::Ready(Some(received)) + } else { + self.inner.set(make_future(rx)); + Poll::Ready(None) } } } diff --git a/tokio-stream/tests/watch.rs b/tokio-stream/tests/watch.rs index 3a39aaf3db7..c48b4ae6416 100644 --- a/tokio-stream/tests/watch.rs +++ b/tokio-stream/tests/watch.rs @@ -12,13 +12,11 @@ async fn watch_stream_message_not_twice() { let mut counter = 0; let mut stream = WatchStream::new(rx).map(move |payload| { - println!("{}", payload); + println!("{payload}"); if payload == "goodbye" { counter += 1; } - if counter >= 2 { - panic!("too many goodbyes"); - } + assert!(counter < 2, "too many goodbyes"); }); let task = tokio::spawn(async move { while stream.next().await.is_some() {} }); diff --git a/tokio-test/src/stream_mock.rs b/tokio-test/src/stream_mock.rs index a3f3c776502..b48269207f5 100644 --- a/tokio-test/src/stream_mock.rs +++ b/tokio-test/src/stream_mock.rs @@ -161,8 +161,7 @@ impl Drop for StreamMock { assert!( undropped_count == 0, - "StreamMock was dropped before all actions were consumed, {} actions were not consumed", - undropped_count + "StreamMock was dropped before all actions were consumed, {undropped_count} actions were not consumed" ); } } diff --git a/tokio-test/tests/io.rs b/tokio-test/tests/io.rs index 5f2ed427cd3..effac9a51fa 100644 --- a/tokio-test/tests/io.rs +++ b/tokio-test/tests/io.rs @@ -34,7 +34,7 @@ async fn read_error() { match mock.read(&mut buf).await { Err(error) => { assert_eq!(error.kind(), io::ErrorKind::Other); - assert_eq!("cruel", format!("{}", error)); + assert_eq!("cruel", format!("{error}")); } Ok(_) => panic!("error not received"), } @@ -87,7 +87,7 @@ async fn write_error() { match mock.write_all(b"whoa").await { Err(error) => { assert_eq!(error.kind(), io::ErrorKind::Other); - assert_eq!("cruel", format!("{}", error)); + assert_eq!("cruel", format!("{error}")); } Ok(_) => panic!("error not received"), } diff --git a/tokio-util/src/codec/any_delimiter_codec.rs b/tokio-util/src/codec/any_delimiter_codec.rs index fc5e57582db..ad012252b3e 100644 --- a/tokio-util/src/codec/any_delimiter_codec.rs +++ b/tokio-util/src/codec/any_delimiter_codec.rs @@ -249,7 +249,7 @@ impl fmt::Display for AnyDelimiterCodecError { AnyDelimiterCodecError::MaxChunkLengthExceeded => { write!(f, "max chunk length exceeded") } - AnyDelimiterCodecError::Io(e) => write!(f, "{}", e), + AnyDelimiterCodecError::Io(e) => write!(f, "{e}"), } } } diff --git a/tokio-util/src/codec/length_delimited.rs b/tokio-util/src/codec/length_delimited.rs index fed49ca8a79..7c088f1557d 100644 --- a/tokio-util/src/codec/length_delimited.rs +++ b/tokio-util/src/codec/length_delimited.rs @@ -271,7 +271,7 @@ //! second half of the head is needed. //! //! `length_field_offset` indicates how many bytes to skip before starting -//! to read the length field. `length_adjustment` is the number of bytes to +//! to read the length field. `length_adjustment` is the number of bytes to //! skip starting at the end of the length field. In this case, it is the //! second half of the head. //! diff --git a/tokio-util/src/codec/lines_codec.rs b/tokio-util/src/codec/lines_codec.rs index 0da19238b63..47f68d88fda 100644 --- a/tokio-util/src/codec/lines_codec.rs +++ b/tokio-util/src/codec/lines_codec.rs @@ -218,7 +218,7 @@ impl fmt::Display for LinesCodecError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { LinesCodecError::MaxLineLengthExceeded => write!(f, "max line length exceeded"), - LinesCodecError::Io(e) => write!(f, "{}", e), + LinesCodecError::Io(e) => write!(f, "{e}"), } } } diff --git a/tokio-util/src/codec/mod.rs b/tokio-util/src/codec/mod.rs index 50f01c28fa7..37966249aa4 100644 --- a/tokio-util/src/codec/mod.rs +++ b/tokio-util/src/codec/mod.rs @@ -77,7 +77,7 @@ //! A [`Decoder`] is used together with [`FramedRead`] or [`Framed`] to turn an //! [`AsyncRead`] into a [`Stream`]. The job of the decoder trait is to specify //! how sequences of bytes are turned into a sequence of frames, and to -//! determine where the boundaries between frames are. The job of the +//! determine where the boundaries between frames are. The job of the //! `FramedRead` is to repeatedly switch between reading more data from the IO //! resource, and asking the decoder whether we have received enough data to //! decode another frame of data. @@ -108,7 +108,7 @@ //! It is guaranteed that, from one call to `decode` to another, the provided //! buffer will contain the exact same data as before, except that if more data //! has arrived through the IO resource, that data will have been appended to -//! the buffer. This means that reading frames from a `FramedRead` is +//! the buffer. This means that reading frames from a `FramedRead` is //! essentially equivalent to the following loop: //! //! ```no_run @@ -217,7 +217,7 @@ //! //! An [`Encoder`] is used together with [`FramedWrite`] or [`Framed`] to turn //! an [`AsyncWrite`] into a [`Sink`]. The job of the encoder trait is to -//! specify how frames are turned into a sequences of bytes. The job of the +//! specify how frames are turned into a sequences of bytes. The job of the //! `FramedWrite` is to take the resulting sequence of bytes and write it to the //! IO resource. //! diff --git a/tokio-util/src/compat.rs b/tokio-util/src/compat.rs index 423bd956da0..33fb15ac709 100644 --- a/tokio-util/src/compat.rs +++ b/tokio-util/src/compat.rs @@ -158,7 +158,7 @@ where } fn consume(self: Pin<&mut Self>, amt: usize) { - futures_io::AsyncBufRead::consume(self.project().inner, amt) + futures_io::AsyncBufRead::consume(self.project().inner, amt); } } @@ -174,7 +174,7 @@ where } fn consume(self: Pin<&mut Self>, amt: usize) { - tokio::io::AsyncBufRead::consume(self.project().inner, amt) + tokio::io::AsyncBufRead::consume(self.project().inner, amt); } } diff --git a/tokio-util/src/io/reader_stream.rs b/tokio-util/src/io/reader_stream.rs index 866c11408d5..6f54c75b6b0 100644 --- a/tokio-util/src/io/reader_stream.rs +++ b/tokio-util/src/io/reader_stream.rs @@ -90,9 +90,8 @@ impl Stream for ReaderStream { let mut this = self.as_mut().project(); - let reader = match this.reader.as_pin_mut() { - Some(r) => r, - None => return Poll::Ready(None), + let Some(reader) = this.reader.as_pin_mut() else { + return Poll::Ready(None); }; if this.buf.capacity() == 0 { diff --git a/tokio-util/src/io/sync_bridge.rs b/tokio-util/src/io/sync_bridge.rs index 2402207584c..61a04c5cbe5 100644 --- a/tokio-util/src/io/sync_bridge.rs +++ b/tokio-util/src/io/sync_bridge.rs @@ -20,7 +20,7 @@ impl BufRead for SyncIoBridge { fn consume(&mut self, amt: usize) { let src = &mut self.src; - AsyncBufReadExt::consume(src, amt) + AsyncBufReadExt::consume(src, amt); } fn read_until(&mut self, byte: u8, buf: &mut Vec) -> std::io::Result { @@ -122,9 +122,9 @@ impl SyncIoBridge { /// by e.g. [`tokio::task::spawn_blocking`]. /// /// Stated even more strongly: to make use of this bridge, you *must* move - /// it into a separate thread outside the runtime. The synchronous I/O will use the + /// it into a separate thread outside the runtime. The synchronous I/O will use the /// underlying handle to block on the backing asynchronous source, via - /// [`tokio::runtime::Handle::block_on`]. As noted in the documentation for that + /// [`tokio::runtime::Handle::block_on`]. As noted in the documentation for that /// function, an attempt to `block_on` from an asynchronous execution context /// will panic. /// diff --git a/tokio-util/src/sync/mpsc.rs b/tokio-util/src/sync/mpsc.rs index 8e2ff814622..98977d3a102 100644 --- a/tokio-util/src/sync/mpsc.rs +++ b/tokio-util/src/sync/mpsc.rs @@ -15,7 +15,7 @@ impl PollSendError { /// Consumes the stored value, if any. /// /// If this error was encountered when calling `start_send`/`send_item`, this will be the item - /// that the caller attempted to send. Otherwise, it will be `None`. + /// that the caller attempted to send. Otherwise, it will be `None`. pub fn into_inner(self) -> Option { self.0 } @@ -47,7 +47,7 @@ pub struct PollSender { acquire: PollSenderFuture, } -// Creates a future for acquiring a permit from the underlying channel. This is used to ensure +// Creates a future for acquiring a permit from the underlying channel. This is used to ensure // there's capacity for a send to complete. // // By reusing the same async fn for both `Some` and `None`, we make sure every future passed to @@ -133,7 +133,7 @@ impl PollSender { /// /// # Errors /// - /// If the channel is closed, an error will be returned. This is a permanent state. + /// If the channel is closed, an error will be returned. This is a permanent state. pub fn poll_reserve(&mut self, cx: &mut Context<'_>) -> Poll>> { loop { let (result, next_state) = match self.take_state() { @@ -173,7 +173,7 @@ impl PollSender { /// /// # Errors /// - /// If the channel is closed, an error will be returned. This is a permanent state. + /// If the channel is closed, an error will be returned. This is a permanent state. /// /// # Panics /// @@ -221,8 +221,8 @@ impl PollSender { /// remain open until all senders have dropped, or until the [`Receiver`] closes the channel. /// /// If a slot was previously reserved by calling `poll_reserve`, then a final call can be made - /// to `send_item` in order to consume the reserved slot. After that, no further sends will be - /// possible. If you do not intend to send another item, you can release the reserved slot back + /// to `send_item` in order to consume the reserved slot. After that, no further sends will be + /// possible. If you do not intend to send another item, you can release the reserved slot back /// to the underlying sender by calling [`abort_send`]. /// /// [`abort_send`]: crate::sync::PollSender::abort_send @@ -232,7 +232,7 @@ impl PollSender { self.sender = None; // If we're already idle, closed, or we haven't yet reserved a slot, we can quickly - // transition to the closed state. Otherwise, leave the existing permit in place for the + // transition to the closed state. Otherwise, leave the existing permit in place for the // caller if they want to complete the send. match self.state { State::Idle(_) => self.state = State::Closed, @@ -246,12 +246,12 @@ impl PollSender { /// Aborts the current in-progress send, if any. /// - /// Returns `true` if a send was aborted. If the sender was closed prior to calling + /// Returns `true` if a send was aborted. If the sender was closed prior to calling /// `abort_send`, then the sender will remain in the closed state, otherwise the sender will be /// ready to attempt another send. pub fn abort_send(&mut self) -> bool { // We may have been closed in the meantime, after a call to `poll_reserve` already - // succeeded. We'll check if `self.sender` is `None` to see if we should transition to the + // succeeded. We'll check if `self.sender` is `None` to see if we should transition to the // closed state when we actually abort a send, rather than resetting ourselves back to idle. let (result, next_state) = match self.take_state() { @@ -268,7 +268,7 @@ impl PollSender { }; (true, state) } - // We got the permit. If we haven't closed yet, get the sender back. + // We got the permit. If we haven't closed yet, get the sender back. State::ReadyToSend(permit) => { let state = if self.sender.is_some() { State::Idle(permit.release()) diff --git a/tokio-util/src/task/join_map.rs b/tokio-util/src/task/join_map.rs index 13e27bb670b..c17d58f63f5 100644 --- a/tokio-util/src/task/join_map.rs +++ b/tokio-util/src/task/join_map.rs @@ -13,7 +13,7 @@ use tokio::task::{AbortHandle, Id, JoinError, JoinSet, LocalSet}; /// keys. /// /// This type is very similar to the [`JoinSet`] type in `tokio::task`, with the -/// addition of a set of keys associated with each task. These keys allow +/// addition of a set of keys associated with each task. These keys allow /// [cancelling a task][abort] or [multiple tasks][abort_matching] in the /// `JoinMap` based on their keys, or [test whether a task corresponding to a /// given key exists][contains] in the `JoinMap`. @@ -463,7 +463,7 @@ where /// completed. The `value` is the return value of that ask, and `key` is /// the key associated with the task. /// * `Some((key, Err(err))` if one of the tasks in this `JoinMap` has - /// panicked or been aborted. `key` is the key associated with the task + /// panicked or been aborted. `key` is the key associated with the task /// that panicked or was aborted. /// * `None` if the `JoinMap` is empty. /// diff --git a/tokio-util/src/task/spawn_pinned.rs b/tokio-util/src/task/spawn_pinned.rs index 5e4d6cda3ef..cc9d82fadee 100644 --- a/tokio-util/src/task/spawn_pinned.rs +++ b/tokio-util/src/task/spawn_pinned.rs @@ -242,14 +242,14 @@ impl LocalPool { // we assume the parent task was canceled, so cancel this task // as well. if let Err(join_handle) = sender.send(join_handle) { - join_handle.abort() + join_handle.abort(); } }); // Send the callback to the LocalSet task if let Err(e) = worker_spawner.send(spawn_task) { // Propagate the error as a panic in the join handle. - panic!("Failed to send job to worker: {}", e); + panic!("Failed to send job to worker: {e}"); } // Wait for the task's join handle @@ -260,7 +260,7 @@ impl LocalPool { // join handle... We assume something happened to the worker // and the task was not spawned. Propagate the error as a // panic in the join handle. - panic!("Worker failed to send join handle: {}", e); + panic!("Worker failed to send join handle: {e}"); } }; @@ -284,12 +284,12 @@ impl LocalPool { // No one else should have the join handle, so this is // unexpected. Forward this error as a panic in the join // handle. - panic!("spawn_pinned task was canceled: {}", e); + panic!("spawn_pinned task was canceled: {e}"); } else { // Something unknown happened (not a panic or // cancellation). Forward this error as a panic in the // join handle. - panic!("spawn_pinned task failed: {}", e); + panic!("spawn_pinned task failed: {e}"); } } } diff --git a/tokio-util/src/time/delay_queue.rs b/tokio-util/src/time/delay_queue.rs index 55dd311a03e..f04985b02e8 100644 --- a/tokio-util/src/time/delay_queue.rs +++ b/tokio-util/src/time/delay_queue.rs @@ -245,7 +245,7 @@ impl SlabStorage { pub(crate) fn compact(&mut self) { if !self.compact_called { - for (key, _) in self.inner.iter() { + for (key, _) in &self.inner { self.key_map.insert(Key::new(key), KeyInternal::new(key)); } } @@ -667,7 +667,7 @@ impl DelayQueue { // The delay is already expired, store it in the expired queue self.expired.push(key, &mut self.slab); } - Err((_, err)) => panic!("invalid deadline; err={:?}", err), + Err((_, err)) => panic!("invalid deadline; err={err:?}"), } } diff --git a/tokio-util/src/time/wheel/level.rs b/tokio-util/src/time/wheel/level.rs index a69aee918aa..681a88b9c7a 100644 --- a/tokio-util/src/time/wheel/level.rs +++ b/tokio-util/src/time/wheel/level.rs @@ -127,10 +127,7 @@ impl Level { pub(crate) fn next_expiration(&self, now: u64) -> Option { // Use the `occupied` bit field to get the index of the next slot that // needs to be processed. - let slot = match self.next_occupied_slot(now) { - Some(slot) => slot, - None => return None, - }; + let slot = self.next_occupied_slot(now)?; // From the slot index, calculate the `Instant` at which it needs to be // processed. This value *must* be in the future with respect to `now`. diff --git a/tokio-util/src/time/wheel/mod.rs b/tokio-util/src/time/wheel/mod.rs index d81611c92bd..e08659931aa 100644 --- a/tokio-util/src/time/wheel/mod.rs +++ b/tokio-util/src/time/wheel/mod.rs @@ -155,22 +155,19 @@ where } }); - match expiration { - Some(ref expiration) => { - if let Some(item) = self.poll_expiration(expiration, store) { - return Some(item); - } - - self.set_elapsed(expiration.deadline); - } - None => { - // in this case the poll did not indicate an expiration - // _and_ we were not able to find a next expiration in - // the current list of timers. advance to the poll's - // current time and do nothing else. - self.set_elapsed(now); - return None; + if let Some(expiration) = &expiration { + if let Some(item) = self.poll_expiration(expiration, store) { + return Some(item); } + + self.set_elapsed(expiration.deadline); + } else { + // in this case the poll did not indicate an expiration + // _and_ we were not able to find a next expiration in + // the current list of timers. Advance to the poll's + // current time and do nothing else. + self.set_elapsed(now); + return None; } } } @@ -206,8 +203,8 @@ where res } - /// iteratively find entries that are between the wheel's current - /// time and the expiration time. for each in that population either + /// Iteratively find entries that are between the wheel's current + /// time and the expiration time. For each in that population either /// return it for notification (in the case of the last level) or tier /// it down to the next level (in all other cases). pub(crate) fn poll_expiration( @@ -280,13 +277,7 @@ mod test { #[test] fn test_level_for() { for pos in 0..64 { - assert_eq!( - 0, - level_for(0, pos), - "level_for({}) -- binary = {:b}", - pos, - pos - ); + assert_eq!(0, level_for(0, pos), "level_for({pos}) -- binary = {pos:b}"); } for level in 1..5 { @@ -295,9 +286,7 @@ mod test { assert_eq!( level, level_for(0, a as u64), - "level_for({}) -- binary = {:b}", - a, - a + "level_for({a}) -- binary = {a:b}" ); if pos > level { @@ -305,9 +294,7 @@ mod test { assert_eq!( level, level_for(0, a as u64), - "level_for({}) -- binary = {:b}", - a, - a + "level_for({a}) -- binary = {a:b}" ); } @@ -316,9 +303,7 @@ mod test { assert_eq!( level, level_for(0, a as u64), - "level_for({}) -- binary = {:b}", - a, - a + "level_for({a}) -- binary = {a:b}" ); } } diff --git a/tokio-util/tests/codecs.rs b/tokio-util/tests/codecs.rs index f9a780140a2..1cfd9208e86 100644 --- a/tokio-util/tests/codecs.rs +++ b/tokio-util/tests/codecs.rs @@ -75,32 +75,17 @@ fn lines_decoder_max_length() { assert!(codec.decode(buf).is_err()); let line = codec.decode(buf).unwrap().unwrap(); - assert!( - line.len() <= MAX_LENGTH, - "{:?}.len() <= {:?}", - line, - MAX_LENGTH - ); + assert!(line.len() <= MAX_LENGTH, "{line:?}.len() <= {MAX_LENGTH:?}"); assert_eq!("line 2", line); assert!(codec.decode(buf).is_err()); let line = codec.decode(buf).unwrap().unwrap(); - assert!( - line.len() <= MAX_LENGTH, - "{:?}.len() <= {:?}", - line, - MAX_LENGTH - ); + assert!(line.len() <= MAX_LENGTH, "{line:?}.len() <= {MAX_LENGTH:?}"); assert_eq!("line 4", line); let line = codec.decode(buf).unwrap().unwrap(); - assert!( - line.len() <= MAX_LENGTH, - "{:?}.len() <= {:?}", - line, - MAX_LENGTH - ); + assert!(line.len() <= MAX_LENGTH, "{line:?}.len() <= {MAX_LENGTH:?}"); assert_eq!("", line); assert_eq!(None, codec.decode(buf).unwrap()); @@ -109,12 +94,7 @@ fn lines_decoder_max_length() { assert_eq!(None, codec.decode(buf).unwrap()); let line = codec.decode_eof(buf).unwrap().unwrap(); - assert!( - line.len() <= MAX_LENGTH, - "{:?}.len() <= {:?}", - line, - MAX_LENGTH - ); + assert!(line.len() <= MAX_LENGTH, "{line:?}.len() <= {MAX_LENGTH:?}"); assert_eq!("\rk", line); assert_eq!(None, codec.decode(buf).unwrap()); @@ -273,18 +253,14 @@ fn any_delimiters_decoder_max_length() { let chunk = codec.decode(buf).unwrap().unwrap(); assert!( chunk.len() <= MAX_LENGTH, - "{:?}.len() <= {:?}", - chunk, - MAX_LENGTH + "{chunk:?}.len() <= {MAX_LENGTH:?}" ); assert_eq!("chunk 2", chunk); let chunk = codec.decode(buf).unwrap().unwrap(); assert!( chunk.len() <= MAX_LENGTH, - "{:?}.len() <= {:?}", - chunk, - MAX_LENGTH + "{chunk:?}.len() <= {MAX_LENGTH:?}" ); assert_eq!("chunk 3", chunk); @@ -292,36 +268,28 @@ fn any_delimiters_decoder_max_length() { let chunk = codec.decode(buf).unwrap().unwrap(); assert!( chunk.len() <= MAX_LENGTH, - "{:?}.len() <= {:?}", - chunk, - MAX_LENGTH + "{chunk:?}.len() <= {MAX_LENGTH:?}" ); assert_eq!("", chunk); let chunk = codec.decode(buf).unwrap().unwrap(); assert!( chunk.len() <= MAX_LENGTH, - "{:?}.len() <= {:?}", - chunk, - MAX_LENGTH + "{chunk:?}.len() <= {MAX_LENGTH:?}" ); assert_eq!("chunk 4", chunk); let chunk = codec.decode(buf).unwrap().unwrap(); assert!( chunk.len() <= MAX_LENGTH, - "{:?}.len() <= {:?}", - chunk, - MAX_LENGTH + "{chunk:?}.len() <= {MAX_LENGTH:?}" ); assert_eq!("", chunk); let chunk = codec.decode(buf).unwrap().unwrap(); assert!( chunk.len() <= MAX_LENGTH, - "{:?}.len() <= {:?}", - chunk, - MAX_LENGTH + "{chunk:?}.len() <= {MAX_LENGTH:?}" ); assert_eq!("", chunk); @@ -333,9 +301,7 @@ fn any_delimiters_decoder_max_length() { let chunk = codec.decode_eof(buf).unwrap().unwrap(); assert!( chunk.len() <= MAX_LENGTH, - "{:?}.len() <= {:?}", - chunk, - MAX_LENGTH + "{chunk:?}.len() <= {MAX_LENGTH:?}" ); assert_eq!("k", chunk); diff --git a/tokio-util/tests/framed_read.rs b/tokio-util/tests/framed_read.rs index 2a9e27e22f5..bce2613f656 100644 --- a/tokio-util/tests/framed_read.rs +++ b/tokio-util/tests/framed_read.rs @@ -170,7 +170,7 @@ fn read_err() { .unwrap() .unwrap_err() .kind() - ) + ); }); } @@ -190,7 +190,7 @@ fn read_partial_then_err() { .unwrap() .unwrap_err() .kind() - ) + ); }); } @@ -212,7 +212,7 @@ fn read_partial_would_block_then_err() { .unwrap() .unwrap_err() .kind() - ) + ); }); } diff --git a/tokio-util/tests/framed_stream.rs b/tokio-util/tests/framed_stream.rs index 76d8af7b7d6..a8e277a58a6 100644 --- a/tokio-util/tests/framed_stream.rs +++ b/tokio-util/tests/framed_stream.rs @@ -34,5 +34,5 @@ async fn return_none_after_error() { assert!(assert_ready!(pin!(io).poll_next(cx)).unwrap().is_err()); assert!(assert_ready!(pin!(io).poll_next(cx)).is_none()); assert_read!(pin!(io).poll_next(cx), b"more data".to_vec()); - }) + }); } diff --git a/tokio-util/tests/framed_write.rs b/tokio-util/tests/framed_write.rs index 39091c0b1b5..3aa1b073386 100644 --- a/tokio-util/tests/framed_write.rs +++ b/tokio-util/tests/framed_write.rs @@ -162,7 +162,7 @@ fn write_hits_backpressure() { // Ensure the mock is empty assert_eq!(0, framed.get_ref().calls.len()); - }) + }); } // // ===== Mock ====== @@ -180,7 +180,7 @@ impl Write for Mock { Ok(data.len()) } Some(Err(e)) => Err(e), - None => panic!("unexpected write; {:?}", src), + None => panic!("unexpected write; {src:?}"), } } diff --git a/tokio-util/tests/io_inspect.rs b/tokio-util/tests/io_inspect.rs index e6319afcf1b..523152de81e 100644 --- a/tokio-util/tests/io_inspect.rs +++ b/tokio-util/tests/io_inspect.rs @@ -22,7 +22,7 @@ impl AsyncRead for SmallReader { buf: &mut ReadBuf<'_>, ) -> Poll> { if let Some(byte) = self.contents.pop() { - buf.put_slice(&[byte]) + buf.put_slice(&[byte]); } Poll::Ready(Ok(())) } @@ -165,14 +165,14 @@ async fn write_tee_vectored() { }; let original = b"A very long string split up"; let bufs: Vec> = original - .split(|b| b.is_ascii_whitespace()) + .split(u8::is_ascii_whitespace) .map(Vec::from) .collect(); assert!(bufs.len() > 1); let expected: Vec = { let mut out = Vec::new(); for item in &bufs { - out.extend_from_slice(item) + out.extend_from_slice(item); } out }; @@ -180,7 +180,7 @@ async fn write_tee_vectored() { let mut bufcount = 0; let tee = InspectWriter::new(&mut writeout, |bytes| { bufcount += 1; - altout.extend(bytes) + altout.extend(bytes); }); assert!(tee.is_write_vectored()); diff --git a/tokio-util/tests/io_reader_stream.rs b/tokio-util/tests/io_reader_stream.rs index e30cd85164c..01fa164d0a3 100644 --- a/tokio-util/tests/io_reader_stream.rs +++ b/tokio-util/tests/io_reader_stream.rs @@ -42,20 +42,17 @@ async fn correct_behavior_on_errors() { let mut had_error = false; loop { let item = stream.next().await.unwrap(); - println!("{:?}", item); - match item { - Ok(bytes) => { - let bytes = &*bytes; - for byte in bytes { - assert_eq!(*byte, 0); - zeros_received += 1; - } - } - Err(_) => { - assert!(!had_error); - had_error = true; - break; + println!("{item:?}"); + if let Ok(bytes) = item { + let bytes = &*bytes; + for byte in bytes { + assert_eq!(*byte, 0); + zeros_received += 1; } + } else { + assert!(!had_error); + had_error = true; + break; } } diff --git a/tokio-util/tests/length_delimited.rs b/tokio-util/tests/length_delimited.rs index 091a5b449e4..14d4ab52137 100644 --- a/tokio-util/tests/length_delimited.rs +++ b/tokio-util/tests/length_delimited.rs @@ -789,7 +789,7 @@ impl AsyncWrite for Mock { match self.calls.pop_front() { Some(Poll::Ready(Ok(Op::Data(data)))) => { let len = data.len(); - assert!(src.len() >= len, "expect={:?}; actual={:?}", data, src); + assert!(src.len() >= len, "expect={data:?}; actual={src:?}"); assert_eq!(&data[..], &src[..len]); Poll::Ready(Ok(len)) } diff --git a/tokio-util/tests/mpsc.rs b/tokio-util/tests/mpsc.rs index cf4dcd55f63..5fb9e6b4e2b 100644 --- a/tokio-util/tests/mpsc.rs +++ b/tokio-util/tests/mpsc.rs @@ -37,7 +37,7 @@ async fn simple_ref() { let (send, mut recv) = channel(3); let mut send = PollSender::new(send); - for vi in v.iter() { + for vi in &v { let mut reserve = spawn(poll_fn(|cx| send.poll_reserve(cx))); assert_ready_ok!(reserve.poll()); send.send_item(vi).unwrap(); diff --git a/tokio-util/tests/sync_cancellation_token.rs b/tokio-util/tests/sync_cancellation_token.rs index db33114a2e3..82cb28660ae 100644 --- a/tokio-util/tests/sync_cancellation_token.rs +++ b/tokio-util/tests/sync_cancellation_token.rs @@ -234,7 +234,7 @@ fn cancel_child_token_without_parent() { #[test] fn create_child_token_after_parent_was_cancelled() { - for drop_child_first in [true, false].iter().cloned() { + for drop_child_first in [true, false].iter().copied() { let (waker, wake_counter) = new_count_waker(); let token = CancellationToken::new(); token.cancel(); diff --git a/tokio-util/tests/time_delay_queue.rs b/tokio-util/tests/time_delay_queue.rs index 9915b11b58a..ff415713a04 100644 --- a/tokio-util/tests/time_delay_queue.rs +++ b/tokio-util/tests/time_delay_queue.rs @@ -35,7 +35,7 @@ async fn single_immediate_delay() { assert_ready_some!(poll!(queue)); let entry = assert_ready!(poll!(queue)); - assert!(entry.is_none()) + assert!(entry.is_none()); } #[tokio::test] @@ -110,7 +110,7 @@ async fn multi_delay_at_start() { let start = Instant::now(); for elapsed in 0..1200 { - println!("elapsed: {:?}", elapsed); + println!("elapsed: {elapsed:?}"); let elapsed = elapsed + 1; tokio::time::sleep_until(start + ms(elapsed)).await; @@ -198,7 +198,7 @@ async fn reset_entry() { assert_eq!(*entry.get_ref(), "foo"); let entry = assert_ready!(poll!(queue)); - assert!(entry.is_none()) + assert!(entry.is_none()); } // Reproduces tokio-rs/tokio#849. @@ -327,7 +327,7 @@ async fn remove_at_timer_wheel_threshold() { let entry = queue.remove(&key1).into_inner(); assert_eq!(entry, "foo"); } - other => panic!("other: {:?}", other), + other => panic!("other: {other:?}"), } } @@ -391,7 +391,7 @@ async fn multi_reset() { assert_eq!(*entry.get_ref(), "one"); let entry = assert_ready!(poll!(queue)); - assert!(entry.is_none()) + assert!(entry.is_none()); } #[tokio::test] @@ -539,8 +539,8 @@ async fn reset_later_after_slot_starts() { // At this point the queue hasn't been polled, so `elapsed` on the wheel // for the queue is still at 0 and hence the 1ms resolution slots cover - // [0-64). Resetting the time on the entry to 120 causes it to get put in - // the [64-128) slot. As the queue knows that the first entry is within + // [0-64). Resetting the time on the entry to 120 causes it to get put in + // the [64-128) slot. As the queue knows that the first entry is within // that slot, but doesn't know when, it must wake immediately to advance // the wheel. queue.reset_at(&foo, now + ms(120)); @@ -601,8 +601,8 @@ async fn reset_earlier_after_slot_starts() { // At this point the queue hasn't been polled, so `elapsed` on the wheel // for the queue is still at 0 and hence the 1ms resolution slots cover - // [0-64). Resetting the time on the entry to 120 causes it to get put in - // the [64-128) slot. As the queue knows that the first entry is within + // [0-64). Resetting the time on the entry to 120 causes it to get put in + // the [64-128) slot. As the queue knows that the first entry is within // that slot, but doesn't know when, it must wake immediately to advance // the wheel. queue.reset_at(&foo, now + ms(120)); diff --git a/tokio/README.md b/tokio/README.md index fb567dd6a23..1d936f9cea7 100644 --- a/tokio/README.md +++ b/tokio/README.md @@ -196,7 +196,7 @@ release. The MSRV history for past minor releases can be found below: * 1.27 to 1.29 - Rust 1.56 * 1.17 to 1.26 - Rust 1.49 * 1.15 to 1.16 - Rust 1.46 - * 1.0 to 1.14 - Rust 1.45 + * 1.0 to 1.14 - Rust 1.45 Note that although we try to avoid the situation where a dependency transitively increases the MSRV of Tokio, we do not guarantee that this does not happen. diff --git a/tokio/src/fs/create_dir_all.rs b/tokio/src/fs/create_dir_all.rs index 0a85b6a0c7f..1256469b500 100644 --- a/tokio/src/fs/create_dir_all.rs +++ b/tokio/src/fs/create_dir_all.rs @@ -22,9 +22,9 @@ use std::path::Path; /// limited to just these cases: /// /// * If any directory in the path specified by `path` does not already exist -/// and it could not be created otherwise. The specific error conditions for -/// when a directory is being created (after it is determined to not exist) are -/// outlined by [`fs::create_dir`]. +/// and it could not be created otherwise. The specific error conditions for +/// when a directory is being created (after it is determined to not exist) are +/// outlined by [`fs::create_dir`]. /// /// Notable exception is made for situations where any of the directories /// specified in the `path` could not be created as it was being created concurrently. diff --git a/tokio/src/fs/metadata.rs b/tokio/src/fs/metadata.rs index 21ebe4f786b..68ea6288aa2 100644 --- a/tokio/src/fs/metadata.rs +++ b/tokio/src/fs/metadata.rs @@ -15,7 +15,7 @@ use std::path::Path; /// # Platform-specific behavior /// /// This function currently corresponds to the `stat` function on Unix and the -/// `GetFileAttributesEx` function on Windows. Note that, this [may change in +/// `GetFileAttributesEx` function on Windows. Note that, this [may change in /// the future][changes]. /// /// [changes]: https://doc.rust-lang.org/std/io/index.html#platform-specific-behavior diff --git a/tokio/src/fs/mocks.rs b/tokio/src/fs/mocks.rs index a2ce1cd6ca3..b8584cc09e1 100644 --- a/tokio/src/fs/mocks.rs +++ b/tokio/src/fs/mocks.rs @@ -1,4 +1,5 @@ -//! Mock version of std::fs::File; +//! Mock version of [`std::fs::File`]. + use mockall::mock; use crate::sync::oneshot; @@ -19,7 +20,7 @@ mock! { pub fn create(pb: PathBuf) -> io::Result; // These inner_ methods exist because std::fs::File has two // implementations for each of these methods: one on "&mut self" and - // one on "&&self". Defining both of those in terms of an inner_ method + // one on "&&self". Defining both of those in terms of an inner_ method // allows us to specify the expectation the same way, regardless of // which method is used. pub fn inner_flush(&self) -> io::Result<()>; @@ -129,7 +130,7 @@ impl Future for JoinHandle { match Pin::new(&mut self.rx).poll(cx) { Poll::Ready(Ok(v)) => Poll::Ready(Ok(v)), - Poll::Ready(Err(e)) => panic!("error = {:?}", e), + Poll::Ready(Err(e)) => panic!("error = {e:?}"), Poll::Pending => Poll::Pending, } } diff --git a/tokio/src/fs/open_options.rs b/tokio/src/fs/open_options.rs index 12615393867..dbf0bec651a 100644 --- a/tokio/src/fs/open_options.rs +++ b/tokio/src/fs/open_options.rs @@ -165,7 +165,7 @@ impl OpenOptions { /// Sets the option for the append mode. /// /// This option, when true, means that writes will append to a file instead - /// of overwriting previous contents. Note that setting + /// of overwriting previous contents. Note that setting /// `.write(true).append(true)` has the same effect as setting only /// `.append(true)`. /// @@ -292,7 +292,7 @@ impl OpenOptions { /// Sets the option to always create a new file. /// - /// This option indicates whether a new file will be created. No file is + /// This option indicates whether a new file will be created. No file is /// allowed to exist at the target location, also no (dangling) symlink. /// /// This option is useful because it is atomic. Otherwise between checking diff --git a/tokio/src/fs/read_dir.rs b/tokio/src/fs/read_dir.rs index 20d74967cd4..73dd90b9bea 100644 --- a/tokio/src/fs/read_dir.rs +++ b/tokio/src/fs/read_dir.rs @@ -127,9 +127,8 @@ impl ReadDir { fn next_chunk(buf: &mut VecDeque>, std: &mut std::fs::ReadDir) -> bool { for _ in 0..CHUNK_SIZE { - let ret = match std.next() { - Some(ret) => ret, - None => return false, + let Some(ret) = std.next() else { + return false; }; let success = ret.is_ok(); diff --git a/tokio/src/io/async_fd.rs b/tokio/src/io/async_fd.rs index 96d0518a6e5..848a3c09a9b 100644 --- a/tokio/src/io/async_fd.rs +++ b/tokio/src/io/async_fd.rs @@ -67,7 +67,7 @@ use std::{task::Context, task::Poll}; /// # Examples /// /// This example shows how to turn [`std::net::TcpStream`] asynchronous using -/// `AsyncFd`. It implements the read/write operations both as an `async fn` +/// `AsyncFd`. It implements the read/write operations both as an `async fn` /// and using the IO traits [`AsyncRead`] and [`AsyncWrite`]. /// /// ```no_run diff --git a/tokio/src/io/async_write.rs b/tokio/src/io/async_write.rs index 7ec1a302efa..c2cd15e1dbb 100644 --- a/tokio/src/io/async_write.rs +++ b/tokio/src/io/async_write.rs @@ -28,7 +28,7 @@ use std::task::{Context, Poll}; /// This trait importantly means that the [`write`][stdwrite] method only works in /// the context of a future's task. The object may panic if used outside of a task. /// -/// Note that this trait also represents that the [`Write::flush`][stdflush] method +/// Note that this trait also represents that the [`Write::flush`][stdflush] method /// works very similarly to the `write` method, notably that `Ok(())` means that the /// writer has successfully been flushed, a "would block" error means that the /// current task is ready to receive a notification when flushing can make more diff --git a/tokio/src/io/bsd/poll_aio.rs b/tokio/src/io/bsd/poll_aio.rs index 708ca7484e7..697fd66fbdd 100644 --- a/tokio/src/io/bsd/poll_aio.rs +++ b/tokio/src/io/bsd/poll_aio.rs @@ -70,7 +70,7 @@ impl Source for MioSource { /// /// If [`Aio::poll_ready`] returns ready, but the consumer determines that the /// Source is not completely ready and must return to the Pending state, -/// [`Aio::clear_ready`] may be used. This can be useful with +/// [`Aio::clear_ready`] may be used. This can be useful with /// [`lio_listio`], which may generate a kevent when only a portion of the /// operations have completed. /// @@ -82,10 +82,10 @@ impl Source for MioSource { /// [`lio_listio`]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/lio_listio.html // Note: Unlike every other kqueue event source, POSIX AIO registers events not // via kevent(2) but when the aiocb is submitted to the kernel via aio_read, -// aio_write, etc. It needs the kqueue's file descriptor to do that. So +// aio_write, etc. It needs the kqueue's file descriptor to do that. So // AsyncFd can't be used for POSIX AIO. // -// Note that Aio doesn't implement Drop. There's no need. Unlike other +// Note that Aio doesn't implement Drop. There's no need. Unlike other // kqueue sources, simply dropping the object effectively deregisters it. pub struct Aio { io: MioSource, @@ -97,7 +97,7 @@ pub struct Aio { impl Aio { /// Creates a new `Aio` suitable for use with POSIX AIO functions. /// - /// It will be associated with the default reactor. The runtime is usually + /// It will be associated with the default reactor. The runtime is usually /// set implicitly when this function is called from a future driven by a /// Tokio runtime, otherwise runtime can be set explicitly with /// [`Runtime::enter`](crate::runtime::Runtime::enter) function. @@ -107,7 +107,7 @@ impl Aio { /// Creates a new `Aio` suitable for use with [`lio_listio`]. /// - /// It will be associated with the default reactor. The runtime is usually + /// It will be associated with the default reactor. The runtime is usually /// set implicitly when this function is called from a future driven by a /// Tokio runtime, otherwise runtime can be set explicitly with /// [`Runtime::enter`](crate::runtime::Runtime::enter) function. @@ -124,20 +124,20 @@ impl Aio { Ok(Self { io, registration }) } - /// Indicates to Tokio that the source is no longer ready. The internal + /// Indicates to Tokio that the source is no longer ready. The internal /// readiness flag will be cleared, and tokio will wait for the next /// edge-triggered readiness notification from the OS. /// /// It is critical that this method not be called unless your code - /// _actually observes_ that the source is _not_ ready. The OS must + /// _actually observes_ that the source is _not_ ready. The OS must /// deliver a subsequent notification, or this source will block - /// forever. It is equally critical that you `do` call this method if you + /// forever. It is equally critical that you `do` call this method if you /// resubmit the same structure to the kernel and poll it again. /// /// This method is not very useful with AIO readiness, since each `aiocb` - /// structure is typically only used once. It's main use with + /// structure is typically only used once. It's main use with /// [`lio_listio`], which will sometimes send notification when only a - /// portion of its elements are complete. In that case, the caller must + /// portion of its elements are complete. In that case, the caller must /// call `clear_ready` before resubmitting it. /// /// [`lio_listio`]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/lio_listio.html @@ -150,14 +150,14 @@ impl Aio { self.io.0 } - /// Polls for readiness. Either AIO or LIO counts. + /// Polls for readiness. Either AIO or LIO counts. /// /// This method returns: /// * `Poll::Pending` if the underlying operation is not complete, whether - /// or not it completed successfully. This will be true if the OS is + /// or not it completed successfully. This will be true if the OS is /// still processing it, or if it has not yet been submitted to the OS. /// * `Poll::Ready(Ok(_))` if the underlying operation is complete. - /// * `Poll::Ready(Err(_))` if the reactor has been shutdown. This does + /// * `Poll::Ready(Err(_))` if the reactor has been shutdown. This does /// _not_ indicate that the underlying operation encountered an error. /// /// When the method returns `Poll::Pending`, the `Waker` in the provided `Context` diff --git a/tokio/src/io/join.rs b/tokio/src/io/join.rs index 6e41f89e867..df4ae4a63ce 100644 --- a/tokio/src/io/join.rs +++ b/tokio/src/io/join.rs @@ -125,6 +125,6 @@ where } fn consume(self: Pin<&mut Self>, amt: usize) { - self.project().reader.consume(amt) + self.project().reader.consume(amt); } } diff --git a/tokio/src/io/mod.rs b/tokio/src/io/mod.rs index b35a20dd35b..2fbc0aa57b3 100644 --- a/tokio/src/io/mod.rs +++ b/tokio/src/io/mod.rs @@ -154,7 +154,7 @@ //! These APIs are very similar to the ones provided by `std`, but they also //! implement [`AsyncRead`] and [`AsyncWrite`]. //! -//! Note that the standard input / output APIs **must** be used from the +//! Note that the standard input / output APIs **must** be used from the //! context of the Tokio runtime, as they require Tokio-specific features to //! function. Calling these functions outside of a Tokio runtime will panic. //! diff --git a/tokio/src/io/poll_evented.rs b/tokio/src/io/poll_evented.rs index 73cb8e5809e..16c9b618a26 100644 --- a/tokio/src/io/poll_evented.rs +++ b/tokio/src/io/poll_evented.rs @@ -244,7 +244,7 @@ feature! { match self.io.as_ref().unwrap().write(buf) { Ok(n) => { // if we write only part of our buffer, this is sufficient on unix to show - // that the socket buffer is full. Unfortunately this assumption + // that the socket buffer is full. Unfortunately this assumption // fails for level-triggered selectors (like on Windows or poll even for // UNIX): https://github.com/tokio-rs/tokio/issues/5866 if n > 0 && (!cfg!(windows) && !cfg!(mio_unsupported_force_poll_poll) && n < buf.len()) { diff --git a/tokio/src/io/stdio_common.rs b/tokio/src/io/stdio_common.rs index 4adbfe23606..c2faf378fd1 100644 --- a/tokio/src/io/stdio_common.rs +++ b/tokio/src/io/stdio_common.rs @@ -56,7 +56,7 @@ where // Now there are two possibilities. // If caller gave is binary buffer, we **should not** shrink it // anymore, because excessive shrinking hits performance. - // If caller gave as binary buffer, we **must** additionally + // If caller gave as binary buffer, we **must** additionally // shrink it to strip incomplete char at the end of buffer. // that's why check we will perform now is allowed to have // false-positive. diff --git a/tokio/src/io/util/chain.rs b/tokio/src/io/util/chain.rs index f96f42f4a99..056d67690ea 100644 --- a/tokio/src/io/util/chain.rs +++ b/tokio/src/io/util/chain.rs @@ -126,9 +126,9 @@ where fn consume(self: Pin<&mut Self>, amt: usize) { let me = self.project(); if !*me.done_first { - me.first.consume(amt) + me.first.consume(amt); } else { - me.second.consume(amt) + me.second.consume(amt); } } } diff --git a/tokio/src/io/util/lines.rs b/tokio/src/io/util/lines.rs index 717f633f950..644182d66bc 100644 --- a/tokio/src/io/util/lines.rs +++ b/tokio/src/io/util/lines.rs @@ -106,7 +106,7 @@ where /// /// When the method returns `Poll::Pending`, the `Waker` in the provided /// `Context` is scheduled to receive a wakeup when more bytes become - /// available on the underlying IO resource. Note that on multiple calls to + /// available on the underlying IO resource. Note that on multiple calls to /// `poll_next_line`, only the `Waker` from the `Context` passed to the most /// recent call is scheduled to receive a wakeup. pub fn poll_next_line( diff --git a/tokio/src/loom/std/mod.rs b/tokio/src/loom/std/mod.rs index 985d8d73aeb..74b1324fd0e 100644 --- a/tokio/src/loom/std/mod.rs +++ b/tokio/src/loom/std/mod.rs @@ -91,22 +91,16 @@ pub(crate) mod sys { match std::env::var(ENV_WORKER_THREADS) { Ok(s) => { let n = s.parse().unwrap_or_else(|e| { - panic!( - "\"{}\" must be usize, error: {}, value: {}", - ENV_WORKER_THREADS, e, s - ) + panic!("\"{ENV_WORKER_THREADS}\" must be usize, error: {e}, value: {s}"); }); - assert!(n > 0, "\"{}\" cannot be set to 0", ENV_WORKER_THREADS); + assert!(n > 0, "\"{ENV_WORKER_THREADS}\" cannot be set to 0"); n } Err(std::env::VarError::NotPresent) => { std::thread::available_parallelism().map_or(1, NonZeroUsize::get) } Err(std::env::VarError::NotUnicode(e)) => { - panic!( - "\"{}\" must be valid unicode, error: {:?}", - ENV_WORKER_THREADS, e - ) + panic!("\"{ENV_WORKER_THREADS}\" must be valid unicode, error: {e:?}"); } } } diff --git a/tokio/src/macros/select.rs b/tokio/src/macros/select.rs index d1e59d34736..a4621664b8e 100644 --- a/tokio/src/macros/select.rs +++ b/tokio/src/macros/select.rs @@ -92,7 +92,7 @@ macro_rules! doc { /// When using `select!` in a loop to receive messages from multiple sources, /// you should make sure that the receive call is cancellation safe to avoid /// losing messages. This section goes through various common methods and - /// describes whether they are cancel safe. The lists in this section are not + /// describes whether they are cancel safe. The lists in this section are not /// exhaustive. /// /// The following methods are cancellation safe: diff --git a/tokio/src/net/mod.rs b/tokio/src/net/mod.rs index d5562ac5d47..1a19a47b277 100644 --- a/tokio/src/net/mod.rs +++ b/tokio/src/net/mod.rs @@ -10,9 +10,9 @@ //! * [`TcpListener`] and [`TcpStream`] provide functionality for communication over TCP //! * [`UdpSocket`] provides functionality for communication over UDP //! * [`UnixListener`] and [`UnixStream`] provide functionality for communication over a -//! Unix Domain Stream Socket **(available on Unix only)** +//! Unix Domain Stream Socket **(available on Unix only)** //! * [`UnixDatagram`] provides functionality for communication -//! over Unix Domain Datagram Socket **(available on Unix only)** +//! over Unix Domain Datagram Socket **(available on Unix only)** //! * [`tokio::net::unix::pipe`] for FIFO pipes **(available on Unix only)** //! * [`tokio::net::windows::named_pipe`] for Named Pipes **(available on Windows only)** //! diff --git a/tokio/src/net/tcp/listener.rs b/tokio/src/net/tcp/listener.rs index 3f6592abe19..65db636824e 100644 --- a/tokio/src/net/tcp/listener.rs +++ b/tokio/src/net/tcp/listener.rs @@ -171,7 +171,7 @@ impl TcpListener { /// Polls to accept a new incoming connection to this listener. /// /// If there is no connection to accept, `Poll::Pending` is returned and the - /// current task will be notified by a waker. Note that on multiple calls + /// current task will be notified by a waker. Note that on multiple calls /// to `poll_accept`, only the `Waker` from the `Context` passed to the most /// recent call is scheduled to receive a wakeup. pub fn poll_accept(&self, cx: &mut Context<'_>) -> Poll> { @@ -243,7 +243,7 @@ impl TcpListener { /// Turns a [`tokio::net::TcpListener`] into a [`std::net::TcpListener`]. /// /// The returned [`std::net::TcpListener`] will have nonblocking mode set as - /// `true`. Use [`set_nonblocking`] to change the blocking mode if needed. + /// `true`. Use [`set_nonblocking`] to change the blocking mode if needed. /// /// # Examples /// diff --git a/tokio/src/net/tcp/split_owned.rs b/tokio/src/net/tcp/split_owned.rs index 6771d6497a2..d48c74423f3 100644 --- a/tokio/src/net/tcp/split_owned.rs +++ b/tokio/src/net/tcp/split_owned.rs @@ -1,7 +1,7 @@ //! `TcpStream` owned split support. //! //! A `TcpStream` can be split into an `OwnedReadHalf` and a `OwnedWriteHalf` -//! with the `TcpStream::into_split` method. `OwnedReadHalf` implements +//! with the `TcpStream::into_split` method. `OwnedReadHalf` implements //! `AsyncRead` while `OwnedWriteHalf` implements `AsyncWrite`. //! //! Compared to the generic split of `AsyncRead + AsyncWrite`, this specialized @@ -39,7 +39,7 @@ pub struct OwnedReadHalf { /// Owned write half of a [`TcpStream`], created by [`into_split`]. /// /// Note that in the [`AsyncWrite`] implementation of this type, [`poll_shutdown`] will -/// shut down the TCP stream in the write direction. Dropping the write half +/// shut down the TCP stream in the write direction. Dropping the write half /// will also shut down the write half of the TCP stream. /// /// Writing to an `OwnedWriteHalf` is usually done using the convenience methods found diff --git a/tokio/src/net/tcp/stream.rs b/tokio/src/net/tcp/stream.rs index e20473e5cc3..25d9a2a71b7 100644 --- a/tokio/src/net/tcp/stream.rs +++ b/tokio/src/net/tcp/stream.rs @@ -76,7 +76,7 @@ impl TcpStream { /// Opens a TCP connection to a remote host. /// /// `addr` is an address of the remote host. Anything which implements the - /// [`ToSocketAddrs`] trait can be supplied as the address. If `addr` + /// [`ToSocketAddrs`] trait can be supplied as the address. If `addr` /// yields multiple addresses, connect will be attempted with each of the /// addresses until a connection is successful. If none of the addresses /// result in a successful connection, the error returned from the last diff --git a/tokio/src/net/udp.rs b/tokio/src/net/udp.rs index 03a66585047..6932d1ff358 100644 --- a/tokio/src/net/udp.rs +++ b/tokio/src/net/udp.rs @@ -226,7 +226,7 @@ impl UdpSocket { /// Turns a [`tokio::net::UdpSocket`] into a [`std::net::UdpSocket`]. /// /// The returned [`std::net::UdpSocket`] will have nonblocking mode set as - /// `true`. Use [`set_nonblocking`] to change the blocking mode if needed. + /// `true`. Use [`set_nonblocking`] to change the blocking mode if needed. /// /// # Examples /// diff --git a/tokio/src/net/unix/listener.rs b/tokio/src/net/unix/listener.rs index 5b28dc03f8f..6b6b61d3b7c 100644 --- a/tokio/src/net/unix/listener.rs +++ b/tokio/src/net/unix/listener.rs @@ -198,7 +198,7 @@ impl UnixListener { /// Polls to accept a new incoming connection to this listener. /// /// If there is no connection to accept, `Poll::Pending` is returned and the - /// current task will be notified by a waker. Note that on multiple calls + /// current task will be notified by a waker. Note that on multiple calls /// to `poll_accept`, only the `Waker` from the `Context` passed to the most /// recent call is scheduled to receive a wakeup. pub fn poll_accept(&self, cx: &mut Context<'_>) -> Poll> { diff --git a/tokio/src/net/unix/split_owned.rs b/tokio/src/net/unix/split_owned.rs index d1c6f93ded7..66393fc3e65 100644 --- a/tokio/src/net/unix/split_owned.rs +++ b/tokio/src/net/unix/split_owned.rs @@ -1,7 +1,7 @@ //! `UnixStream` owned split support. //! //! A `UnixStream` can be split into an `OwnedReadHalf` and a `OwnedWriteHalf` -//! with the `UnixStream::into_split` method. `OwnedReadHalf` implements +//! with the `UnixStream::into_split` method. `OwnedReadHalf` implements //! `AsyncRead` while `OwnedWriteHalf` implements `AsyncWrite`. //! //! Compared to the generic split of `AsyncRead + AsyncWrite`, this specialized diff --git a/tokio/src/net/unix/stream.rs b/tokio/src/net/unix/stream.rs index a8b6479f1f8..1f841e0e3e0 100644 --- a/tokio/src/net/unix/stream.rs +++ b/tokio/src/net/unix/stream.rs @@ -827,7 +827,7 @@ impl UnixStream { /// Turns a [`tokio::net::UnixStream`] into a [`std::os::unix::net::UnixStream`]. /// /// The returned [`std::os::unix::net::UnixStream`] will have nonblocking - /// mode set as `true`. Use [`set_nonblocking`] to change the blocking + /// mode set as `true`. Use [`set_nonblocking`] to change the blocking /// mode if needed. /// /// # Examples diff --git a/tokio/src/net/windows/named_pipe.rs b/tokio/src/net/windows/named_pipe.rs index 0b312f896f1..14a837292b2 100644 --- a/tokio/src/net/windows/named_pipe.rs +++ b/tokio/src/net/windows/named_pipe.rs @@ -1782,7 +1782,7 @@ impl ServerOptions { /// The default pipe mode is [`PipeMode::Byte`]. See [`PipeMode`] for /// documentation of what each mode means. /// - /// This corresponds to specifying `PIPE_TYPE_` and `PIPE_READMODE_` in [`dwPipeMode`]. + /// This corresponds to specifying `PIPE_TYPE_` and `PIPE_READMODE_` in [`dwPipeMode`]. /// /// [`dwPipeMode`]: https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-createnamedpipea pub fn pipe_mode(&mut self, pipe_mode: PipeMode) -> &mut Self { diff --git a/tokio/src/process/unix/orphan.rs b/tokio/src/process/unix/orphan.rs index a89555f5876..961f0652d62 100644 --- a/tokio/src/process/unix/orphan.rs +++ b/tokio/src/process/unix/orphan.rs @@ -83,26 +83,23 @@ impl OrphanQueueImpl { // If someone else is holding the lock, they will be responsible for draining // the queue as necessary, so we can safely bail if that happens if let Some(mut sigchild_guard) = self.sigchild.try_lock() { - match &mut *sigchild_guard { - Some(sigchild) => { - if sigchild.try_has_changed().and_then(Result::ok).is_some() { - drain_orphan_queue(self.queue.lock()); - } + if let Some(sigchild) = &mut *sigchild_guard { + if sigchild.try_has_changed().and_then(Result::ok).is_some() { + drain_orphan_queue(self.queue.lock()); } - None => { - let queue = self.queue.lock(); - - // Be lazy and only initialize the SIGCHLD listener if there - // are any orphaned processes in the queue. - if !queue.is_empty() { - // An errors shouldn't really happen here, but if it does it - // means that the signal driver isn't running, in - // which case there isn't anything we can - // register/initialize here, so we can try again later - if let Ok(sigchild) = signal_with_handle(SignalKind::child(), handle) { - *sigchild_guard = Some(sigchild); - drain_orphan_queue(queue); - } + } else { + let queue = self.queue.lock(); + + // Be lazy and only initialize the SIGCHLD listener if there + // are any orphaned processes in the queue. + if !queue.is_empty() { + // An errors shouldn't really happen here, but if it does it + // means that the signal driver isn't running, in + // which case there isn't anything we can + // register/initialize here, so we can try again later + if let Ok(sigchild) = signal_with_handle(SignalKind::child(), handle) { + *sigchild_guard = Some(sigchild); + drain_orphan_queue(queue); } } } diff --git a/tokio/src/process/unix/pidfd_reaper.rs b/tokio/src/process/unix/pidfd_reaper.rs index 3b7d622b34b..f79739a2141 100644 --- a/tokio/src/process/unix/pidfd_reaper.rs +++ b/tokio/src/process/unix/pidfd_reaper.rs @@ -43,7 +43,7 @@ impl Pidfd { let errno = io::Error::last_os_error().raw_os_error().unwrap(); if errno == ENOSYS { - NO_PIDFD_SUPPORT.store(true, Relaxed) + NO_PIDFD_SUPPORT.store(true, Relaxed); } None @@ -120,7 +120,7 @@ where match ready!(this.pidfd.poll_read_ready(cx)) { Err(err) if is_rt_shutdown_err(&err) => { this.pidfd.reregister(Interest::READABLE)?; - ready!(this.pidfd.poll_read_ready(cx))? + ready!(this.pidfd.poll_read_ready(cx))?; } res => res?, } @@ -162,7 +162,7 @@ where if let Some(pidfd) = Pidfd::open(inner.id()) { match PollEvented::new_with_interest(pidfd, Interest::READABLE) { Ok(pidfd) => Ok(Self { - inner: Some(PidfdReaperInner { pidfd, inner }), + inner: Some(PidfdReaperInner { inner, pidfd }), orphan_queue, }), Err(io_error) => Err((Some(io_error), inner)), @@ -237,7 +237,7 @@ mod test { } fn run_test(fut: impl Future) { - create_runtime().block_on(fut) + create_runtime().block_on(fut); } fn is_pidfd_available() -> bool { diff --git a/tokio/src/runtime/blocking/pool.rs b/tokio/src/runtime/blocking/pool.rs index 8bd44278e2a..09745f58c7c 100644 --- a/tokio/src/runtime/blocking/pool.rs +++ b/tokio/src/runtime/blocking/pool.rs @@ -311,7 +311,7 @@ impl Spawner { // Compat: do not panic here, return the join_handle even though it will never resolve Err(SpawnError::ShuttingDown) => join_handle, Err(SpawnError::NoThreads(e)) => { - panic!("OS can't spawn worker thread: {}", e) + panic!("OS can't spawn worker thread: {e}"); } } } diff --git a/tokio/src/runtime/blocking/shutdown.rs b/tokio/src/runtime/blocking/shutdown.rs index fe5abae076d..1b7cc1953a9 100644 --- a/tokio/src/runtime/blocking/shutdown.rs +++ b/tokio/src/runtime/blocking/shutdown.rs @@ -41,18 +41,15 @@ impl Receiver { return false; } - let mut e = match try_enter_blocking_region() { - Some(enter) => enter, - _ => { - if std::thread::panicking() { - // Don't panic in a panic - return false; - } else { - panic!( - "Cannot drop a runtime in a context where blocking is not allowed. \ - This happens when a runtime is dropped from within an asynchronous context." - ); - } + let Some(mut guard) = try_enter_blocking_region() else { + if std::thread::panicking() { + // Don't panic in a panic + return false; + } else { + panic!( + "Cannot drop a runtime in a context where blocking is not allowed. \ + This happens when a runtime is dropped from within an asynchronous context." + ); } }; @@ -62,9 +59,9 @@ impl Receiver { // current thread (usually, shutting down a runtime stored in a // thread-local). if let Some(timeout) = timeout { - e.block_on_timeout(&mut self.rx, timeout).is_ok() + guard.block_on_timeout(&mut self.rx, timeout).is_ok() } else { - let _ = e.block_on(&mut self.rx); + let _ = guard.block_on(&mut self.rx); true } } diff --git a/tokio/src/runtime/builder.rs b/tokio/src/runtime/builder.rs index 16be770985c..1baaea625b1 100644 --- a/tokio/src/runtime/builder.rs +++ b/tokio/src/runtime/builder.rs @@ -686,7 +686,7 @@ impl Builder { /// ``` /// use tokio::runtime::Builder; /// - /// let rt = Builder::new_multi_thread().build().unwrap(); + /// let rt = Builder::new_multi_thread().build().unwrap(); /// /// rt.block_on(async { /// println!("Hello from the Tokio runtime"); diff --git a/tokio/src/runtime/context.rs b/tokio/src/runtime/context.rs index 76918114bc3..2e834974125 100644 --- a/tokio/src/runtime/context.rs +++ b/tokio/src/runtime/context.rs @@ -144,13 +144,12 @@ cfg_rt! { pub(crate) fn thread_id() -> Result { CONTEXT.try_with(|ctx| { - match ctx.thread_id.get() { - Some(id) => id, - None => { - let id = ThreadId::next(); - ctx.thread_id.set(Some(id)); - id - } + if let Some(id) = ctx.thread_id.get() { + id + } else { + let id = ThreadId::next(); + ctx.thread_id.set(Some(id)); + id } }) } diff --git a/tokio/src/runtime/coop.rs b/tokio/src/runtime/coop.rs index f2afa75c9c4..c4fb141ad2a 100644 --- a/tokio/src/runtime/coop.rs +++ b/tokio/src/runtime/coop.rs @@ -250,7 +250,7 @@ mod test { use wasm_bindgen_test::wasm_bindgen_test as test; fn get() -> Budget { - context::budget(|cell| cell.get()).unwrap_or(Budget::unconstrained()) + context::budget(Cell::get).unwrap_or(Budget::unconstrained()) } #[test] diff --git a/tokio/src/runtime/handle.rs b/tokio/src/runtime/handle.rs index 64bc540c664..9dd110f04ad 100644 --- a/tokio/src/runtime/handle.rs +++ b/tokio/src/runtime/handle.rs @@ -82,10 +82,8 @@ impl Handle { /// [`tokio::spawn`]: fn@crate::spawn pub fn enter(&self) -> EnterGuard<'_> { EnterGuard { - _guard: match context::try_set_current(&self.inner) { - Some(guard) => guard, - None => panic!("{}", crate::util::error::THREAD_LOCAL_DESTROYED_ERROR), - }, + _guard: context::try_set_current(&self.inner) + .expect(crate::util::error::THREAD_LOCAL_DESTROYED_ERROR), _handle_lifetime: PhantomData, } } @@ -257,7 +255,7 @@ impl Handle { /// use tokio::runtime::Runtime; /// /// // Create the runtime - /// let rt = Runtime::new().unwrap(); + /// let rt = Runtime::new().unwrap(); /// /// // Get a handle from this runtime /// let handle = rt.handle(); diff --git a/tokio/src/runtime/io/driver.rs b/tokio/src/runtime/io/driver.rs index 0f7b1e57acb..f4976be1438 100644 --- a/tokio/src/runtime/io/driver.rs +++ b/tokio/src/runtime/io/driver.rs @@ -154,7 +154,7 @@ impl Driver { // In case of wasm32_wasi this error happens, when trying to poll without subscriptions // just return from the park, as there would be nothing, which wakes us up. } - Err(e) => panic!("unexpected error when polling the I/O driver: {:?}", e), + Err(e) => panic!("unexpected error when polling the I/O driver: {e:?}"), } // Process all the events that came in, dispatching appropriately @@ -226,7 +226,7 @@ impl Handle { // safety: `scheduled_io` is part of the `registrations` set. unsafe { self.registrations - .remove(&mut self.synced.lock(), &scheduled_io) + .remove(&mut self.synced.lock(), &scheduled_io); }; return Err(e); diff --git a/tokio/src/runtime/metrics/worker.rs b/tokio/src/runtime/metrics/worker.rs index 29804a08798..0bccfcf0c94 100644 --- a/tokio/src/runtime/metrics/worker.rs +++ b/tokio/src/runtime/metrics/worker.rs @@ -15,10 +15,10 @@ use std::thread::ThreadId; #[derive(Debug, Default)] #[repr(align(128))] pub(crate) struct WorkerMetrics { - /// Number of times the worker parked. + /// Number of times the worker parked. pub(crate) park_count: MetricAtomicU64, - /// Number of times the worker parked and unparked. + /// Number of times the worker parked and unparked. pub(crate) park_unpark_count: MetricAtomicU64, /// Number of times the worker woke then parked again without doing work. diff --git a/tokio/src/runtime/mod.rs b/tokio/src/runtime/mod.rs index 38a0285b3be..9b192ce7622 100644 --- a/tokio/src/runtime/mod.rs +++ b/tokio/src/runtime/mod.rs @@ -68,7 +68,7 @@ //! //! fn main() -> Result<(), Box> { //! // Create the runtime -//! let rt = Runtime::new()?; +//! let rt = Runtime::new()?; //! //! // Spawn the root task //! rt.block_on(async { diff --git a/tokio/src/runtime/park.rs b/tokio/src/runtime/park.rs index cdc32dac50a..c260b7512be 100644 --- a/tokio/src/runtime/park.rs +++ b/tokio/src/runtime/park.rs @@ -109,7 +109,7 @@ impl Inner { return; } - Err(actual) => panic!("inconsistent park state; actual = {}", actual), + Err(actual) => panic!("inconsistent park state; actual = {actual}"), } loop { @@ -155,7 +155,7 @@ impl Inner { return; } - Err(actual) => panic!("inconsistent park_timeout state; actual = {}", actual), + Err(actual) => panic!("inconsistent park_timeout state; actual = {actual}"), } // Wait with a timeout, and if we spuriously wake up or otherwise wake up @@ -167,7 +167,7 @@ impl Inner { match self.state.swap(EMPTY, SeqCst) { NOTIFIED => {} // got a notification, hurray! PARKED => {} // no notification, alas - n => panic!("inconsistent park_timeout state: {}", n), + n => panic!("inconsistent park_timeout state: {n}"), } } diff --git a/tokio/src/runtime/runtime.rs b/tokio/src/runtime/runtime.rs index 16f8718ab23..4d14b6b46f7 100644 --- a/tokio/src/runtime/runtime.rs +++ b/tokio/src/runtime/runtime.rs @@ -154,7 +154,7 @@ impl Runtime { /// initialized. /// /// Most applications will not need to call this function directly. Instead, - /// they will use the [`#[tokio::main]` attribute][main]. When a more complex + /// they will use the [`#[tokio::main]` attribute][main]. When a more complex /// configuration is necessary, the [runtime builder] may be used. /// /// See [module level][mod] documentation for more details. @@ -318,7 +318,7 @@ impl Runtime { /// use tokio::runtime::Runtime; /// /// // Create the runtime - /// let rt = Runtime::new().unwrap(); + /// let rt = Runtime::new().unwrap(); /// /// // Execute the future, blocking the current thread until completion /// rt.block_on(async { diff --git a/tokio/src/runtime/scheduler/current_thread/mod.rs b/tokio/src/runtime/scheduler/current_thread/mod.rs index 5c952061e72..53c9eadffb9 100644 --- a/tokio/src/runtime/scheduler/current_thread/mod.rs +++ b/tokio/src/runtime/scheduler/current_thread/mod.rs @@ -690,22 +690,19 @@ impl CoreGuard<'_> { let entry = core.next_task(handle); - let task = match entry { - Some(entry) => entry, - None => { - core.metrics.end_processing_scheduled_tasks(); + let Some(task) = entry else { + core.metrics.end_processing_scheduled_tasks(); - core = if !context.defer.is_empty() { - context.park_yield(core, handle) - } else { - context.park(core, handle) - }; + core = if context.defer.is_empty() { + context.park(core, handle) + } else { + context.park_yield(core, handle) + }; - core.metrics.start_processing_scheduled_tasks(); + core.metrics.start_processing_scheduled_tasks(); - // Try polling the `block_on` future next - continue 'outer; - } + // Try polling the `block_on` future next + continue 'outer; }; let task = context.handle.shared.owned.assert_owner(task); diff --git a/tokio/src/runtime/scheduler/multi_thread/park.rs b/tokio/src/runtime/scheduler/multi_thread/park.rs index aacd9012cc3..b00c648e6d3 100644 --- a/tokio/src/runtime/scheduler/multi_thread/park.rs +++ b/tokio/src/runtime/scheduler/multi_thread/park.rs @@ -151,7 +151,7 @@ impl Inner { return; } - Err(actual) => panic!("inconsistent park state; actual = {}", actual), + Err(actual) => panic!("inconsistent park state; actual = {actual}"), } loop { @@ -188,7 +188,7 @@ impl Inner { return; } - Err(actual) => panic!("inconsistent park state; actual = {}", actual), + Err(actual) => panic!("inconsistent park state; actual = {actual}"), } driver.park(handle); @@ -196,7 +196,7 @@ impl Inner { match self.state.swap(EMPTY, SeqCst) { NOTIFIED => {} // got a notification, hurray! PARKED_DRIVER => {} // no notification, alas - n => panic!("inconsistent park_timeout state: {}", n), + n => panic!("inconsistent park_timeout state: {n}"), } } @@ -211,7 +211,7 @@ impl Inner { NOTIFIED => {} // already unparked PARKED_CONDVAR => self.unpark_condvar(), PARKED_DRIVER => driver.unpark(), - actual => panic!("inconsistent state in unpark; actual = {}", actual), + actual => panic!("inconsistent state in unpark; actual = {actual}"), } } diff --git a/tokio/src/runtime/scheduler/multi_thread/queue.rs b/tokio/src/runtime/scheduler/multi_thread/queue.rs index 99ee31ba15b..8abf3b27dfb 100644 --- a/tokio/src/runtime/scheduler/multi_thread/queue.rs +++ b/tokio/src/runtime/scheduler/multi_thread/queue.rs @@ -264,9 +264,7 @@ impl Local { assert_eq!( tail.wrapping_sub(head) as usize, LOCAL_QUEUE_CAPACITY, - "queue is not full; tail = {}; head = {}", - tail, - head + "queue is not full; tail = {tail}; head = {head}", ); let prev = pack(head, head); @@ -490,8 +488,7 @@ impl Steal { assert!( n <= LOCAL_QUEUE_CAPACITY as UnsignedShort / 2, - "actual = {}", - n + "actual = {n}", ); let (first, _) = unpack(next_packed); diff --git a/tokio/src/runtime/scheduler/multi_thread/worker.rs b/tokio/src/runtime/scheduler/multi_thread/worker.rs index cefa8704bf6..54d1fa9aeba 100644 --- a/tokio/src/runtime/scheduler/multi_thread/worker.rs +++ b/tokio/src/runtime/scheduler/multi_thread/worker.rs @@ -373,7 +373,7 @@ where }, false, ) => { - // We are on an executor, but _not_ on the thread pool. That is + // We are on an executor, but _not_ on the thread pool. That is // _only_ okay if we are in a thread pool runtime's block_on // method: if allow_block_in_place { @@ -402,9 +402,8 @@ where let cx = maybe_cx.expect("no .is_some() == false cases above should lead here"); // Get the worker core. If none is set, then blocking is fine! - let mut core = match cx.core.borrow_mut().take() { - Some(core) => core, - None => return Ok(()), + let Some(mut core) = cx.core.borrow_mut().take() else { + return Ok(()); }; // If we heavily call `spawn_blocking`, there might be no available thread to @@ -484,9 +483,8 @@ fn run(worker: Arc) { // Acquire a core. If this fails, then another thread is running this // worker and there is nothing further to do. - let core = match worker.core.take() { - Some(core) => core, - None => return, + let Some(core) = worker.core.take() else { + return; }; worker.handle.shared.worker_metrics[worker.index].set_thread_id(thread::current().id()); @@ -599,24 +597,18 @@ impl Context { loop { // Check if we still have the core. If not, the core was stolen // by another worker. - let mut core = match self.core.borrow_mut().take() { - Some(core) => core, - None => { - // In this case, we cannot call `reset_lifo_enabled()` - // because the core was stolen. The stealer will handle - // that at the top of `Context::run` - return Err(()); - } + let Some(mut core) = self.core.borrow_mut().take() else { + // In this case, we cannot call `reset_lifo_enabled()` + // because the core was stolen. The stealer will handle + // that at the top of `Context::run` + return Err(()); }; // Check for a task in the LIFO slot - let task = match core.lifo_slot.take() { - Some(task) => task, - None => { - self.reset_lifo_enabled(&mut core); - core.stats.end_poll(); - return Ok(core); - } + let Some(task) = core.lifo_slot.take() else { + self.reset_lifo_enabled(&mut core); + core.stats.end_poll(); + return Ok(core); }; if !coop::has_budget_remaining() { diff --git a/tokio/src/runtime/scheduler/multi_thread_alt/worker.rs b/tokio/src/runtime/scheduler/multi_thread_alt/worker.rs index b55dc317a77..875a32afafb 100644 --- a/tokio/src/runtime/scheduler/multi_thread_alt/worker.rs +++ b/tokio/src/runtime/scheduler/multi_thread_alt/worker.rs @@ -389,7 +389,7 @@ where }, false, ) => { - // We are on an executor, but _not_ on the thread pool. That is + // We are on an executor, but _not_ on the thread pool. That is // _only_ okay if we are in a thread pool runtime's block_on // method: if allow_block_in_place { diff --git a/tokio/src/runtime/signal/mod.rs b/tokio/src/runtime/signal/mod.rs index bc50c6e982c..8055c0965a6 100644 --- a/tokio/src/runtime/signal/mod.rs +++ b/tokio/src/runtime/signal/mod.rs @@ -118,7 +118,7 @@ impl Driver { Ok(0) => panic!("EOF on self-pipe"), Ok(_) => continue, // Keep reading Err(e) if e.kind() == std_io::ErrorKind::WouldBlock => break, - Err(e) => panic!("Bad read on self-pipe: {}", e), + Err(e) => panic!("Bad read on self-pipe: {e}"), } } diff --git a/tokio/src/runtime/task/core.rs b/tokio/src/runtime/task/core.rs index 590e3fbc9d5..54fd5d39a6d 100644 --- a/tokio/src/runtime/task/core.rs +++ b/tokio/src/runtime/task/core.rs @@ -317,9 +317,8 @@ impl Core { let res = { self.stage.stage.with_mut(|ptr| { // Safety: The caller ensures mutual exclusion to the field. - let future = match unsafe { &mut *ptr } { - Stage::Running(future) => future, - _ => unreachable!("unexpected stage"), + let Stage::Running(future) = (unsafe { &mut *ptr }) else { + unreachable!("unexpected stage"); }; // Safety: The caller ensures the future is pinned. diff --git a/tokio/src/runtime/task/harness.rs b/tokio/src/runtime/task/harness.rs index 8479becd80a..55db44b85c3 100644 --- a/tokio/src/runtime/task/harness.rs +++ b/tokio/src/runtime/task/harness.rs @@ -89,7 +89,7 @@ impl RawTask { } /// This call notifies the task. It will not consume any ref-counts, but the - /// caller should hold a ref-count. This will create a new Notified and + /// caller should hold a ref-count. This will create a new Notified and /// submit it if necessary. pub(super) fn wake_by_ref(&self) { use super::state::TransitionToNotifiedByRef; diff --git a/tokio/src/runtime/task/id.rs b/tokio/src/runtime/task/id.rs index 9c3b1403ec2..8429495a121 100644 --- a/tokio/src/runtime/task/id.rs +++ b/tokio/src/runtime/task/id.rs @@ -50,7 +50,7 @@ pub fn id() -> Id { /// Returns the [`Id`] of the currently running task, or `None` if called outside /// of a task. /// -/// This function is similar to [`task::id()`](crate::runtime::task::id()), except +/// This function is similar to [`task::id()`](crate::runtime::task::id()), except /// that it returns `None` rather than panicking if called outside of a task /// context. /// diff --git a/tokio/src/runtime/task/list.rs b/tokio/src/runtime/task/list.rs index 988d422836d..4e75bf9666c 100644 --- a/tokio/src/runtime/task/list.rs +++ b/tokio/src/runtime/task/list.rs @@ -311,7 +311,7 @@ impl LocalOwnedTasks { F: FnOnce(&mut OwnedTasksInner) -> T, { // safety: This type is not Sync, so concurrent calls of this method - // can't happen. Furthermore, all uses of this method in this file make + // can't happen. Furthermore, all uses of this method in this file make // sure that they don't call `with_inner` recursively. self.inner.with_mut(|ptr| unsafe { f(&mut *ptr) }) } diff --git a/tokio/src/runtime/task/mod.rs b/tokio/src/runtime/task/mod.rs index 8248fc0b591..51421f4d02e 100644 --- a/tokio/src/runtime/task/mod.rs +++ b/tokio/src/runtime/task/mod.rs @@ -125,7 +125,7 @@ //! //! ## Non-Send futures //! -//! If a future is not Send, then it is bound to a `LocalOwnedTasks`. The future +//! If a future is not Send, then it is bound to a `LocalOwnedTasks`. The future //! will only ever be polled or dropped given a `LocalNotified` or inside a call //! to `LocalOwnedTasks::shutdown_all`. In either case, it is guaranteed that the //! future is on the right thread. diff --git a/tokio/src/runtime/task/state.rs b/tokio/src/runtime/task/state.rs index 0fc7bb0329b..d3327125a55 100644 --- a/tokio/src/runtime/task/state.rs +++ b/tokio/src/runtime/task/state.rs @@ -475,9 +475,8 @@ impl State { loop { let (output, next) = f(curr); - let next = match next { - Some(next) => next, - None => return output, + let Some(next) = next else { + return output; }; let res = self.val.compare_exchange(curr.0, next.0, AcqRel, Acquire); @@ -496,9 +495,8 @@ impl State { let mut curr = self.load(); loop { - let next = match f(curr) { - Some(next) => next, - None => return Err(curr), + let Some(next) = f(curr) else { + return Err(curr); }; let res = self.val.compare_exchange(curr.0, next.0, AcqRel, Acquire); diff --git a/tokio/src/runtime/tests/task_combinations.rs b/tokio/src/runtime/tests/task_combinations.rs index 0f99ed66247..3ad9fbfc8b4 100644 --- a/tokio/src/runtime/tests/task_combinations.rs +++ b/tokio/src/runtime/tests/task_combinations.rs @@ -114,7 +114,7 @@ fn test_combinations() { for ji in ji.iter().copied() { for jh in jh.iter().copied() { for abort in abort.iter().copied() { - // abort via join handle --- abort handles + // abort via join handle --- abort handles // may be dropped at any point for ah in ah.iter().copied() { test_combination( diff --git a/tokio/src/runtime/thread_id.rs b/tokio/src/runtime/thread_id.rs index ef392897963..132b84cecf9 100644 --- a/tokio/src/runtime/thread_id.rs +++ b/tokio/src/runtime/thread_id.rs @@ -11,9 +11,8 @@ impl ThreadId { let mut last = NEXT_ID.load(Relaxed); loop { - let id = match last.checked_add(1) { - Some(id) => id, - None => exhausted(), + let Some(id) = last.checked_add(1) else { + exhausted(); }; match NEXT_ID.compare_exchange_weak(last, id, Relaxed, Relaxed) { diff --git a/tokio/src/runtime/time/tests/mod.rs b/tokio/src/runtime/time/tests/mod.rs index 0e453433691..43a7d7600d9 100644 --- a/tokio/src/runtime/time/tests/mod.rs +++ b/tokio/src/runtime/time/tests/mod.rs @@ -71,7 +71,7 @@ fn single_timer() { time.process_at_time(0, time.time_source().now(clock) + 2_000_000_000); jh.join().unwrap(); - }) + }); } #[test] @@ -105,7 +105,7 @@ fn drop_timer() { time.process_at_time(0, time.time_source().now(clock) + 2_000_000_000); jh.join().unwrap(); - }) + }); } #[test] @@ -141,7 +141,7 @@ fn change_waker() { time.process_at_time(0, time.time_source().now(clock) + 2_000_000_000); jh.join().unwrap(); - }) + }); } #[test] @@ -199,7 +199,7 @@ fn reset_future() { jh.join().unwrap(); assert!(finished_early.load(Ordering::Relaxed)); - }) + }); } #[cfg(not(loom))] diff --git a/tokio/src/runtime/time/wheel/mod.rs b/tokio/src/runtime/time/wheel/mod.rs index f2b4228514c..3533e25051d 100644 --- a/tokio/src/runtime/time/wheel/mod.rs +++ b/tokio/src/runtime/time/wheel/mod.rs @@ -154,7 +154,7 @@ impl Wheel { _ => { // in this case the poll did not indicate an expiration // _and_ we were not able to find a next expiration in - // the current list of timers. advance to the poll's + // the current list of timers. Advance to the poll's // current time and do nothing else. self.set_elapsed(now); break; @@ -211,8 +211,8 @@ impl Wheel { res } - /// iteratively find entries that are between the wheel's current - /// time and the expiration time. for each in that population either + /// Iteratively find entries that are between the wheel's current + /// time and the expiration time. For each in that population either /// queue it for notification (in the case of the last level) or tier /// it down to the next level (in all other cases). pub(crate) fn process_expiration(&mut self, expiration: &Expiration) { @@ -298,13 +298,7 @@ mod test { #[test] fn test_level_for() { for pos in 0..64 { - assert_eq!( - 0, - level_for(0, pos), - "level_for({}) -- binary = {:b}", - pos, - pos - ); + assert_eq!(0, level_for(0, pos), "level_for({pos}) -- binary = {pos:b}",); } for level in 1..5 { @@ -313,9 +307,7 @@ mod test { assert_eq!( level, level_for(0, a as u64), - "level_for({}) -- binary = {:b}", - a, - a + "level_for({a}) -- binary = {a:b}", ); if pos > level { @@ -323,9 +315,7 @@ mod test { assert_eq!( level, level_for(0, a as u64), - "level_for({}) -- binary = {:b}", - a, - a + "level_for({a}) -- binary = {a:b}", ); } @@ -334,9 +324,7 @@ mod test { assert_eq!( level, level_for(0, a as u64), - "level_for({}) -- binary = {:b}", - a, - a + "level_for({a}) -- binary = {a:b}", ); } } diff --git a/tokio/src/signal/ctrl_c.rs b/tokio/src/signal/ctrl_c.rs index e1e92fa9977..2654d659a0f 100644 --- a/tokio/src/signal/ctrl_c.rs +++ b/tokio/src/signal/ctrl_c.rs @@ -26,7 +26,7 @@ use std::io; /// receives a signal generated by `"CTRL+C"` on the terminal. But, when a /// `ctrl_c` stream is created to listen for this signal, the time it arrives, /// it will be translated to a stream event, and the process will continue to -/// execute. **Even if this `Signal` instance is dropped, subsequent `SIGINT` +/// execute. **Even if this `Signal` instance is dropped, subsequent `SIGINT` /// deliveries will end up captured by Tokio, and the default platform behavior /// will NOT be reset**. /// diff --git a/tokio/src/signal/registry.rs b/tokio/src/signal/registry.rs index 3fff8df9303..e5358cae324 100644 --- a/tokio/src/signal/registry.rs +++ b/tokio/src/signal/registry.rs @@ -76,7 +76,7 @@ impl Registry { fn register_listener(&self, event_id: EventId) -> watch::Receiver<()> { self.storage .event_info(event_id) - .unwrap_or_else(|| panic!("invalid event_id: {}", event_id)) + .unwrap_or_else(|| panic!("invalid event_id: {event_id}")) .tx .subscribe() } diff --git a/tokio/src/signal/unix.rs b/tokio/src/signal/unix.rs index c4a196a660f..82a86c94a73 100644 --- a/tokio/src/signal/unix.rs +++ b/tokio/src/signal/unix.rs @@ -258,7 +258,7 @@ fn signal_enable(signal: SignalKind, handle: &Handle) -> io::Result<()> { if signal < 0 || signal_hook_registry::FORBIDDEN.contains(&signal) { return Err(Error::new( ErrorKind::Other, - format!("Refusing to register signal {}", signal), + format!("Refusing to register signal {signal}"), )); } @@ -266,9 +266,8 @@ fn signal_enable(signal: SignalKind, handle: &Handle) -> io::Result<()> { handle.check_inner()?; let globals = globals(); - let siginfo = match globals.storage().get(signal as EventId) { - Some(slot) => slot, - None => return Err(io::Error::new(io::ErrorKind::Other, "signal too large")), + let Some(siginfo) = globals.storage().get(signal as EventId) else { + return Err(io::Error::new(io::ErrorKind::Other, "signal too large")); }; let mut registered = Ok(()); siginfo.init.call_once(|| { diff --git a/tokio/src/sync/batch_semaphore.rs b/tokio/src/sync/batch_semaphore.rs index 84f88fb390e..e36bca67cfb 100644 --- a/tokio/src/sync/batch_semaphore.rs +++ b/tokio/src/sync/batch_semaphore.rs @@ -311,18 +311,15 @@ impl Semaphore { let mut waiters = lock.take().unwrap_or_else(|| self.waiters.lock()); 'inner: while wakers.can_push() { // Was the waiter assigned enough permits to wake it? - match waiters.queue.last() { - Some(waiter) => { - if !waiter.assign_permits(&mut rem) { - break 'inner; - } - } - None => { - is_empty = true; - // If we assigned permits to all the waiters in the queue, and there are - // still permits left over, assign them back to the semaphore. + if let Some(waiter) = waiters.queue.last() { + if !waiter.assign_permits(&mut rem) { break 'inner; } + } else { + is_empty = true; + // If we assigned permits to all the waiters in the queue, and there are + // still permits left over, assign them back to the semaphore. + break 'inner; }; let mut waiter = waiters.queue.pop_back().unwrap(); if let Some(waker) = diff --git a/tokio/src/sync/broadcast.rs b/tokio/src/sync/broadcast.rs index ba0a44fb8b9..454557d7a45 100644 --- a/tokio/src/sync/broadcast.rs +++ b/tokio/src/sync/broadcast.rs @@ -254,7 +254,7 @@ pub mod error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { RecvError::Closed => write!(f, "channel closed"), - RecvError::Lagged(amt) => write!(f, "channel lagged by {}", amt), + RecvError::Lagged(amt) => write!(f, "channel lagged by {amt}"), } } } @@ -290,7 +290,7 @@ pub mod error { match self { TryRecvError::Empty => write!(f, "channel empty"), TryRecvError::Closed => write!(f, "channel closed"), - TryRecvError::Lagged(amt) => write!(f, "channel lagged by {}", amt), + TryRecvError::Lagged(amt) => write!(f, "channel lagged by {amt}"), } } } diff --git a/tokio/src/sync/mpsc/block.rs b/tokio/src/sync/mpsc/block.rs index 927c4566463..0022d33752d 100644 --- a/tokio/src/sync/mpsc/block.rs +++ b/tokio/src/sync/mpsc/block.rs @@ -97,9 +97,8 @@ impl Block { // Allocate the block on the heap. // SAFETY: The size of the Block is non-zero, since it is at least the size of the header. let block = std::alloc::alloc(Layout::new::>()) as *mut Block; - let block = match NonNull::new(block) { - Some(block) => block, - None => std::alloc::handle_alloc_error(Layout::new::>()), + let Some(block) = NonNull::new(block) else { + std::alloc::handle_alloc_error(Layout::new::>()); }; // Write the header to the block. @@ -371,13 +370,10 @@ impl Block { .unwrap_or_else(|x| x), ); - let next = match next { - Some(next) => next, - None => { - // The compare-and-swap succeeded and the newly allocated block - // is successfully pushed. - return new_block; - } + let Some(next) = next else { + // The compare-and-swap succeeded and the newly allocated block + // is successfully pushed. + return new_block; }; // There already is a next block in the linked list. The newly allocated diff --git a/tokio/src/sync/mpsc/bounded.rs b/tokio/src/sync/mpsc/bounded.rs index beda7fe1bf4..5bba0be40a4 100644 --- a/tokio/src/sync/mpsc/bounded.rs +++ b/tokio/src/sync/mpsc/bounded.rs @@ -111,7 +111,7 @@ pub struct Receiver { /// Creates a bounded mpsc channel for communicating between asynchronous tasks /// with backpressure. /// -/// The channel will buffer up to the provided number of messages. Once the +/// The channel will buffer up to the provided number of messages. Once the /// buffer is full, attempts to send new messages will wait until a message is /// received from the channel. The provided buffer capacity must be at least 1. /// @@ -189,7 +189,7 @@ impl Receiver { /// /// If there are no messages in the channel's buffer, but the channel has /// not yet been closed, this method will sleep until a message is sent or - /// the channel is closed. Note that if [`close`] is called, but there are + /// the channel is closed. Note that if [`close`] is called, but there are /// still outstanding [`Permits`] from before it was closed, the channel is /// not considered closed by `recv` until the permits are released. /// @@ -622,7 +622,7 @@ impl Receiver { /// /// When the method returns `Poll::Pending`, the `Waker` in the provided /// `Context` is scheduled to receive a wakeup when a message is sent on any - /// receiver, or when the channel is closed. Note that on multiple calls to + /// receiver, or when the channel is closed. Note that on multiple calls to /// `poll_recv` or `poll_recv_many`, only the `Waker` from the `Context` /// passed to the most recent call is scheduled to receive a wakeup. /// @@ -646,7 +646,7 @@ impl Receiver { /// /// When the method returns `Poll::Pending`, the `Waker` in the provided /// `Context` is scheduled to receive a wakeup when a message is sent on any - /// receiver, or when the channel is closed. Note that on multiple calls to + /// receiver, or when the channel is closed. Note that on multiple calls to /// `poll_recv` or `poll_recv_many`, only the `Waker` from the `Context` /// passed to the most recent call is scheduled to receive a wakeup. /// @@ -768,7 +768,7 @@ impl Sender { /// capacity, then use the returned [`Permit`] to send the message. /// /// This channel uses a queue to ensure that calls to `send` and `reserve` - /// complete in the order they were requested. Cancelling a call to + /// complete in the order they were requested. Cancelling a call to /// `send` makes you lose your place in the queue. /// /// # Examples @@ -1068,7 +1068,7 @@ impl Sender { /// # Cancel safety /// /// This channel uses a queue to ensure that calls to `send` and `reserve` - /// complete in the order they were requested. Cancelling a call to + /// complete in the order they were requested. Cancelling a call to /// `reserve` makes you lose your place in the queue. /// /// # Examples @@ -1187,7 +1187,7 @@ impl Sender { /// # Cancel safety /// /// This channel uses a queue to ensure that calls to `send` and `reserve` - /// complete in the order they were requested. Cancelling a call to + /// complete in the order they were requested. Cancelling a call to /// `reserve_owned` makes you lose your place in the queue. /// /// # Examples @@ -1406,7 +1406,7 @@ impl Sender { /// This moves the sender _by value_, and returns an owned permit that can /// be used to send a message into the channel. Unlike [`Sender::try_reserve`], /// this method may be used in cases where the permit must be valid for the - /// `'static` lifetime. `Sender`s may be cloned cheaply (`Sender::clone` is + /// `'static` lifetime. `Sender`s may be cloned cheaply (`Sender::clone` is /// essentially a reference count increment, comparable to [`Arc::clone`]), /// so when multiple [`OwnedPermit`]s are needed or the `Sender` cannot be /// moved, it can be cloned prior to calling `try_reserve_owned`. @@ -1473,7 +1473,7 @@ impl Sender { /// /// ``` /// let (tx, rx) = tokio::sync::mpsc::channel::<()>(1); - /// let tx2 = tx.clone(); + /// let tx2 = tx.clone(); /// assert!(tx.same_channel(&tx2)); /// /// let (tx3, rx3) = tokio::sync::mpsc::channel::<()>(1); diff --git a/tokio/src/sync/mpsc/chan.rs b/tokio/src/sync/mpsc/chan.rs index 4006aa2b746..31dbcf3216d 100644 --- a/tokio/src/sync/mpsc/chan.rs +++ b/tokio/src/sync/mpsc/chan.rs @@ -546,7 +546,7 @@ impl Semaphore for bounded::Semaphore { } fn add_permits(&self, n: usize) { - self.semaphore.release(n) + self.semaphore.release(n); } fn is_idle(&self) -> bool { diff --git a/tokio/src/sync/mpsc/list.rs b/tokio/src/sync/mpsc/list.rs index 90d9b828c8e..0b2c8b99d25 100644 --- a/tokio/src/sync/mpsc/list.rs +++ b/tokio/src/sync/mpsc/list.rs @@ -316,11 +316,8 @@ impl Rx { block.load_next(Acquire) }; - let next_block = match next_block { - Some(next_block) => next_block, - None => { - return false; - } + let Some(next_block) = next_block else { + return false; }; self.head = next_block; @@ -338,9 +335,8 @@ impl Rx { let observed_tail_position = block.as_ref().observed_tail_position(); - let required_index = match observed_tail_position { - Some(i) => i, - None => return, + let Some(required_index) = observed_tail_position else { + return; }; if required_index > self.index { diff --git a/tokio/src/sync/mpsc/mod.rs b/tokio/src/sync/mpsc/mod.rs index e6601e90a4a..fddcdd4cedc 100644 --- a/tokio/src/sync/mpsc/mod.rs +++ b/tokio/src/sync/mpsc/mod.rs @@ -59,7 +59,7 @@ //! **Unbounded channel**: You should use the kind of channel that matches where //! the receiver is. So for sending a message _from async to sync_, you should //! use [the standard library unbounded channel][std-unbounded] or -//! [crossbeam][crossbeam-unbounded]. Similarly, for sending a message _from sync +//! [crossbeam][crossbeam-unbounded]. Similarly, for sending a message _from sync //! to async_, you should use an unbounded Tokio `mpsc` channel. //! //! Please be aware that the above remarks were written with the `mpsc` channel diff --git a/tokio/src/sync/mpsc/unbounded.rs b/tokio/src/sync/mpsc/unbounded.rs index 47e1b6c7c77..27df586c56b 100644 --- a/tokio/src/sync/mpsc/unbounded.rs +++ b/tokio/src/sync/mpsc/unbounded.rs @@ -409,7 +409,7 @@ impl UnboundedReceiver { /// /// When the method returns `Poll::Pending`, the `Waker` in the provided /// `Context` is scheduled to receive a wakeup when a message is sent on any - /// receiver, or when the channel is closed. Note that on multiple calls to + /// receiver, or when the channel is closed. Note that on multiple calls to /// `poll_recv` or `poll_recv_many`, only the `Waker` from the `Context` /// passed to the most recent call is scheduled to receive a wakeup. /// @@ -433,7 +433,7 @@ impl UnboundedReceiver { /// /// When the method returns `Poll::Pending`, the `Waker` in the provided /// `Context` is scheduled to receive a wakeup when a message is sent on any - /// receiver, or when the channel is closed. Note that on multiple calls to + /// receiver, or when the channel is closed. Note that on multiple calls to /// `poll_recv` or `poll_recv_many`, only the `Waker` from the `Context` /// passed to the most recent call is scheduled to receive a wakeup. /// @@ -635,7 +635,7 @@ impl UnboundedSender { /// /// ``` /// let (tx, rx) = tokio::sync::mpsc::unbounded_channel::<()>(); - /// let tx2 = tx.clone(); + /// let tx2 = tx.clone(); /// assert!(tx.same_channel(&tx2)); /// /// let (tx3, rx3) = tokio::sync::mpsc::unbounded_channel::<()>(); diff --git a/tokio/src/sync/mutex.rs b/tokio/src/sync/mutex.rs index 30f0bdecedb..6fe6afa8970 100644 --- a/tokio/src/sync/mutex.rs +++ b/tokio/src/sync/mutex.rs @@ -405,7 +405,7 @@ impl Mutex { } /// Locks this mutex, causing the current task to yield until the lock has - /// been acquired. When the lock has been acquired, function returns a + /// been acquired. When the lock has been acquired, function returns a /// [`MutexGuard`]. /// /// If the mutex is available to be acquired immediately, then this call @@ -489,7 +489,7 @@ impl Mutex { /// /// #[tokio::main] /// async fn main() { - /// let mutex = Arc::new(Mutex::new(1)); + /// let mutex = Arc::new(Mutex::new(1)); /// let lock = mutex.lock().await; /// /// let mutex1 = Arc::clone(&mutex); @@ -546,7 +546,7 @@ impl Mutex { /// /// #[tokio::main] /// async fn main() { - /// let mutex = Arc::new(Mutex::new(1)); + /// let mutex = Arc::new(Mutex::new(1)); /// let lock = mutex.lock().await; /// /// let mutex1 = Arc::clone(&mutex); @@ -726,7 +726,7 @@ impl Mutex { /// is currently held somewhere else. /// /// This method is identical to [`Mutex::try_lock`], except that the - /// returned guard references the `Mutex` with an [`Arc`] rather than by + /// returned guard references the `Mutex` with an [`Arc`] rather than by /// borrowing it. Therefore, the `Mutex` must be wrapped in an `Arc` to call /// this method, and the guard will live for the `'static` lifetime, as it /// keeps the `Mutex` alive by holding an `Arc`. diff --git a/tokio/src/sync/notify.rs b/tokio/src/sync/notify.rs index 5d344f70411..55e10e3b925 100644 --- a/tokio/src/sync/notify.rs +++ b/tokio/src/sync/notify.rs @@ -36,7 +36,7 @@ type GuardedWaitList = GuardedLinkedList:: /// The synchronization details of `Notify` are similar to /// [`thread::park`][park] and [`Thread::unpark`][unpark] from std. A [`Notify`] /// value contains a single permit. [`notified().await`] waits for the permit to -/// be made available, consumes the permit, and resumes. [`notify_one()`] sets +/// be made available, consumes the permit, and resumes. [`notify_one()`] sets /// the permit, waking a pending task if there is one. /// /// If `notify_one()` is called **before** `notified().await`, then the next diff --git a/tokio/src/sync/once_cell.rs b/tokio/src/sync/once_cell.rs index 82b8259c667..8d0b3f2364e 100644 --- a/tokio/src/sync/once_cell.rs +++ b/tokio/src/sync/once_cell.rs @@ -358,24 +358,21 @@ impl OnceCell { // will allow us to set the value of the OnceCell, and prevents // other tasks from initializing the OnceCell while we are holding // it. - match self.semaphore.acquire().await { - Ok(permit) => { - debug_assert!(!self.initialized()); + if let Ok(permit) = self.semaphore.acquire().await { + debug_assert!(!self.initialized()); - // If `f()` panics or `select!` is called, this - // `get_or_init` call is aborted and the semaphore permit is - // dropped. - let value = f().await; + // If `f()` panics or `select!` is called, this + // `get_or_init` call is aborted and the semaphore permit is + // dropped. + let value = f().await; - self.set_value(value, permit) - } - Err(_) => { - debug_assert!(self.initialized()); + self.set_value(value, permit) + } else { + debug_assert!(self.initialized()); - // SAFETY: The semaphore has been closed. This only happens - // when the OnceCell is fully initialized. - unsafe { self.get_unchecked() } - } + // SAFETY: The semaphore has been closed. This only happens + // when the OnceCell is fully initialized. + unsafe { self.get_unchecked() } } } } @@ -408,27 +405,24 @@ impl OnceCell { // will allow us to set the value of the OnceCell, and prevents // other tasks from initializing the OnceCell while we are holding // it. - match self.semaphore.acquire().await { - Ok(permit) => { - debug_assert!(!self.initialized()); - - // If `f()` panics or `select!` is called, this - // `get_or_try_init` call is aborted and the semaphore - // permit is dropped. - let value = f().await; - - match value { - Ok(value) => Ok(self.set_value(value, permit)), - Err(e) => Err(e), - } - } - Err(_) => { - debug_assert!(self.initialized()); + if let Ok(permit) = self.semaphore.acquire().await { + debug_assert!(!self.initialized()); + + // If `f()` panics or `select!` is called, this + // `get_or_try_init` call is aborted and the semaphore + // permit is dropped. + let value = f().await; - // SAFETY: The semaphore has been closed. This only happens - // when the OnceCell is fully initialized. - unsafe { Ok(self.get_unchecked()) } + match value { + Ok(value) => Ok(self.set_value(value, permit)), + Err(e) => Err(e), } + } else { + debug_assert!(self.initialized()); + + // SAFETY: The semaphore has been closed. This only happens + // when the OnceCell is fully initialized. + unsafe { Ok(self.get_unchecked()) } } } } @@ -445,7 +439,7 @@ impl OnceCell { } } - /// Takes ownership of the current value, leaving the cell empty. Returns + /// Takes ownership of the current value, leaving the cell empty. Returns /// `None` if the cell is empty. pub fn take(&mut self) -> Option { std::mem::take(self).into_inner() diff --git a/tokio/src/sync/oneshot.rs b/tokio/src/sync/oneshot.rs index ab29b3e3edd..1eb9635f67d 100644 --- a/tokio/src/sync/oneshot.rs +++ b/tokio/src/sync/oneshot.rs @@ -139,7 +139,7 @@ use std::task::{Context, Poll, Waker}; /// Sends a value to the associated [`Receiver`]. /// -/// A pair of both a [`Sender`] and a [`Receiver`] are created by the +/// A pair of both a [`Sender`] and a [`Receiver`] are created by the /// [`channel`](fn@channel) function. /// /// # Examples @@ -227,7 +227,7 @@ pub struct Sender { /// Receives a value from the associated [`Sender`]. /// -/// A pair of both a [`Sender`] and a [`Receiver`] are created by the +/// A pair of both a [`Sender`] and a [`Receiver`] are created by the /// [`channel`](fn@channel) function. /// /// This channel has no `recv` method because the receiver itself implements the @@ -557,7 +557,7 @@ impl Sender { /// /// This method consumes `self` as only one value may ever be sent on a `oneshot` /// channel. It is not marked async because sending a message to an `oneshot` - /// channel never requires any form of waiting. Because of this, the `send` + /// channel never requires any form of waiting. Because of this, the `send` /// method can be used in both synchronous and asynchronous code without /// problems. /// diff --git a/tokio/src/sync/rwlock.rs b/tokio/src/sync/rwlock.rs index 14983d5cb32..7ca57dbfe40 100644 --- a/tokio/src/sync/rwlock.rs +++ b/tokio/src/sync/rwlock.rs @@ -274,8 +274,7 @@ impl RwLock { { assert!( max_reads <= MAX_READS, - "a RwLock may not be created with more than {} readers", - MAX_READS + "a RwLock may not be created with more than {MAX_READS} readers", ); #[cfg(all(tokio_unstable, feature = "tracing"))] @@ -837,7 +836,7 @@ impl RwLock { /// /// #[tokio::main] /// async fn main() { - /// let rwlock = Arc::new(RwLock::new(1)); + /// let rwlock = Arc::new(RwLock::new(1)); /// let read_lock = rwlock.read().await; /// /// let blocking_task = tokio::task::spawn_blocking({ @@ -1095,7 +1094,7 @@ impl From for RwLock { } } -impl Default for RwLock +impl Default for RwLock where T: Default, { diff --git a/tokio/src/sync/watch.rs b/tokio/src/sync/watch.rs index 366066797f1..3b4c27120a7 100644 --- a/tokio/src/sync/watch.rs +++ b/tokio/src/sync/watch.rs @@ -46,7 +46,7 @@ //! //! If the receiver intends to await notifications from [`changed`] in a loop, //! [`Receiver::borrow_and_update()`] should be preferred over -//! [`Receiver::borrow()`]. This avoids a potential race where a new value is +//! [`Receiver::borrow()`]. This avoids a potential race where a new value is //! sent between [`changed`] being ready and the value being read. (If //! [`Receiver::borrow()`] is used, the loop may run twice with the same value.) //! diff --git a/tokio/src/task/blocking.rs b/tokio/src/task/blocking.rs index 193c28dfd0f..80ab8f30496 100644 --- a/tokio/src/task/blocking.rs +++ b/tokio/src/task/blocking.rs @@ -93,7 +93,7 @@ cfg_rt! { /// After reaching the upper limit, the tasks are put in a queue. /// The thread limit is very large by default, because `spawn_blocking` is often /// used for various kinds of IO operations that cannot be performed - /// asynchronously. When you run CPU-bound code using `spawn_blocking`, you + /// asynchronously. When you run CPU-bound code using `spawn_blocking`, you /// should keep this large upper limit in mind. When running many CPU-bound /// computations, a semaphore or some other synchronization primitive should be /// used to limit the number of computation executed in parallel. Specialized @@ -112,7 +112,7 @@ cfg_rt! { /// When you shut down the executor, it will wait indefinitely for all blocking operations to /// finish. You can use [`shutdown_timeout`] to stop waiting for them after a /// certain timeout. Be aware that this will still not cancel the tasks — they - /// are simply allowed to keep running after the method returns. It is possible + /// are simply allowed to keep running after the method returns. It is possible /// for a blocking task to be cancelled if it has not yet started running, but this /// is not guaranteed. /// @@ -131,7 +131,7 @@ cfg_rt! { /// by `spawn_blocking`. /// /// Another option is [`SyncIoBridge`] for cases where the synchronous context - /// is operating on byte streams. For example, you might use an asynchronous + /// is operating on byte streams. For example, you might use an asynchronous /// HTTP client such as [hyper] to fetch data, but perform complex parsing /// of the payload body using a library written for synchronous I/O. /// diff --git a/tokio/src/task/consume_budget.rs b/tokio/src/task/consume_budget.rs index 1e398d73b2a..320390a3515 100644 --- a/tokio/src/task/consume_budget.rs +++ b/tokio/src/task/consume_budget.rs @@ -37,5 +37,5 @@ pub async fn consume_budget() { }); status }) - .await + .await; } diff --git a/tokio/src/task/join_set.rs b/tokio/src/task/join_set.rs index 612e53addb3..9277ab27a25 100644 --- a/tokio/src/task/join_set.rs +++ b/tokio/src/task/join_set.rs @@ -418,15 +418,12 @@ impl JoinSet { pub fn poll_join_next(&mut self, cx: &mut Context<'_>) -> Poll>> { // The call to `pop_notified` moves the entry to the `idle` list. It is moved back to // the `notified` list if the waker is notified in the `poll` call below. - let mut entry = match self.inner.pop_notified(cx.waker()) { - Some(entry) => entry, - None => { - if self.is_empty() { - return Poll::Ready(None); - } else { - // The waker was set by `pop_notified`. - return Poll::Pending; - } + let Some(mut entry) = self.inner.pop_notified(cx.waker()) else { + if self.is_empty() { + return Poll::Ready(None); + } else { + // The waker was set by `pop_notified`. + return Poll::Pending; } }; diff --git a/tokio/src/task/local.rs b/tokio/src/task/local.rs index 08d89c49c03..c21e2fcb96a 100644 --- a/tokio/src/task/local.rs +++ b/tokio/src/task/local.rs @@ -315,7 +315,7 @@ impl<'a> Drop for LocalDataEnterGuard<'a> { self.local_data_ref.ctx.set(self.ctx.take()); self.local_data_ref .wake_on_schedule - .set(self.wake_on_schedule) + .set(self.wake_on_schedule); } } @@ -552,7 +552,7 @@ impl LocalSet { /// use tokio::runtime::Runtime; /// use tokio::task; /// - /// let rt = Runtime::new().unwrap(); + /// let rt = Runtime::new().unwrap(); /// let local = task::LocalSet::new(); /// local.block_on(&rt, async { /// let join = task::spawn_local(async { @@ -569,7 +569,7 @@ impl LocalSet { /// use tokio::runtime::Runtime; /// use tokio::task; /// - /// let rt = Runtime::new().unwrap(); + /// let rt = Runtime::new().unwrap(); /// let local = task::LocalSet::new(); /// local.block_on(&rt, async { /// let join = task::spawn_local(async { @@ -711,7 +711,7 @@ impl LocalSet { .queue .lock() .as_mut() - .and_then(|queue| queue.pop_front()) + .and_then(VecDeque::pop_front) .or_else(|| self.pop_local()) } else { self.pop_local().or_else(|| { @@ -1200,7 +1200,7 @@ mod tests { crate::runtime::Builder::new_current_thread() .build() .expect("rt") - .block_on(f) + .block_on(f); } // Tests that when a task on a `LocalSet` is woken by an io driver on the @@ -1245,6 +1245,6 @@ mod tests { task.is_some(), "task should have been notified to the LocalSet's local queue" ); - }) + }); } } diff --git a/tokio/src/task/task_local.rs b/tokio/src/task/task_local.rs index cb9d22c61e7..92bf3f88d84 100644 --- a/tokio/src/task/task_local.rs +++ b/tokio/src/task/task_local.rs @@ -273,7 +273,7 @@ impl LocalKey { /// This function will panic if the task local doesn't have a value set. #[track_caller] pub fn get(&'static self) -> T { - self.with(|v| v.clone()) + self.with(Clone::clone) } } diff --git a/tokio/src/time/clock.rs b/tokio/src/time/clock.rs index 50884f972fa..cb7cf8bf444 100644 --- a/tokio/src/time/clock.rs +++ b/tokio/src/time/clock.rs @@ -28,9 +28,9 @@ cfg_not_test_util! { } cfg_test_util! { - use crate::time::{Duration, Instant}; - use crate::loom::sync::Mutex; use crate::loom::sync::atomic::Ordering; + use crate::loom::sync::Mutex; + use crate::time::{Duration, Instant}; use std::sync::atomic::AtomicBool as StdAtomicBool; cfg_rt! { @@ -38,13 +38,13 @@ cfg_test_util! { fn with_clock(f: impl FnOnce(Option<&Clock>) -> Result) -> R { use crate::runtime::Handle; - let res = match Handle::try_current() { + let result = match Handle::try_current() { Ok(handle) => f(Some(handle.inner.driver().clock())), Err(ref e) if e.is_missing_context() => f(None), Err(_) => panic!("{}", crate::util::error::THREAD_LOCAL_DESTROYED_ERROR), }; - match res { + match result { Ok(ret) => ret, Err(msg) => panic!("{}", msg), } @@ -128,11 +128,9 @@ cfg_test_util! { /// [`advance`]: crate::time::advance #[track_caller] pub fn pause() { - with_clock(|maybe_clock| { - match maybe_clock { - Some(clock) => clock.pause(), - None => Err("time cannot be frozen from outside the Tokio runtime"), - } + with_clock(|maybe_clock| match maybe_clock { + Some(clock) => clock.pause(), + None => Err("time cannot be frozen from outside the Tokio runtime"), }); } @@ -148,9 +146,8 @@ cfg_test_util! { #[track_caller] pub fn resume() { with_clock(|maybe_clock| { - let clock = match maybe_clock { - Some(clock) => clock, - None => return Err("time cannot be frozen from outside the Tokio runtime"), + let Some(clock) = maybe_clock else { + return Err("time cannot be frozen from outside the Tokio runtime"); }; let mut inner = clock.inner.lock(); @@ -172,7 +169,7 @@ cfg_test_util! { /// This function will make the current time jump forward by the given /// duration in one jump. This means that all `sleep` calls with a deadline /// before the new time will immediately complete "at the same time", and - /// the runtime is free to poll them in any order. Additionally, this + /// the runtime is free to poll them in any order. Additionally, this /// method will not wait for the `sleep` calls it advanced past to complete. /// If you want to do that, you should instead call [`sleep`] and rely on /// the runtime's auto-advance feature. @@ -197,9 +194,8 @@ cfg_test_util! { /// [`sleep`]: fn@crate::time::sleep pub async fn advance(duration: Duration) { with_clock(|maybe_clock| { - let clock = match maybe_clock { - Some(clock) => clock, - None => return Err("time cannot be frozen from outside the Tokio runtime"), + let Some(clock) = maybe_clock else { + return Err("time cannot be frozen from outside the Tokio runtime"); }; clock.advance(duration) @@ -261,7 +257,7 @@ cfg_test_util! { let elapsed = match inner.unfrozen.as_ref() { Some(v) => v.elapsed(), - None => return Err("time is already frozen") + None => return Err("time is already frozen"), }; inner.base += elapsed; inner.unfrozen = None; diff --git a/tokio/src/time/error.rs b/tokio/src/time/error.rs index 3d6025f5f29..21920059090 100644 --- a/tokio/src/time/error.rs +++ b/tokio/src/time/error.rs @@ -96,7 +96,7 @@ impl fmt::Display for Error { Kind::AtCapacity => "timer is at capacity and cannot create a new entry", Kind::Invalid => "timer duration exceeds maximum duration", }; - write!(fmt, "{}", descr) + write!(fmt, "{descr}") } } diff --git a/tokio/src/time/sleep.rs b/tokio/src/time/sleep.rs index d5a68f09554..f0ecc934e62 100644 --- a/tokio/src/time/sleep.rs +++ b/tokio/src/time/sleep.rs @@ -447,7 +447,7 @@ impl Future for Sleep { let _ao_poll_span = self.inner.ctx.async_op_poll_span.clone().entered(); match ready!(self.as_mut().poll_elapsed(cx)) { Ok(()) => Poll::Ready(()), - Err(e) => panic!("timer error: {}", e), + Err(e) => panic!("timer error: {e}"), } } } diff --git a/tokio/src/util/linked_list.rs b/tokio/src/util/linked_list.rs index 3650f87fbb0..fd5df7517b3 100644 --- a/tokio/src/util/linked_list.rs +++ b/tokio/src/util/linked_list.rs @@ -520,7 +520,7 @@ pub(crate) mod tests { list: &mut LinkedList<&'a Entry, <&'_ Entry as Link>::Target>, entries: &[Pin<&'a Entry>], ) { - for entry in entries.iter() { + for entry in entries { list.push_front(*entry); } } diff --git a/tokio/src/util/metric_atomics.rs b/tokio/src/util/metric_atomics.rs index afc1cd4c7f4..9c1ec1c3e0f 100644 --- a/tokio/src/util/metric_atomics.rs +++ b/tokio/src/util/metric_atomics.rs @@ -26,7 +26,7 @@ impl MetricAtomicU64 { cfg_64bit_metrics! { pub(crate) fn store(&self, val: u64, ordering: Ordering) { - self.value.store(val, ordering) + self.value.store(val, ordering); } pub(crate) fn new(value: u64) -> Self { @@ -41,7 +41,7 @@ impl MetricAtomicU64 { cfg_no_64bit_metrics! { pub(crate) fn store(&self, _val: u64, _ordering: Ordering) { } // on platforms without 64-bit atomics, fetch-add returns unit - pub(crate) fn add(&self, _value: u64, _ordering: Ordering) { } + pub(crate) fn add(&self, _value: u64, _ordering: Ordering) { } pub(crate) fn new(_value: u64) -> Self { Self { } } } } @@ -68,7 +68,7 @@ impl MetricAtomicUsize { } pub(crate) fn store(&self, val: usize, ordering: Ordering) { - self.value.store(val, ordering) + self.value.store(val, ordering); } pub(crate) fn increment(&self) -> usize { diff --git a/tokio/src/util/sharded_list.rs b/tokio/src/util/sharded_list.rs index 525cec9ea77..2f8b7a0e11e 100644 --- a/tokio/src/util/sharded_list.rs +++ b/tokio/src/util/sharded_list.rs @@ -39,7 +39,7 @@ impl ShardedList { let shard_mask = sharded_size - 1; let mut lists = Vec::with_capacity(sharded_size); for _ in 0..sharded_size { - lists.push(Mutex::new(LinkedList::::new())) + lists.push(Mutex::new(LinkedList::::new())); } Self { lists: lists.into_boxed_slice(), diff --git a/tokio/tests/fs_file.rs b/tokio/tests/fs_file.rs index 520c4ec8438..2656f521ddf 100644 --- a/tokio/tests/fs_file.rs +++ b/tokio/tests/fs_file.rs @@ -210,7 +210,7 @@ async fn file_debug_fmt() { let file = File::open(tempfile.path()).await.unwrap(); assert_eq!( - &format!("{:?}", file)[0..33], + &format!("{file:?}")[0..33], "tokio::fs::File { std: File { fd:" ); } diff --git a/tokio/tests/fs_open_options.rs b/tokio/tests/fs_open_options.rs index 84b63a504cf..58d7de647e2 100644 --- a/tokio/tests/fs_open_options.rs +++ b/tokio/tests/fs_open_options.rs @@ -59,8 +59,7 @@ async fn open_options_mode() { // TESTING HACK: use Debug output to check the stored data assert!( mode.contains("mode: 420 ") || mode.contains("mode: 0o000644 "), - "mode is: {}", - mode + "mode is: {mode}" ); } diff --git a/tokio/tests/io_async_fd.rs b/tokio/tests/io_async_fd.rs index f4dcfcf0927..ba1e5eac35a 100644 --- a/tokio/tests/io_async_fd.rs +++ b/tokio/tests/io_async_fd.rs @@ -104,13 +104,12 @@ fn set_nonblocking(fd: RawFd) { let flags = nix::fcntl::fcntl(fd, F_GETFL).expect("fcntl(F_GETFD)"); - if flags < 0 { - panic!( - "bad return value from fcntl(F_GETFL): {} ({:?})", - flags, - nix::Error::last() - ); - } + assert!( + flags >= 0, + "bad return value from fcntl(F_GETFL): {} ({:?})", + flags, + nix::Error::last() + ); let flags = OFlag::from_bits_truncate(flags) | OFlag::O_NONBLOCK; @@ -141,7 +140,7 @@ fn drain(mut fd: &FileDescriptor, mut amt: usize) { match fd.read(&mut buf[..]) { Err(e) if e.kind() == ErrorKind::WouldBlock => {} Ok(0) => panic!("unexpected EOF"), - Err(e) => panic!("unexpected error: {:?}", e), + Err(e) => panic!("unexpected error: {e:?}"), Ok(x) => amt -= x, } } @@ -352,7 +351,7 @@ async fn multiple_waiters() { biased; guard = afd_a.readable() => { tokio::task::yield_now().await; - guard.unwrap().clear_ready() + guard.unwrap().clear_ready(); }, _ = notify_barrier => unreachable!(), } diff --git a/tokio/tests/io_buf_reader.rs b/tokio/tests/io_buf_reader.rs index 0d3f6bafc20..8f27f8c3b11 100644 --- a/tokio/tests/io_buf_reader.rs +++ b/tokio/tests/io_buf_reader.rs @@ -316,7 +316,7 @@ async fn maybe_pending_seek() { } fn consume(mut self: Pin<&mut Self>, amt: usize) { - Pin::new(&mut self.inner).consume(amt) + Pin::new(&mut self.inner).consume(amt); } } diff --git a/tokio/tests/io_copy_bidirectional.rs b/tokio/tests/io_copy_bidirectional.rs index 3cdce32d0ce..c99826f2ed2 100644 --- a/tokio/tests/io_copy_bidirectional.rs +++ b/tokio/tests/io_copy_bidirectional.rs @@ -24,7 +24,7 @@ async fn block_write(s: &mut TcpStream) -> usize { loop { tokio::select! { result = s.write(&BUF) => { - copied += result.expect("write error") + copied += result.expect("write error"); }, _ = tokio::time::sleep(Duration::from_millis(10)) => { break; @@ -66,7 +66,7 @@ async fn test_basic_transfer() { b.read_exact(&mut tmp).await.unwrap(); assert_eq!(&tmp[..], b"test"); }) - .await + .await; } #[tokio::test] @@ -85,7 +85,7 @@ async fn test_transfer_after_close() { assert_eq!(handle.await.unwrap().unwrap(), (0, 4)); }) - .await + .await; } #[tokio::test] @@ -107,7 +107,7 @@ async fn blocking_one_side_does_not_block_other() { assert_eq!(handle.await.unwrap().unwrap(), (buf.len() as u64, 4)); }) - .await + .await; } #[tokio::test] diff --git a/tokio/tests/io_join.rs b/tokio/tests/io_join.rs index 69b09393311..9b9f1e5ae5b 100644 --- a/tokio/tests/io_join.rs +++ b/tokio/tests/io_join.rs @@ -15,7 +15,7 @@ impl AsyncRead for R { _cx: &mut Context<'_>, buf: &mut ReadBuf<'_>, ) -> Poll> { - buf.put_slice(&[b'z']); + buf.put_slice(b"z"); Poll::Ready(Ok(())) } } @@ -68,12 +68,10 @@ fn method_delegation() { assert_eq!(1, rw.read(&mut buf).await.unwrap()); assert_eq!(b'z', buf[0]); - assert_eq!(1, rw.write(&[b'x']).await.unwrap()); + assert_eq!(1, rw.write(b"x").await.unwrap()); assert_eq!( 2, - rw.write_vectored(&[io::IoSlice::new(&[b'x'])]) - .await - .unwrap() + rw.write_vectored(&[io::IoSlice::new(b"x")]).await.unwrap() ); assert!(rw.is_write_vectored()); diff --git a/tokio/tests/io_panic.rs b/tokio/tests/io_panic.rs index 9e4cda21f3b..048244d8a93 100644 --- a/tokio/tests/io_panic.rs +++ b/tokio/tests/io_panic.rs @@ -19,7 +19,7 @@ impl AsyncRead for RW { _cx: &mut Context<'_>, buf: &mut ReadBuf<'_>, ) -> Poll> { - buf.put_slice(&[b'z']); + buf.put_slice(b"z"); Poll::Ready(Ok(())) } } diff --git a/tokio/tests/io_poll_aio.rs b/tokio/tests/io_poll_aio.rs index 242887eb60f..f60ed4ded76 100644 --- a/tokio/tests/io_poll_aio.rs +++ b/tokio/tests/io_poll_aio.rs @@ -51,7 +51,7 @@ mod aio { Poll::Pending => Poll::Pending, Poll::Ready(Err(e)) => Poll::Ready(Err(e)), Poll::Ready(Ok(_ev)) => { - // At this point, we could clear readiness. But there's no + // At this point, we could clear readiness. But there's no // point, since we're about to drop the Aio. let p = unsafe { self.map_unchecked_mut(|s| &mut s.0 .0) }; let result = p.aio_return(); @@ -118,7 +118,7 @@ mod aio { Poll::Ready(Ok(ev)) => { // Clearing readiness makes the future non-idempotent; the // caller can't poll it repeatedly after it has already - // returned Ready. But that's ok; most futures behave this + // returned Ready. But that's ok; most futures behave this // way. self.0.clear_ready(ev); let r = unsafe { libc::aio_return(self.0 .0.as_mut().get_unchecked_mut()) }; @@ -197,7 +197,7 @@ mod lio { /// Low-level source based on lio_listio /// - /// An example demonstrating using AIO with `Interest::Lio`. mio_aio 0.8 + /// An example demonstrating using AIO with `Interest::Lio`. mio_aio 0.8 /// doesn't include any bindings for lio_listio, so we've got to go /// low-level. struct LioSource<'a> { @@ -259,8 +259,8 @@ mod lio { Poll::Ready(Ok(ev)) => { // Clearing readiness makes the future non-idempotent; the // caller can't poll it repeatedly after it has already - // returned Ready. But that's ok; most futures behave this - // way. Clearing readiness is especially useful for + // returned Ready. But that's ok; most futures behave this + // way. Clearing readiness is especially useful for // lio_listio, because sometimes some operations will be // ready but not all. self.0.clear_ready(ev); diff --git a/tokio/tests/io_read_to_string.rs b/tokio/tests/io_read_to_string.rs index f30c26caa88..80649353b28 100644 --- a/tokio/tests/io_read_to_string.rs +++ b/tokio/tests/io_read_to_string.rs @@ -23,9 +23,9 @@ async fn to_string_does_not_truncate_on_utf8_error() { let mut s = "abc".to_string(); match AsyncReadExt::read_to_string(&mut data.as_slice(), &mut s).await { - Ok(len) => panic!("Should fail: {} bytes.", len), + Ok(len) => panic!("Should fail: {len} bytes."), Err(err) if err.to_string() == "stream did not contain valid UTF-8" => {} - Err(err) => panic!("Fail: {}.", err), + Err(err) => panic!("Fail: {err}."), } assert_eq!(s, "abc"); @@ -40,9 +40,9 @@ async fn to_string_does_not_truncate_on_io_error() { let mut s = "abc".to_string(); match AsyncReadExt::read_to_string(&mut mock, &mut s).await { - Ok(len) => panic!("Should fail: {} bytes.", len), + Ok(len) => panic!("Should fail: {len} bytes."), Err(err) if err.to_string() == "whoops" => {} - Err(err) => panic!("Fail: {}.", err), + Err(err) => panic!("Fail: {err}."), } assert_eq!(s, "abc"); diff --git a/tokio/tests/io_split.rs b/tokio/tests/io_split.rs index 9f17c9eb14e..983982ccaf9 100644 --- a/tokio/tests/io_split.rs +++ b/tokio/tests/io_split.rs @@ -17,7 +17,7 @@ impl AsyncRead for RW { _cx: &mut Context<'_>, buf: &mut ReadBuf<'_>, ) -> Poll> { - buf.put_slice(&[b'z']); + buf.put_slice(b"z"); Poll::Ready(Ok(())) } } @@ -101,12 +101,10 @@ fn method_delegation() { assert_eq!(1, r.read(&mut buf).await.unwrap()); assert_eq!(b'z', buf[0]); - assert_eq!(1, w.write(&[b'x']).await.unwrap()); + assert_eq!(1, w.write(b"x").await.unwrap()); assert_eq!( 2, - w.write_vectored(&[io::IoSlice::new(&[b'x'])]) - .await - .unwrap() + w.write_vectored(&[io::IoSlice::new(b"x")]).await.unwrap() ); assert!(w.is_write_vectored()); diff --git a/tokio/tests/macros_test.rs b/tokio/tests/macros_test.rs index bed443cf293..36a3ac7d062 100644 --- a/tokio/tests/macros_test.rs +++ b/tokio/tests/macros_test.rs @@ -32,12 +32,12 @@ fn trait_method() { impl A for () { #[tokio::main] async fn f(self) { - self.g() + self.g(); } fn g(self) {} } - ().f() + ().f(); } // https://github.com/tokio-rs/tokio/issues/4175 diff --git a/tokio/tests/process_issue_42.rs b/tokio/tests/process_issue_42.rs index 569c122e36a..5d28c272d9a 100644 --- a/tokio/tests/process_issue_42.rs +++ b/tokio/tests/process_issue_42.rs @@ -19,7 +19,7 @@ async fn issue_42() { task::spawn(async { let processes = (0..10usize).map(|i| { let mut child = Command::new("echo") - .arg(format!("I am spawned process #{}", i)) + .arg(format!("I am spawned process #{i}")) .stdin(Stdio::null()) .stdout(Stdio::null()) .stderr(Stdio::null()) diff --git a/tokio/tests/rt_common.rs b/tokio/tests/rt_common.rs index 75a20057166..97054e92c0c 100644 --- a/tokio/tests/rt_common.rs +++ b/tokio/tests/rt_common.rs @@ -575,7 +575,7 @@ rt_test! { assert_ok!(inner.await) }); - assert_eq!(out, "hello") + assert_eq!(out, "hello"); } #[cfg(not(target_os="wasi"))] // Wasi does not support threads @@ -591,7 +591,7 @@ rt_test! { assert_ok!(inner.await) }); - assert_eq!(out, "hello") + assert_eq!(out, "hello"); } #[cfg(not(target_os="wasi"))] // Wasi does not support threads @@ -893,7 +893,7 @@ rt_test! { Poll::Pending } }) - .await + .await; } #[test] @@ -938,7 +938,7 @@ rt_test! { tokio::spawn(async move { assert_ok!(run_tx.send(())); - Never { drop_tx }.await + Never { drop_tx }.await; }); assert_ok!(run_rx.await); @@ -957,7 +957,7 @@ rt_test! { impl Drop for OnDrop { fn drop(&mut self) { - (self.0)() + (self.0)(); } } diff --git a/tokio/tests/rt_handle_block_on.rs b/tokio/tests/rt_handle_block_on.rs index 95365ec5216..5f1dc8ee1ca 100644 --- a/tokio/tests/rt_handle_block_on.rs +++ b/tokio/tests/rt_handle_block_on.rs @@ -123,7 +123,7 @@ fn unbounded_mpsc_channel() { let value = Handle::current().block_on(rx.recv()).unwrap(); assert_eq!(value, 42); - }) + }); } #[cfg(not(target_os = "wasi"))] // Wasi doesn't support file operations or bind diff --git a/tokio/tests/rt_threaded.rs b/tokio/tests/rt_threaded.rs index a4742dd234e..4a2e226de18 100644 --- a/tokio/tests/rt_threaded.rs +++ b/tokio/tests/rt_threaded.rs @@ -341,7 +341,7 @@ fn blocking() { tokio::task::block_in_place(move || { block.wait(); block.wait(); - }) + }); }); } block.wait(); @@ -429,14 +429,12 @@ fn coop_and_block_in_place() { Pin::new(&mut fut).poll(cx) } { - if v.is_none() { - panic!("did not yield"); - } + assert!(v.is_some(), "did not yield"); } Poll::Ready(()) }) - .await + .await; }) .await .unwrap(); @@ -465,7 +463,7 @@ fn yield_after_block_in_place() { tokio::task::yield_now().await; }) .await - .unwrap() + .unwrap(); }); } @@ -637,10 +635,10 @@ fn test_nested_block_in_place_with_block_on_between() { h.block_on(async { tokio::task::block_in_place(|| {}); }); - }) + }); }) .await - .unwrap() + .unwrap(); }); } } diff --git a/tokio/tests/signal_multi_rt.rs b/tokio/tests/signal_multi_rt.rs index 1e0402c4794..024c1a2797d 100644 --- a/tokio/tests/signal_multi_rt.rs +++ b/tokio/tests/signal_multi_rt.rs @@ -34,7 +34,7 @@ fn multi_loop() { }) .collect(); // Wait for them to declare they're ready - for &_ in threads.iter() { + for _ in &threads { receiver.recv().unwrap(); } // Send a signal diff --git a/tokio/tests/sync_mpsc.rs b/tokio/tests/sync_mpsc.rs index cc88fa79972..89af0b2fdea 100644 --- a/tokio/tests/sync_mpsc.rs +++ b/tokio/tests/sync_mpsc.rs @@ -265,7 +265,7 @@ async fn send_recv_many_bounded_capacity() { .map(|x: usize| format!("{x}")) .collect::>(); for x in expected.clone() { - tx.send(x).await.unwrap() + tx.send(x).await.unwrap(); } tx.send("one more".to_string()).await.unwrap(); @@ -307,7 +307,7 @@ async fn send_recv_many_unbounded_capacity() { .map(|x: usize| format!("{x}")) .collect::>(); for x in expected.clone() { - tx.send(x).unwrap() + tx.send(x).unwrap(); } tx.send("one more".to_string()).unwrap(); @@ -807,7 +807,7 @@ fn blocking_recv() { .block_on(async move { let _ = tx.send(10).await; }); - sync_code.join().unwrap() + sync_code.join().unwrap(); } #[tokio::test] @@ -832,7 +832,7 @@ fn blocking_send() { .block_on(async move { assert_eq!(Some(10), rx.recv().await); }); - sync_code.join().unwrap() + sync_code.join().unwrap(); } #[tokio::test] @@ -1092,14 +1092,14 @@ async fn test_rx_is_not_closed_when_there_are_permits_but_not_senders() { #[tokio::test] async fn test_rx_is_empty_when_no_messages_were_sent() { let (_tx, rx) = mpsc::channel::<()>(10); - assert!(rx.is_empty()) + assert!(rx.is_empty()); } #[tokio::test] async fn test_rx_is_not_empty_when_there_are_messages_in_the_buffer() { let (tx, rx) = mpsc::channel::<()>(10); assert!(tx.send(()).await.is_ok()); - assert!(!rx.is_empty()) + assert!(!rx.is_empty()); } #[tokio::test] @@ -1108,7 +1108,7 @@ async fn test_rx_is_not_empty_when_the_buffer_is_full() { for i in 0..10 { assert!(tx.send(i).await.is_ok()); } - assert!(!rx.is_empty()) + assert!(!rx.is_empty()); } #[tokio::test] @@ -1122,7 +1122,7 @@ async fn test_rx_is_not_empty_when_all_but_one_messages_are_consumed() { assert!(rx.recv().await.is_some()); } - assert!(!rx.is_empty()) + assert!(!rx.is_empty()); } #[tokio::test] @@ -1132,7 +1132,7 @@ async fn test_rx_is_empty_when_all_messages_are_consumed() { assert!(tx.send(i).await.is_ok()); } while rx.try_recv().is_ok() {} - assert!(rx.is_empty()) + assert!(rx.is_empty()); } #[tokio::test] @@ -1147,7 +1147,7 @@ async fn test_rx_is_empty_all_senders_are_dropped_and_messages_consumed() { assert!(rx.recv().await.is_some()); } - assert!(rx.is_empty()) + assert!(rx.is_empty()); } #[tokio::test] @@ -1289,14 +1289,14 @@ async fn test_rx_unbounded_is_closed_when_there_are_messages_and_close_is_called #[tokio::test] async fn test_rx_unbounded_is_empty_when_no_messages_were_sent() { let (_tx, rx) = mpsc::unbounded_channel::<()>(); - assert!(rx.is_empty()) + assert!(rx.is_empty()); } #[tokio::test] async fn test_rx_unbounded_is_not_empty_when_there_are_messages_in_the_buffer() { let (tx, rx) = mpsc::unbounded_channel(); assert!(tx.send(()).is_ok()); - assert!(!rx.is_empty()) + assert!(!rx.is_empty()); } #[tokio::test] @@ -1310,7 +1310,7 @@ async fn test_rx_unbounded_is_not_empty_when_all_but_one_messages_are_consumed() assert!(rx.recv().await.is_some()); } - assert!(!rx.is_empty()) + assert!(!rx.is_empty()); } #[tokio::test] @@ -1320,7 +1320,7 @@ async fn test_rx_unbounded_is_empty_when_all_messages_are_consumed() { assert!(tx.send(i).is_ok()); } while rx.try_recv().is_ok() {} - assert!(rx.is_empty()) + assert!(rx.is_empty()); } #[tokio::test] @@ -1335,7 +1335,7 @@ async fn test_rx_unbounded_is_empty_all_senders_are_dropped_and_messages_consume assert!(rx.recv().await.is_some()); } - assert!(rx.is_empty()) + assert!(rx.is_empty()); } #[tokio::test] diff --git a/tokio/tests/sync_mpsc_weak.rs b/tokio/tests/sync_mpsc_weak.rs index fba0fe4e33a..c62c70a002f 100644 --- a/tokio/tests/sync_mpsc_weak.rs +++ b/tokio/tests/sync_mpsc_weak.rs @@ -37,16 +37,13 @@ async fn weak_sender() { for i in 0..12 { let recvd = rx.recv().await; - match recvd { - Some(msg) => { - if i == 10 { - assert_eq!(msg, 20); - } - } - None => { - assert_eq!(i, 11); - break; + if let Some(msg) = recvd { + if i == 10 { + assert_eq!(msg, 20); } + } else { + assert_eq!(i, 11); + break; } } @@ -120,7 +117,7 @@ async fn actor_weak_sender() { self.send_message_to_self().await; } - i += 1 + i += 1; } assert!(self.received_self_msg); @@ -298,16 +295,13 @@ async fn weak_unbounded_sender() { for i in 0..12 { let recvd = rx.recv().await; - match recvd { - Some(msg) => { - if i == 10 { - assert_eq!(msg, 20); - } - } - None => { - assert_eq!(i, 11); - break; + if let Some(msg) = recvd { + if i == 10 { + assert_eq!(msg, 20); } + } else { + assert_eq!(i, 11); + break; } } @@ -360,7 +354,7 @@ async fn actor_weak_unbounded_sender() { } } - async fn send_message_to_self(&mut self) { + fn send_message_to_self(&mut self) { let msg = ActorMessage::SelfMessage {}; let sender = self.sender.clone(); @@ -378,10 +372,10 @@ async fn actor_weak_unbounded_sender() { self.handle_message(msg); if i == 0 { - self.send_message_to_self().await; + self.send_message_to_self(); } - i += 1 + i += 1; } assert!(self.received_self_msg); diff --git a/tokio/tests/sync_mutex.rs b/tokio/tests/sync_mutex.rs index f423c82e7b1..7564fbf25b7 100644 --- a/tokio/tests/sync_mutex.rs +++ b/tokio/tests/sync_mutex.rs @@ -165,14 +165,14 @@ fn try_lock() { async fn debug_format() { let s = "debug"; let m = Mutex::new(s.to_string()); - assert_eq!(format!("{:?}", s), format!("{:?}", m.lock().await)); + assert_eq!(format!("{s:?}"), format!("{:?}", m.lock().await)); } #[maybe_tokio_test] async fn mutex_debug() { let s = "data"; let m = Mutex::new(s.to_string()); - assert_eq!(format!("{:?}", m), r#"Mutex { data: "data" }"#); + assert_eq!(format!("{m:?}"), r#"Mutex { data: "data" }"#); let _guard = m.lock().await; - assert_eq!(format!("{:?}", m), r#"Mutex { data: }"#) + assert_eq!(format!("{m:?}"), r#"Mutex { data: }"#); } diff --git a/tokio/tests/sync_mutex_owned.rs b/tokio/tests/sync_mutex_owned.rs index badcef3d08e..44503d50c1b 100644 --- a/tokio/tests/sync_mutex_owned.rs +++ b/tokio/tests/sync_mutex_owned.rs @@ -132,5 +132,5 @@ fn try_lock_owned() { async fn debug_format() { let s = "debug"; let m = Arc::new(Mutex::new(s.to_string())); - assert_eq!(format!("{:?}", s), format!("{:?}", m.lock_owned().await)); + assert_eq!(format!("{s:?}"), format!("{:?}", m.lock_owned().await)); } diff --git a/tokio/tests/sync_once_cell.rs b/tokio/tests/sync_once_cell.rs index b662db3add1..ecaf2877621 100644 --- a/tokio/tests/sync_once_cell.rs +++ b/tokio/tests/sync_once_cell.rs @@ -26,7 +26,7 @@ fn drop_cell() { { let once_cell = OnceCell::new(); let prev = once_cell.set(fooer); - assert!(prev.is_ok()) + assert!(prev.is_ok()); } assert!(NUM_DROPS.load(Ordering::Acquire) == 1); } diff --git a/tokio/tests/sync_rwlock.rs b/tokio/tests/sync_rwlock.rs index f711804ce26..b10d9b0082c 100644 --- a/tokio/tests/sync_rwlock.rs +++ b/tokio/tests/sync_rwlock.rs @@ -267,14 +267,14 @@ fn try_read_try_write() { assert!(lock.try_write().is_err()); let rg2 = lock.try_read().unwrap(); - assert_eq!(*rg2, 15) + assert_eq!(*rg2, 15); } { let mut wg = lock.try_write().unwrap(); *wg = 1515; - assert!(lock.try_read().is_err()) + assert!(lock.try_read().is_err()); } assert_eq!(*lock.try_read().unwrap(), 1515); diff --git a/tokio/tests/sync_semaphore_owned.rs b/tokio/tests/sync_semaphore_owned.rs index f9eeee0cfab..b4c621d9900 100644 --- a/tokio/tests/sync_semaphore_owned.rs +++ b/tokio/tests/sync_semaphore_owned.rs @@ -111,7 +111,7 @@ fn merge_unrelated_permits() { let sem2 = Arc::new(Semaphore::new(3)); let mut p1 = sem1.try_acquire_owned().unwrap(); let p2 = sem2.try_acquire_owned().unwrap(); - p1.merge(p2) + p1.merge(p2); } #[test] diff --git a/tokio/tests/sync_watch.rs b/tokio/tests/sync_watch.rs index 17f0c81087a..e2ca4596546 100644 --- a/tokio/tests/sync_watch.rs +++ b/tokio/tests/sync_watch.rs @@ -98,7 +98,7 @@ fn rx_mark_changed() { rx4.mark_changed(); assert!(rx4.has_changed().unwrap()); - assert_eq!(*rx4.borrow_and_update(), "two") + assert_eq!(*rx4.borrow_and_update(), "two"); } assert_eq!(*rx.borrow(), "two"); @@ -323,7 +323,7 @@ fn send_modify_panic() { tx.send_modify(|old| { *old = "panicked"; panic!(); - }) + }); })); assert!(result.is_err()); diff --git a/tokio/tests/task_abort.rs b/tokio/tests/task_abort.rs index 0e742de13e2..0477c08a0e8 100644 --- a/tokio/tests/task_abort.rs +++ b/tokio/tests/task_abort.rs @@ -158,7 +158,7 @@ fn test_abort_wakes_task_3964() { let handle = tokio::spawn(async move { // Make sure the Arc is moved into the task let _notify_dropped = notify_dropped; - tokio::time::sleep(Duration::new(100, 0)).await + tokio::time::sleep(Duration::new(100, 0)).await; }); // wait for task to sleep. @@ -186,7 +186,7 @@ fn test_abort_task_that_panics_on_drop_contained() { let handle = tokio::spawn(async move { // Make sure the Arc is moved into the task let _panic_dropped = PanicOnDrop; - tokio::time::sleep(Duration::new(100, 0)).await + tokio::time::sleep(Duration::new(100, 0)).await; }); // wait for task to sleep. @@ -210,7 +210,7 @@ fn test_abort_task_that_panics_on_drop_returned() { let handle = tokio::spawn(async move { // Make sure the Arc is moved into the task let _panic_dropped = PanicOnDrop; - tokio::time::sleep(Duration::new(100, 0)).await + tokio::time::sleep(Duration::new(100, 0)).await; }); // wait for task to sleep. @@ -233,7 +233,7 @@ fn test_join_error_display() { // `String` payload let join_err = tokio::spawn(async move { let value = 1234; - panic!("Format-args payload: {}", value) + panic!("Format-args payload: {value}") }) .await .unwrap_err(); @@ -244,8 +244,7 @@ fn test_join_error_display() { assert!( join_err_str.starts_with("task ") && join_err_str.ends_with(" panicked with message \"Format-args payload: 1234\""), - "Unexpected join_err_str {:?}", - join_err_str + "Unexpected join_err_str {join_err_str:?}" ); // `&'static str` payload @@ -258,8 +257,7 @@ fn test_join_error_display() { assert!( join_err_str.starts_with("task ") && join_err_str.ends_with(" panicked with message \"Const payload\""), - "Unexpected join_err_str {:?}", - join_err_str + "Unexpected join_err_str {join_err_str:?}" ); // Non-string payload @@ -271,8 +269,7 @@ fn test_join_error_display() { assert!( join_err_str.starts_with("task ") && join_err_str.ends_with(" panicked"), - "Unexpected join_err_str {:?}", - join_err_str + "Unexpected join_err_str {join_err_str:?}" ); }); } @@ -287,19 +284,18 @@ fn test_join_error_debug() { // `String` payload let join_err = tokio::spawn(async move { let value = 1234; - panic!("Format-args payload: {}", value) + panic!("Format-args payload: {value}") }) .await .unwrap_err(); // We can't assert the full output because the task ID can change. - let join_err_str = format!("{:?}", join_err); + let join_err_str = format!("{join_err:?}"); assert!( join_err_str.starts_with("JoinError::Panic(Id(") && join_err_str.ends_with("), \"Format-args payload: 1234\", ...)"), - "Unexpected join_err_str {:?}", - join_err_str + "Unexpected join_err_str {join_err_str:?}" ); // `&'static str` payload @@ -307,13 +303,12 @@ fn test_join_error_debug() { .await .unwrap_err(); - let join_err_str = format!("{:?}", join_err); + let join_err_str = format!("{join_err:?}"); assert!( join_err_str.starts_with("JoinError::Panic(Id(") && join_err_str.ends_with("), \"Const payload\", ...)"), - "Unexpected join_err_str {:?}", - join_err_str + "Unexpected join_err_str {join_err_str:?}" ); // Non-string payload @@ -321,12 +316,11 @@ fn test_join_error_debug() { .await .unwrap_err(); - let join_err_str = format!("{:?}", join_err); + let join_err_str = format!("{join_err:?}"); assert!( join_err_str.starts_with("JoinError::Panic(Id(") && join_err_str.ends_with("), ...)"), - "Unexpected join_err_str {:?}", - join_err_str + "Unexpected join_err_str {join_err_str:?}" ); }); } diff --git a/tokio/tests/task_blocking.rs b/tokio/tests/task_blocking.rs index b9cce9a4aa4..c15767a7a75 100644 --- a/tokio/tests/task_blocking.rs +++ b/tokio/tests/task_blocking.rs @@ -108,8 +108,8 @@ fn can_enter_current_thread_rt_from_within_block_in_place() { .build() .unwrap(); - inner.block_on(async {}) - }) + inner.block_on(async {}); + }); }); } @@ -134,8 +134,7 @@ fn useful_panic_message_when_dropping_rt_in_rt() { assert!( err.contains("Cannot drop a runtime"), - "Wrong panic message: {:?}", - err + "Wrong panic message: {err:?}" ); } @@ -183,14 +182,14 @@ fn coop_disabled_in_block_in_place() { futures::executor::block_on(async move { use tokio_stream::StreamExt; assert_eq!(rx.fold(0, |n, _| n + 1).await, 200); - }) - }) + }); + }); }); tokio::time::timeout(Duration::from_secs(1), jh) .await .expect("timed out (probably hanging)") - .unwrap() + .unwrap(); }); } @@ -213,8 +212,8 @@ fn coop_disabled_in_block_in_place_in_block_on() { futures::executor::block_on(async move { use tokio_stream::StreamExt; assert_eq!(rx.fold(0, |n, _| n + 1).await, 200); - }) - }) + }); + }); }); let _ = done.send(Ok(())); diff --git a/tokio/tests/task_join_set.rs b/tokio/tests/task_join_set.rs index e87135337ba..b77455052a8 100644 --- a/tokio/tests/task_join_set.rs +++ b/tokio/tests/task_join_set.rs @@ -214,7 +214,7 @@ async fn join_set_coop() { loop { match set.join_next().now_or_never() { Some(Some(Ok(()))) => {} - Some(Some(Err(err))) => panic!("failed: {}", err), + Some(Some(Err(err))) => panic!("failed: {err}"), None => { coop_count += 1; tokio::task::yield_now().await; @@ -254,7 +254,7 @@ async fn try_join_next() { Some(Ok(())) => { count += 1; } - Some(Err(err)) => panic!("failed: {}", err), + Some(Err(err)) => panic!("failed: {err}"), None => { break; } diff --git a/tokio/tests/task_local_set.rs b/tokio/tests/task_local_set.rs index ac46291a36c..5b71bb1c45d 100644 --- a/tokio/tests/task_local_set.rs +++ b/tokio/tests/task_local_set.rs @@ -42,9 +42,9 @@ async fn local_threadpool() { LocalSet::new() .run_until(async { - assert!(ON_RT_THREAD.with(|cell| cell.get())); + assert!(ON_RT_THREAD.with(Cell::get)); task::spawn_local(async { - assert!(ON_RT_THREAD.with(|cell| cell.get())); + assert!(ON_RT_THREAD.with(Cell::get)); }) .await .unwrap(); @@ -63,7 +63,7 @@ async fn localset_future_threadpool() { let local = LocalSet::new(); local.spawn_local(async move { - assert!(ON_LOCAL_THREAD.with(|cell| cell.get())); + assert!(ON_LOCAL_THREAD.with(Cell::get)); }); local.await; } @@ -126,11 +126,11 @@ async fn local_threadpool_timer() { LocalSet::new() .run_until(async { - assert!(ON_RT_THREAD.with(|cell| cell.get())); + assert!(ON_RT_THREAD.with(Cell::get)); let join = task::spawn_local(async move { - assert!(ON_RT_THREAD.with(|cell| cell.get())); + assert!(ON_RT_THREAD.with(Cell::get)); time::sleep(Duration::from_millis(10)).await; - assert!(ON_RT_THREAD.with(|cell| cell.get())); + assert!(ON_RT_THREAD.with(Cell::get)); }); join.await.unwrap(); }) @@ -169,11 +169,11 @@ fn local_threadpool_blocking_in_place() { .build() .unwrap(); LocalSet::new().block_on(&rt, async { - assert!(ON_RT_THREAD.with(|cell| cell.get())); + assert!(ON_RT_THREAD.with(Cell::get)); let join = task::spawn_local(async move { - assert!(ON_RT_THREAD.with(|cell| cell.get())); + assert!(ON_RT_THREAD.with(Cell::get)); task::block_in_place(|| {}); - assert!(ON_RT_THREAD.with(|cell| cell.get())); + assert!(ON_RT_THREAD.with(Cell::get)); }); join.await.unwrap(); }); @@ -190,18 +190,18 @@ async fn local_threadpool_blocking_run() { LocalSet::new() .run_until(async { - assert!(ON_RT_THREAD.with(|cell| cell.get())); + assert!(ON_RT_THREAD.with(Cell::get)); let join = task::spawn_local(async move { - assert!(ON_RT_THREAD.with(|cell| cell.get())); + assert!(ON_RT_THREAD.with(Cell::get)); task::spawn_blocking(|| { assert!( - !ON_RT_THREAD.with(|cell| cell.get()), + !ON_RT_THREAD.with(Cell::get), "blocking must not run on the local task set's thread" ); }) .await .unwrap(); - assert!(ON_RT_THREAD.with(|cell| cell.get())); + assert!(ON_RT_THREAD.with(Cell::get)); }); join.await.unwrap(); }) @@ -220,11 +220,11 @@ async fn all_spawns_are_local() { LocalSet::new() .run_until(async { - assert!(ON_RT_THREAD.with(|cell| cell.get())); + assert!(ON_RT_THREAD.with(Cell::get)); let handles = (0..128) .map(|_| { task::spawn_local(async { - assert!(ON_RT_THREAD.with(|cell| cell.get())); + assert!(ON_RT_THREAD.with(Cell::get)); }) }) .collect::>(); @@ -246,15 +246,15 @@ async fn nested_spawn_is_local() { LocalSet::new() .run_until(async { - assert!(ON_RT_THREAD.with(|cell| cell.get())); + assert!(ON_RT_THREAD.with(Cell::get)); task::spawn_local(async { - assert!(ON_RT_THREAD.with(|cell| cell.get())); + assert!(ON_RT_THREAD.with(Cell::get)); task::spawn_local(async { - assert!(ON_RT_THREAD.with(|cell| cell.get())); + assert!(ON_RT_THREAD.with(Cell::get)); task::spawn_local(async { - assert!(ON_RT_THREAD.with(|cell| cell.get())); + assert!(ON_RT_THREAD.with(Cell::get)); task::spawn_local(async { - assert!(ON_RT_THREAD.with(|cell| cell.get())); + assert!(ON_RT_THREAD.with(Cell::get)); }) .await .unwrap(); @@ -286,7 +286,7 @@ fn join_local_future_elsewhere() { let (tx, rx) = oneshot::channel(); let join = task::spawn_local(async move { assert!( - ON_RT_THREAD.with(|cell| cell.get()), + ON_RT_THREAD.with(Cell::get), "local task must run on local thread, no matter where it is awaited" ); rx.await.unwrap(); @@ -295,7 +295,7 @@ fn join_local_future_elsewhere() { }); let join2 = task::spawn(async move { assert!( - !ON_RT_THREAD.with(|cell| cell.get()), + !ON_RT_THREAD.with(Cell::get), "spawned task should be on a worker" ); @@ -303,7 +303,7 @@ fn join_local_future_elsewhere() { join.await.expect("task should complete successfully"); }); - join2.await.unwrap() + join2.await.unwrap(); }); } @@ -323,7 +323,7 @@ async fn localset_in_thread_local() { LOCAL_SET.with(|local_set| { handle.block_on(local_set.run_until(async move { let _ = rx.await; - })) + })); }); }); } @@ -385,9 +385,8 @@ fn with_timeout(timeout: Duration, f: impl FnOnce() + Send + 'static) { // in case CI is slow, we'll give it a long timeout. match done_rx.recv_timeout(timeout) { Err(RecvTimeoutError::Timeout) => panic!( - "test did not complete within {:?} seconds, \ + "test did not complete within {timeout:?} seconds, \ we have (probably) entered an infinite loop!", - timeout, ), // Did the test thread panic? We'll find out for sure when we `join` // with it. @@ -396,7 +395,7 @@ fn with_timeout(timeout: Duration, f: impl FnOnce() + Send + 'static) { Ok(()) => {} } - thread.join().expect("test thread should not panic!") + thread.join().expect("test thread should not panic!"); } #[cfg_attr( @@ -624,7 +623,7 @@ fn store_local_set_in_thread_local_with_runtime() { .run_until(async move { tokio::task::spawn_local(async {}); }) - .await + .await; } fn method(&self) { diff --git a/tokio/tests/tcp_into_split.rs b/tokio/tests/tcp_into_split.rs index df8efadb50f..7b57b7a7449 100644 --- a/tokio/tests/tcp_into_split.rs +++ b/tokio/tests/tcp_into_split.rs @@ -97,7 +97,7 @@ async fn drop_write() -> Result<()> { Ok(0) => Ok(()), Ok(len) => Err(Error::new( ErrorKind::Other, - format!("Unexpected read: {} bytes.", len), + format!("Unexpected read: {len} bytes."), )), Err(err) => Err(err), }; @@ -122,8 +122,8 @@ async fn drop_write() -> Result<()> { match read_half.read(&mut read_buf[..]).await { Ok(0) => {} - Ok(len) => panic!("Unexpected read: {} bytes.", len), - Err(err) => panic!("Unexpected error: {}.", err), + Ok(len) => panic!("Unexpected read: {len} bytes."), + Err(err) => panic!("Unexpected error: {err}."), } handle.join().unwrap().unwrap(); diff --git a/tokio/tests/tcp_stream.rs b/tokio/tests/tcp_stream.rs index 725a60169ea..b8789714088 100644 --- a/tokio/tests/tcp_stream.rs +++ b/tokio/tests/tcp_stream.rs @@ -66,7 +66,7 @@ async fn try_read_write() { Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => { break; } - Err(e) => panic!("error = {:?}", e), + Err(e) => panic!("error = {e:?}"), } } @@ -85,7 +85,7 @@ async fn try_read_write() { match server.try_read(&mut read[i..]) { Ok(n) => i += n, Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => continue, - Err(e) => panic!("error = {:?}", e), + Err(e) => panic!("error = {e:?}"), } } @@ -107,7 +107,7 @@ async fn try_read_write() { Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => { break; } - Err(e) => panic!("error = {:?}", e), + Err(e) => panic!("error = {e:?}"), } } @@ -130,7 +130,7 @@ async fn try_read_write() { match server.try_read_vectored(&mut bufs) { Ok(n) => i += n, Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => continue, - Err(e) => panic!("error = {:?}", e), + Err(e) => panic!("error = {e:?}"), } } @@ -322,7 +322,7 @@ async fn try_read_buf() { Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => { break; } - Err(e) => panic!("error = {:?}", e), + Err(e) => panic!("error = {e:?}"), } } @@ -341,7 +341,7 @@ async fn try_read_buf() { match server.try_read_buf(&mut read) { Ok(n) => i += n, Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => continue, - Err(e) => panic!("error = {:?}", e), + Err(e) => panic!("error = {e:?}"), } } diff --git a/tokio/tests/time_interval.rs b/tokio/tests/time_interval.rs index 7472a37123c..f72fd22f26b 100644 --- a/tokio/tests/time_interval.rs +++ b/tokio/tests/time_interval.rs @@ -360,7 +360,7 @@ fn ms(n: u64) -> Duration { Duration::from_millis(n) } -/// Helper struct to test the [tokio::time::Interval::poll_tick()] method. +/// Helper struct to test the [`tokio::time::Interval::poll_tick()`] method. /// /// `poll_tick()` should register the waker in the context only if it returns /// `Poll::Pending`, not when returning `Poll::Ready`. This struct contains an diff --git a/tokio/tests/time_sleep.rs b/tokio/tests/time_sleep.rs index 6da7ada0394..d475eb92191 100644 --- a/tokio/tests/time_sleep.rs +++ b/tokio/tests/time_sleep.rs @@ -357,7 +357,7 @@ async fn drop_from_wake() { impl futures::task::ArcWake for DropWaker { fn wake_by_ref(arc_self: &Arc) { let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - *arc_self.1.lock().expect("panic in lock") = Vec::new() + *arc_self.1.lock().expect("panic in lock") = Vec::new(); })); if result.is_err() { diff --git a/tokio/tests/udp.rs b/tokio/tests/udp.rs index eea281c2316..f6b2989e4c5 100644 --- a/tokio/tests/udp.rs +++ b/tokio/tests/udp.rs @@ -372,7 +372,7 @@ async fn try_send_spawn() { .unwrap(); assert_eq!(sent, &MSG_LEN); let mut buf = [0u8; 32]; - let mut received = receiver.recv(&mut buf[..]).await.unwrap(); + let mut bytes_received = receiver.recv(&mut buf[..]).await.unwrap(); sender .connect(receiver.local_addr().unwrap()) @@ -380,7 +380,7 @@ async fn try_send_spawn() { .unwrap(); let sent = &sender.try_send(MSG2).unwrap(); assert_eq!(sent, &MSG2_LEN); - received += receiver.recv(&mut buf[..]).await.unwrap(); + bytes_received += receiver.recv(&mut buf[..]).await.unwrap(); std::thread::spawn(move || { let sent = &sender.try_send(MSG).unwrap(); @@ -388,9 +388,9 @@ async fn try_send_spawn() { }) .join() .unwrap(); - received += receiver.recv(&mut buf[..]).await.unwrap(); + bytes_received += receiver.recv(&mut buf[..]).await.unwrap(); - assert_eq!(received, MSG_LEN * 2 + MSG2_LEN); + assert_eq!(bytes_received, MSG_LEN * 2 + MSG2_LEN); } #[tokio::test] @@ -415,7 +415,7 @@ async fn try_send_recv() { break; } Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => continue, - Err(e) => panic!("{:?}", e), + Err(e) => panic!("{e:?}"), } } @@ -431,7 +431,7 @@ async fn try_send_recv() { break; } Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => continue, - Err(e) => panic!("{:?}", e), + Err(e) => panic!("{e:?}"), } } } @@ -457,7 +457,7 @@ async fn try_send_to_recv_from() { break; } Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => continue, - Err(e) => panic!("{:?}", e), + Err(e) => panic!("{e:?}"), } } @@ -474,7 +474,7 @@ async fn try_send_to_recv_from() { break; } Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => continue, - Err(e) => panic!("{:?}", e), + Err(e) => panic!("{e:?}"), } } } @@ -502,7 +502,7 @@ async fn try_recv_buf() { break; } Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => continue, - Err(e) => panic!("{:?}", e), + Err(e) => panic!("{e:?}"), } } @@ -518,7 +518,7 @@ async fn try_recv_buf() { break; } Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => continue, - Err(e) => panic!("{:?}", e), + Err(e) => panic!("{e:?}"), } } } @@ -561,7 +561,7 @@ async fn try_recv_buf_from() { break; } Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => continue, - Err(e) => panic!("{:?}", e), + Err(e) => panic!("{e:?}"), } } @@ -578,7 +578,7 @@ async fn try_recv_buf_from() { break; } Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => continue, - Err(e) => panic!("{:?}", e), + Err(e) => panic!("{e:?}"), } } } @@ -621,7 +621,7 @@ async fn poll_ready() { break; } Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => continue, - Err(e) => panic!("{:?}", e), + Err(e) => panic!("{e:?}"), } } @@ -638,7 +638,7 @@ async fn poll_ready() { break; } Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => continue, - Err(e) => panic!("{:?}", e), + Err(e) => panic!("{e:?}"), } } } diff --git a/tokio/tests/uds_datagram.rs b/tokio/tests/uds_datagram.rs index ad22a0b99dd..4a32755de66 100644 --- a/tokio/tests/uds_datagram.rs +++ b/tokio/tests/uds_datagram.rs @@ -87,7 +87,7 @@ async fn try_send_recv_never_block() -> io::Result<()> { (io::ErrorKind::WouldBlock, _) => break, (_, Some(libc::ENOBUFS)) => break, _ => { - panic!("unexpected error {:?}", err); + panic!("unexpected error {err:?}"); } }, Ok(len) => { @@ -205,7 +205,7 @@ async fn try_send_to_recv_from() -> std::io::Result<()> { break; } Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => continue, - Err(e) => panic!("{:?}", e), + Err(e) => panic!("{e:?}"), } } @@ -222,7 +222,7 @@ async fn try_send_to_recv_from() -> std::io::Result<()> { break; } Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => continue, - Err(e) => panic!("{:?}", e), + Err(e) => panic!("{e:?}"), } } } @@ -252,7 +252,7 @@ async fn try_recv_buf_from() -> std::io::Result<()> { break; } Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => continue, - Err(e) => panic!("{:?}", e), + Err(e) => panic!("{e:?}"), } } @@ -269,7 +269,7 @@ async fn try_recv_buf_from() -> std::io::Result<()> { break; } Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => continue, - Err(e) => panic!("{:?}", e), + Err(e) => panic!("{e:?}"), } } } @@ -316,7 +316,7 @@ async fn try_recv_buf_never_block() -> io::Result<()> { (io::ErrorKind::WouldBlock, _) => break, (_, Some(libc::ENOBUFS)) => break, _ => { - panic!("unexpected error {:?}", err); + panic!("unexpected error {err:?}"); } }, Ok(len) => { @@ -387,7 +387,7 @@ async fn poll_ready() -> io::Result<()> { break; } Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => continue, - Err(e) => panic!("{:?}", e), + Err(e) => panic!("{e:?}"), } } @@ -404,7 +404,7 @@ async fn poll_ready() -> io::Result<()> { break; } Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => continue, - Err(e) => panic!("{:?}", e), + Err(e) => panic!("{e:?}"), } } } diff --git a/tokio/tests/uds_stream.rs b/tokio/tests/uds_stream.rs index 626a96fa31e..c13fb6f67d6 100644 --- a/tokio/tests/uds_stream.rs +++ b/tokio/tests/uds_stream.rs @@ -101,7 +101,7 @@ async fn try_read_write() -> std::io::Result<()> { Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => { break; } - Err(e) => panic!("error = {:?}", e), + Err(e) => panic!("error = {e:?}"), } } @@ -120,7 +120,7 @@ async fn try_read_write() -> std::io::Result<()> { match server.try_read(&mut read[i..]) { Ok(n) => i += n, Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => continue, - Err(e) => panic!("error = {:?}", e), + Err(e) => panic!("error = {e:?}"), } } @@ -142,7 +142,7 @@ async fn try_read_write() -> std::io::Result<()> { Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => { break; } - Err(e) => panic!("error = {:?}", e), + Err(e) => panic!("error = {e:?}"), } } @@ -165,7 +165,7 @@ async fn try_read_write() -> std::io::Result<()> { match server.try_read_vectored(&mut bufs) { Ok(n) => i += n, Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => continue, - Err(e) => panic!("error = {:?}", e), + Err(e) => panic!("error = {e:?}"), } } @@ -338,7 +338,7 @@ async fn try_read_buf() -> std::io::Result<()> { Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => { break; } - Err(e) => panic!("error = {:?}", e), + Err(e) => panic!("error = {e:?}"), } } @@ -357,7 +357,7 @@ async fn try_read_buf() -> std::io::Result<()> { match server.try_read_buf(&mut read) { Ok(n) => i += n, Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => continue, - Err(e) => panic!("error = {:?}", e), + Err(e) => panic!("error = {e:?}"), } }