tokio: avoid positional fmt params when possible (#6978)

This commit is contained in:
Hamir Mahal 2024-11-18 04:50:58 -08:00 committed by GitHub
parent 2f899144ed
commit d4178cf349
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
55 changed files with 156 additions and 237 deletions

View File

@ -37,7 +37,7 @@ fn create_medium<const SIZE: usize>(g: &mut BenchmarkGroup<WallTime>) {
fn send_data<T: Default, const SIZE: usize>(g: &mut BenchmarkGroup<WallTime>, 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::<T>(SIZE);

View File

@ -193,7 +193,7 @@ 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;
}
@ -210,7 +210,7 @@ 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;
}
@ -234,7 +234,7 @@ 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;
}

View File

@ -77,7 +77,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)
}
})

View File

@ -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

View File

@ -40,7 +40,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
// 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.

View File

@ -75,7 +75,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
// 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<dyn std::error::Error>> {
// 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");

View File

@ -38,8 +38,8 @@ async fn main() -> Result<(), Box<dyn Error>> {
.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,7 +50,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
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

View File

@ -90,7 +90,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
.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<dyn Error>> {
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<dyn Error>> {
// 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<Database>) -> Response {
value: value.clone(),
},
None => Response::Error {
msg: format!("no key {}", key),
msg: format!("no key {key}"),
},
},
Request::Set { key, value } => {
@ -203,7 +203,7 @@ impl Request {
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 +212,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}"),
}
}
}

View File

@ -31,13 +31,13 @@ async fn main() -> Result<(), Box<dyn Error>> {
.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}");
}
});
}
@ -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)
})?;

View File

@ -46,7 +46,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
// 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!"),
}

View File

@ -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<usize, syn::Error
Ok(value) => 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<String, syn::E
syn::Lit::Verbatim(s) => 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<Path, syn::Error
}
_ => 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<bool, syn::Erro
syn::Lit::Bool(b) => 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));
}
@ -358,21 +357,19 @@ fn build_config(
let msg = match name.as_str() {
"threaded_scheduler" | "multi_thread" => {
format!(
"Set the runtime flavor with #[{}(flavor = \"multi_thread\")].",
macro_name
"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));

View File

@ -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::<Vec<_>>();
// Use a bitfield to track which futures completed

View File

@ -161,8 +161,7 @@ impl<T: Unpin> Drop for StreamMock<T> {
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"
);
}
}

View File

@ -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"),
}

View File

@ -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}"),
}
}
}

View File

@ -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}"),
}
}
}

View File

@ -249,7 +249,7 @@ impl LocalPool {
// 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}");
}
}
}

View File

@ -665,7 +665,7 @@ impl<T> DelayQueue<T> {
// 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:?}"),
}
}

View File

@ -280,13 +280,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 +289,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 +297,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 +306,7 @@ mod test {
assert_eq!(
level,
level_for(0, a as u64),
"level_for({}) -- binary = {:b}",
a,
a
"level_for({a}) -- binary = {a:b}"
);
}
}

View File

@ -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);

View File

@ -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:?}"),
}
}

View File

@ -42,7 +42,7 @@ async fn correct_behavior_on_errors() {
let mut had_error = false;
loop {
let item = stream.next().await.unwrap();
println!("{:?}", item);
println!("{item:?}");
match item {
Ok(bytes) => {
let bytes = &*bytes;

View File

@ -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))
}

View File

@ -111,7 +111,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;
@ -328,7 +328,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:?}"),
}
}

View File

@ -129,7 +129,7 @@ impl<T> Future for JoinHandle<T> {
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,
}
}

View File

@ -95,22 +95,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:?}")
}
}
}

View File

@ -322,7 +322,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}")
}
}
}

View File

@ -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

View File

@ -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}"),
}
}

View File

@ -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}"),
}
}

View File

@ -264,9 +264,7 @@ impl<T> Local<T> {
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<T> Steal<T> {
assert!(
n <= LOCAL_QUEUE_CAPACITY as UnsignedShort / 2,
"actual = {}",
n
"actual = {n}"
);
let (first, _) = unpack(next_packed);

View File

@ -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}"),
}
}

View File

@ -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}"
);
}
}

View File

@ -76,7 +76,7 @@ impl<S: Storage> Registry<S> {
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()
}

View File

@ -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}"),
));
}

View File

@ -255,7 +255,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}"),
}
}
}
@ -291,7 +291,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}"),
}
}
}

View File

@ -274,8 +274,7 @@ impl<T: ?Sized> RwLock<T> {
{
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"))]

View File

@ -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}")
}
}

View File

@ -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}"),
}
}
}

View File

@ -211,7 +211,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:"
);
}

View File

@ -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}"
);
}

View File

@ -141,7 +141,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,
}
}

View File

@ -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");

View File

@ -20,7 +20,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())

View File

@ -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: <locked> }"#)
assert_eq!(format!("{m:?}"), r#"Mutex { data: <locked> }"#)
}

View File

@ -133,5 +133,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));
}

View File

@ -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:?}"
);
});
}

View File

@ -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:?}"
);
}

View File

@ -254,7 +254,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;
@ -294,7 +294,7 @@ async fn try_join_next() {
Some(Ok(())) => {
count += 1;
}
Some(Err(err)) => panic!("failed: {}", err),
Some(Err(err)) => panic!("failed: {err}"),
None => {
break;
}

View File

@ -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.

View File

@ -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();

View File

@ -65,7 +65,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:?}"),
}
}
@ -84,7 +84,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:?}"),
}
}
@ -106,7 +106,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:?}"),
}
}
@ -129,7 +129,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:?}"),
}
}
@ -321,7 +321,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:?}"),
}
}
@ -340,7 +340,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:?}"),
}
}

View File

@ -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:?}"),
}
}
}

View File

@ -88,7 +88,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) => {
@ -206,7 +206,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:?}"),
}
}
@ -223,7 +223,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:?}"),
}
}
}
@ -253,7 +253,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:?}"),
}
}
@ -270,7 +270,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:?}"),
}
}
}
@ -317,7 +317,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) => {
@ -388,7 +388,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:?}"),
}
}
@ -405,7 +405,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:?}"),
}
}
}

View File

@ -106,7 +106,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:?}"),
}
}
@ -125,7 +125,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:?}"),
}
}
@ -147,7 +147,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:?}"),
}
}
@ -170,7 +170,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:?}"),
}
}
@ -343,7 +343,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:?}"),
}
}
@ -362,7 +362,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:?}"),
}
}