Skip to content

Commit c23e18f

Browse files
committed
rust: Inline format args
A minor Rust cleanup to inline `format!("{}", foo)` and similar macro calls into `format!("{foo}")`. While mostly cosmetic, this change makes it a bit easier to read format argument strings, shortens code, and makes it easier to see cases with double-referencing values causing minor performance (apparently `&foo` in a format! causes about 6% perf cost due to Rust compiler being unable to inline it due to dynamic invocation.
1 parent 18b7491 commit c23e18f

File tree

11 files changed

+34
-47
lines changed

11 files changed

+34
-47
lines changed

drivers/gpio/gpio_pl061_rust.rs

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -143,8 +143,7 @@ impl irq::Chip for PL061Device {
143143
{
144144
dev_err!(
145145
data.dev,
146-
"trying to configure line {} for both level and edge detection, choose one!\n",
147-
offset
146+
"trying to configure line {offset} for both level and edge detection, choose one!\n",
148147
);
149148
return Err(EINVAL);
150149
}
@@ -172,8 +171,7 @@ impl irq::Chip for PL061Device {
172171
irq_data.set_level_handler();
173172
dev_dbg!(
174173
data.dev,
175-
"line {}: IRQ on {} level\n",
176-
offset,
174+
"line {offset}: IRQ on {} level\n",
177175
if polarity { "HIGH" } else { "LOW" }
178176
);
179177
} else if (trigger & irq::Type::EDGE_BOTH) == irq::Type::EDGE_BOTH {
@@ -182,7 +180,7 @@ impl irq::Chip for PL061Device {
182180
// Select both edges, settings this makes GPIOEV be ignored.
183181
gpioibe |= bit;
184182
irq_data.set_edge_handler();
185-
dev_dbg!(data.dev, "line {}: IRQ on both edges\n", offset);
183+
dev_dbg!(data.dev, "line {offset}: IRQ on both edges\n");
186184
} else if trigger & (irq::Type::EDGE_RISING | irq::Type::EDGE_FALLING) != 0 {
187185
let rising = trigger & irq::Type::EDGE_RISING != 0;
188186

@@ -199,8 +197,7 @@ impl irq::Chip for PL061Device {
199197
irq_data.set_edge_handler();
200198
dev_dbg!(
201199
data.dev,
202-
"line {}: IRQ on {} edge\n",
203-
offset,
200+
"line {offset}: IRQ on {} edge\n",
204201
if rising { "RISING" } else { "FALLING}" }
205202
);
206203
} else {
@@ -209,7 +206,7 @@ impl irq::Chip for PL061Device {
209206
gpioibe &= !bit;
210207
gpioiev &= !bit;
211208
irq_data.set_bad_handler();
212-
dev_warn!(data.dev, "no trigger selected for line {}\n", offset);
209+
dev_warn!(data.dev, "no trigger selected for line {offset}\n");
213210
}
214211

215212
pl061.base.writeb(gpiois, GPIOIS);

rust/build_error.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,5 +27,7 @@
2727
#[export_name = "rust_build_error"]
2828
#[track_caller]
2929
pub const fn build_error(msg: &'static str) -> ! {
30+
// This uses const context expansion panic! special case:
31+
// https://github.com/rust-lang/rust/issues/108595
3032
panic!("{}", msg);
3133
}

rust/kernel/error.rs

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -192,10 +192,7 @@ impl Error {
192192
pub(crate) fn from_kernel_errno(errno: core::ffi::c_int) -> Error {
193193
if errno < -(bindings::MAX_ERRNO as i32) || errno >= 0 {
194194
// TODO: Make it a `WARN_ONCE` once available.
195-
crate::pr_warn!(
196-
"attempted to create `Error` with out of range `errno`: {}",
197-
errno
198-
);
195+
crate::pr_warn!("attempted to create `Error` with out of range `errno`: {errno}");
199196
return code::EINVAL;
200197
}
201198

rust/kernel/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -254,7 +254,7 @@ macro_rules! container_of {
254254
#[cfg(not(any(testlib, test)))]
255255
#[panic_handler]
256256
fn panic(info: &core::panic::PanicInfo<'_>) -> ! {
257-
pr_emerg!("{}\n", info);
257+
pr_emerg!("{info}\n");
258258
// SAFETY: FFI call.
259259
unsafe { bindings::BUG() };
260260
// Bindgen currently does not recognize `__noreturn` so `BUG` returns `()`

rust/kernel/module_param.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -399,7 +399,7 @@ impl<T: Copy, const N: usize> ArrayParam<T, { N }> {
399399
impl<T: core::fmt::Display, const N: usize> core::fmt::Display for ArrayParam<T, { N }> {
400400
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
401401
for val in self.values() {
402-
write!(f, "{},", val)?;
402+
write!(f, "{val},")?;
403403
}
404404
Ok(())
405405
}
@@ -462,8 +462,8 @@ impl core::fmt::Display for StringParam {
462462
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
463463
let bytes = self.bytes();
464464
match core::str::from_utf8(bytes) {
465-
Ok(utf8) => write!(f, "{}", utf8),
466-
Err(_) => write!(f, "{:?}", bytes),
465+
Ok(utf8) => write!(f, "{utf8}"),
466+
Err(_) => write!(f, "{bytes:?}"),
467467
}
468468
}
469469
}

rust/kernel/str.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -209,11 +209,11 @@ impl fmt::Display for CStr {
209209
/// # use kernel::str::CStr;
210210
/// # use kernel::str::CString;
211211
/// let penguin = c_str!("🐧");
212-
/// let s = CString::try_from_fmt(fmt!("{}", penguin)).unwrap();
212+
/// let s = CString::try_from_fmt(fmt!("{penguin}")).unwrap();
213213
/// assert_eq!(s.as_bytes_with_nul(), "\\xf0\\x9f\\x90\\xa7\0".as_bytes());
214214
///
215215
/// let ascii = c_str!("so \"cool\"");
216-
/// let s = CString::try_from_fmt(fmt!("{}", ascii)).unwrap();
216+
/// let s = CString::try_from_fmt(fmt!("{ascii}")).unwrap();
217217
/// assert_eq!(s.as_bytes_with_nul(), "so \"cool\"\0".as_bytes());
218218
/// ```
219219
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
@@ -222,7 +222,7 @@ impl fmt::Display for CStr {
222222
// Printable character.
223223
f.write_char(c as char)?;
224224
} else {
225-
write!(f, "\\x{:02x}", c)?;
225+
write!(f, "\\x{c:02x}")?;
226226
}
227227
}
228228
Ok(())
@@ -237,12 +237,12 @@ impl fmt::Debug for CStr {
237237
/// # use kernel::str::CStr;
238238
/// # use kernel::str::CString;
239239
/// let penguin = c_str!("🐧");
240-
/// let s = CString::try_from_fmt(fmt!("{:?}", penguin)).unwrap();
240+
/// let s = CString::try_from_fmt(fmt!("{penguin:?}")).unwrap();
241241
/// assert_eq!(s.as_bytes_with_nul(), "\"\\xf0\\x9f\\x90\\xa7\"\0".as_bytes());
242242
///
243243
/// // Embedded double quotes are escaped.
244244
/// let ascii = c_str!("so \"cool\"");
245-
/// let s = CString::try_from_fmt(fmt!("{:?}", ascii)).unwrap();
245+
/// let s = CString::try_from_fmt(fmt!("{ascii:?}")).unwrap();
246246
/// assert_eq!(s.as_bytes_with_nul(), "\"so \\\"cool\\\"\"\0".as_bytes());
247247
/// ```
248248
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
@@ -252,7 +252,7 @@ impl fmt::Debug for CStr {
252252
// Printable characters.
253253
b'\"' => f.write_str("\\\"")?,
254254
0x20..=0x7e => f.write_char(c as char)?,
255-
_ => write!(f, "\\x{:02x}", c)?,
255+
_ => write!(f, "\\x{c:02x}")?,
256256
}
257257
}
258258
f.write_str("\"")

rust/kernel/types.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -450,7 +450,7 @@ define_unsigned_number_traits!(usize);
450450
///
451451
/// fn print_bits(x: usize) {
452452
/// for bit in bits_iter(x) {
453-
/// pr_info!("{}\n", bit);
453+
/// pr_info!("{bit}\n");
454454
/// }
455455
/// }
456456
///

rust/kernel/workqueue.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,7 @@ macro_rules! init_work_item_adapter {
140140
///
141141
/// kernel::impl_self_work_adapter!(Example, work, |w| {
142142
/// let count = w.count.fetch_add(1, Ordering::Relaxed);
143-
/// pr_info!("Called with count={}\n", count);
143+
/// pr_info!("Called with count={count}\n");
144144
///
145145
/// // Queue again if the count is less than 10.
146146
/// if count < 10 {

rust/macros/module.rs

Lines changed: 7 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,7 @@ fn param_ops_path(param_type: &str) -> &'static str {
139139
"isize" => "kernel::module_param::PARAM_OPS_ISIZE",
140140
"usize" => "kernel::module_param::PARAM_OPS_USIZE",
141141
"str" => "kernel::module_param::PARAM_OPS_STR",
142-
t => panic!("Unrecognized type {}", t),
142+
t => panic!("Unrecognized type {t}"),
143143
}
144144
}
145145

@@ -151,7 +151,7 @@ fn try_simple_param_val(
151151
"bool" => Box::new(try_ident),
152152
"str" => Box::new(|param_it| {
153153
try_byte_string(param_it)
154-
.map(|s| format!("kernel::module_param::StringParam::Ref(b\"{}\")", s))
154+
.map(|s| format!("kernel::module_param::StringParam::Ref(b\"{s}\")"))
155155
}),
156156
_ => Box::new(try_literal),
157157
}
@@ -247,10 +247,7 @@ impl ModuleInfo {
247247
};
248248

249249
if seen_keys.contains(&key) {
250-
panic!(
251-
"Duplicated key \"{}\". Keys can only be specified once.",
252-
key
253-
);
250+
panic!("Duplicated key \"{key}\". Keys can only be specified once.");
254251
}
255252

256253
assert_eq!(expect_punct(it), ':');
@@ -266,10 +263,7 @@ impl ModuleInfo {
266263
info.alias = Some(format!("rtnl-link-{}", expect_string_ascii(it)))
267264
}
268265
"params" => info.params = Some(expect_group(it)),
269-
_ => panic!(
270-
"Unknown key \"{}\". Valid keys are: {:?}.",
271-
key, EXPECTED_KEYS
272-
),
266+
_ => panic!("Unknown key \"{key}\". Valid keys are: {EXPECTED_KEYS:?}."),
273267
}
274268

275269
assert_eq!(expect_punct(it), ',');
@@ -281,7 +275,7 @@ impl ModuleInfo {
281275

282276
for key in REQUIRED_KEYS {
283277
if !seen_keys.iter().any(|e| e == key) {
284-
panic!("Missing required key \"{}\".", key);
278+
panic!("Missing required key \"{key}\".");
285279
}
286280
}
287281

@@ -293,10 +287,7 @@ impl ModuleInfo {
293287
}
294288

295289
if seen_keys != ordered_keys {
296-
panic!(
297-
"Keys are not ordered as expected. Order them like: {:?}.",
298-
ordered_keys
299-
);
290+
panic!("Keys are not ordered as expected. Order them like: {ordered_keys:?}.");
300291
}
301292

302293
info
@@ -364,7 +355,7 @@ pub(crate) fn module(ts: TokenStream) -> TokenStream {
364355
} => {
365356
array_types_to_generate.push((vals.clone(), max_length));
366357
(
367-
format!("__rust_array_param_{}_{}", vals, max_length),
358+
format!("__rust_array_param_{vals}_{max_length}"),
368359
generated_array_ops_name(vals, max_length),
369360
)
370361
}

samples/rust/hostprogs/a.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,5 +3,5 @@
33
//! Rust single host program sample: module `a`.
44
55
pub(crate) fn f(x: i32) {
6-
println!("The number is {}.", x);
6+
println!("The number is {x}.");
77
}

scripts/generate_rust_target.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -30,14 +30,14 @@ type Object = Vec<(String, Value)>;
3030
impl Display for Value {
3131
fn fmt(&self, formatter: &mut Formatter<'_>) -> Result {
3232
match self {
33-
Value::Boolean(boolean) => write!(formatter, "{}", boolean),
34-
Value::Number(number) => write!(formatter, "{}", number),
35-
Value::String(string) => write!(formatter, "\"{}\"", string),
33+
Value::Boolean(boolean) => write!(formatter, "{boolean}"),
34+
Value::Number(number) => write!(formatter, "{number}"),
35+
Value::String(string) => write!(formatter, "\"{string}\""),
3636
Value::Object(object) => {
3737
formatter.write_str("{")?;
3838
if let [ref rest @ .., ref last] = object[..] {
3939
for (key, value) in rest {
40-
write!(formatter, "\"{}\": {},", key, value)?;
40+
write!(formatter, "\"{key}\": {value},")?;
4141
}
4242
write!(formatter, "\"{}\": {}", last.0, last.1)?;
4343
}
@@ -95,7 +95,7 @@ impl Display for TargetSpec {
9595
formatter.write_str("{\n")?;
9696
if let [ref rest @ .., ref last] = self.0[..] {
9797
for (key, value) in rest {
98-
write!(formatter, " \"{}\": {},\n", key, value)?;
98+
write!(formatter, " \"{key}\": {value},\n")?;
9999
}
100100
write!(formatter, " \"{}\": {}\n", last.0, last.1)?;
101101
}
@@ -228,5 +228,5 @@ fn main() {
228228
ts.push("target-endian", "big");
229229
}
230230

231-
println!("{}", ts);
231+
println!("{ts}");
232232
}

0 commit comments

Comments
 (0)