Skip to content

Commit 2d95850

Browse files
committed
chore: manual inline formatting
Minor manual cleanup - inlined many format args. This makes the code a bit more readable, and helps spot a few inefficiencies and possible bugs. Note that `&foo` in a `format!` parameter results in a 6% extra performance cost, and does not get inlined by the compiler (yet).
1 parent 9cb4348 commit 2d95850

File tree

74 files changed

+226
-319
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

74 files changed

+226
-319
lines changed

src/bin/uudoc.rs

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ fn main() -> io::Result<()> {
6464
for platform in ["unix", "macos", "windows", "unix_android"] {
6565
let platform_utils: Vec<String> = String::from_utf8(
6666
std::process::Command::new("./util/show-utils.sh")
67-
.arg(format!("--features=feat_os_{}", platform))
67+
.arg(format!("--features=feat_os_{platform}"))
6868
.output()?
6969
.stdout,
7070
)
@@ -138,7 +138,7 @@ fn main() -> io::Result<()> {
138138
if name == "[" {
139139
continue;
140140
}
141-
let p = format!("docs/src/utils/{}.md", name);
141+
let p = format!("docs/src/utils/{name}.md");
142142

143143
let markdown = File::open(format!("src/uu/{name}/{name}.md"))
144144
.and_then(|mut f: File| {
@@ -158,11 +158,11 @@ fn main() -> io::Result<()> {
158158
markdown,
159159
}
160160
.markdown()?;
161-
println!("Wrote to '{}'", p);
161+
println!("Wrote to '{p}'");
162162
} else {
163-
println!("Error writing to {}", p);
163+
println!("Error writing to {p}");
164164
}
165-
writeln!(summary, "* [{0}](utils/{0}.md)", name)?;
165+
writeln!(summary, "* [{name}](utils/{name}.md)")?;
166166
}
167167
Ok(())
168168
}
@@ -214,7 +214,7 @@ impl MDWriter<'_, '_> {
214214
.iter()
215215
.any(|u| u == self.name)
216216
{
217-
writeln!(self.w, "<i class=\"fa fa-brands fa-{}\"></i>", icon)?;
217+
writeln!(self.w, "<i class=\"fa fa-brands fa-{icon}\"></i>")?;
218218
}
219219
}
220220
writeln!(self.w, "</div>")?;
@@ -242,7 +242,7 @@ impl MDWriter<'_, '_> {
242242
let usage = usage.replace("{}", self.name);
243243

244244
writeln!(self.w, "\n```")?;
245-
writeln!(self.w, "{}", usage)?;
245+
writeln!(self.w, "{usage}")?;
246246
writeln!(self.w, "```")
247247
} else {
248248
Ok(())
@@ -293,14 +293,14 @@ impl MDWriter<'_, '_> {
293293
writeln!(self.w)?;
294294
for line in content.lines().skip_while(|l| !l.starts_with('-')) {
295295
if let Some(l) = line.strip_prefix("- ") {
296-
writeln!(self.w, "{}", l)?;
296+
writeln!(self.w, "{l}")?;
297297
} else if line.starts_with('`') {
298298
writeln!(self.w, "```shell\n{}\n```", line.trim_matches('`'))?;
299299
} else if line.is_empty() {
300300
writeln!(self.w)?;
301301
} else {
302302
println!("Not sure what to do with this line:");
303-
println!("{}", line);
303+
println!("{line}");
304304
}
305305
}
306306
writeln!(self.w)?;
@@ -332,14 +332,14 @@ impl MDWriter<'_, '_> {
332332
write!(self.w, ", ")?;
333333
}
334334
write!(self.w, "<code>")?;
335-
write!(self.w, "--{}", l)?;
335+
write!(self.w, "--{l}")?;
336336
if let Some(names) = arg.get_value_names() {
337337
write!(
338338
self.w,
339339
"={}",
340340
names
341341
.iter()
342-
.map(|x| format!("&lt;{}&gt;", x))
342+
.map(|x| format!("&lt;{x}&gt;"))
343343
.collect::<Vec<_>>()
344344
.join(" ")
345345
)?;
@@ -353,14 +353,14 @@ impl MDWriter<'_, '_> {
353353
write!(self.w, ", ")?;
354354
}
355355
write!(self.w, "<code>")?;
356-
write!(self.w, "-{}", s)?;
356+
write!(self.w, "-{s}")?;
357357
if let Some(names) = arg.get_value_names() {
358358
write!(
359359
self.w,
360360
" {}",
361361
names
362362
.iter()
363-
.map(|x| format!("&lt;{}&gt;", x))
363+
.map(|x| format!("&lt;{x}&gt;"))
364364
.collect::<Vec<_>>()
365365
.join(" ")
366366
)?;

src/uu/basename/src/basename.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
6868
//
6969

7070
for path in name_args {
71-
print!("{}{}", basename(path, &suffix), line_ending);
71+
print!("{}{line_ending}", basename(path, &suffix));
7272
}
7373

7474
Ok(())

src/uu/cat/src/cat.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ enum CatError {
101101
#[error("{0}")]
102102
Nix(#[from] nix::Error),
103103
/// Unknown file type; it's not a regular file, socket, etc.
104-
#[error("unknown filetype: {}", ft_debug)]
104+
#[error("unknown filetype: {ft_debug}")]
105105
UnknownFiletype {
106106
/// A debug print of the file type
107107
ft_debug: String,
@@ -457,7 +457,7 @@ fn cat_files(files: &[String], options: &OutputOptions) -> UResult<()> {
457457

458458
for path in files {
459459
if let Err(err) = cat_path(path, options, &mut state, out_info.as_ref()) {
460-
error_messages.push(format!("{}: {}", path.maybe_quote(), err));
460+
error_messages.push(format!("{}: {err}", path.maybe_quote()));
461461
}
462462
}
463463
if state.skipped_carriage_return {

src/uu/chmod/src/chmod.rs

Lines changed: 6 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
106106
Err(err) => {
107107
return Err(USimpleError::new(
108108
1,
109-
format!("cannot stat attributes of {}: {}", fref.quote(), err),
109+
format!("cannot stat attributes of {}: {err}", fref.quote()),
110110
));
111111
}
112112
},
@@ -373,7 +373,7 @@ impl Chmoder {
373373
format!("{}: Permission denied", file.quote()),
374374
));
375375
} else {
376-
return Err(USimpleError::new(1, format!("{}: {}", file.quote(), err)));
376+
return Err(USimpleError::new(1, format!("{}: {err}", file.quote())));
377377
}
378378
}
379379
};
@@ -441,36 +441,31 @@ impl Chmoder {
441441
if fperm == mode {
442442
if self.verbose && !self.changes {
443443
println!(
444-
"mode of {} retained as {:04o} ({})",
444+
"mode of {} retained as {fperm:04o} ({})",
445445
file.quote(),
446-
fperm,
447446
display_permissions_unix(fperm as mode_t, false),
448447
);
449448
}
450449
Ok(())
451450
} else if let Err(err) = fs::set_permissions(file, fs::Permissions::from_mode(mode)) {
452451
if !self.quiet {
453-
show_error!("{}", err);
452+
show_error!("{err}");
454453
}
455454
if self.verbose {
456455
println!(
457-
"failed to change mode of file {} from {:04o} ({}) to {:04o} ({})",
456+
"failed to change mode of file {} from {fperm:04o} ({}) to {mode:04o} ({})",
458457
file.quote(),
459-
fperm,
460458
display_permissions_unix(fperm as mode_t, false),
461-
mode,
462459
display_permissions_unix(mode as mode_t, false)
463460
);
464461
}
465462
Err(1)
466463
} else {
467464
if self.verbose || self.changes {
468465
println!(
469-
"mode of {} changed from {:04o} ({}) to {:04o} ({})",
466+
"mode of {} changed from {fperm:04o} ({}) to {mode:04o} ({})",
470467
file.quote(),
471-
fperm,
472468
display_permissions_unix(fperm as mode_t, false),
473-
mode,
474469
display_permissions_unix(mode as mode_t, false)
475470
);
476471
}

src/uu/cp/src/copydir.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -485,7 +485,7 @@ pub(crate) fn copy_directory(
485485
}
486486

487487
// Print an error message, but continue traversing the directory.
488-
Err(e) => show_error!("{}", e),
488+
Err(e) => show_error!("{e}"),
489489
}
490490
}
491491

src/uu/cp/src/cp.rs

Lines changed: 11 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -53,19 +53,19 @@ quick_error! {
5353
#[derive(Debug)]
5454
pub enum Error {
5555
/// Simple io::Error wrapper
56-
IoErr(err: io::Error) { from() source(err) display("{}", err)}
56+
IoErr(err: io::Error) { from() source(err) display("{err}")}
5757

5858
/// Wrapper for io::Error with path context
5959
IoErrContext(err: io::Error, path: String) {
60-
display("{}: {}", path, err)
60+
display("{path}: {err}")
6161
context(path: &'a str, err: io::Error) -> (err, path.to_owned())
6262
context(context: String, err: io::Error) -> (err, context)
6363
source(err)
6464
}
6565

6666
/// General copy error
6767
Error(err: String) {
68-
display("{}", err)
68+
display("{err}")
6969
from(err: String) -> (err)
7070
from(err: &'static str) -> (err.to_string())
7171
}
@@ -75,7 +75,7 @@ quick_error! {
7575
NotAllFilesCopied {}
7676

7777
/// Simple walkdir::Error wrapper
78-
WalkDirErr(err: walkdir::Error) { from() display("{}", err) source(err) }
78+
WalkDirErr(err: walkdir::Error) { from() display("{err}") source(err) }
7979

8080
/// Simple std::path::StripPrefixError wrapper
8181
StripPrefixError(err: StripPrefixError) { from() }
@@ -87,15 +87,15 @@ quick_error! {
8787
Skipped(exit_with_error:bool) { }
8888

8989
/// Result of a skipped file
90-
InvalidArgument(description: String) { display("{}", description) }
90+
InvalidArgument(description: String) { display("{description}") }
9191

9292
/// All standard options are included as an an implementation
9393
/// path, but those that are not implemented yet should return
9494
/// a NotImplemented error.
95-
NotImplemented(opt: String) { display("Option '{}' not yet implemented.", opt) }
95+
NotImplemented(opt: String) { display("Option '{opt}' not yet implemented.") }
9696

9797
/// Invalid arguments to backup
98-
Backup(description: String) { display("{}\nTry '{} --help' for more information.", description, uucore::execution_phrase()) }
98+
Backup(description: String) { display("{description}\nTry '{} --help' for more information.", uucore::execution_phrase()) }
9999

100100
NotADirectory(path: PathBuf) { display("'{}' is not a directory", path.display()) }
101101
}
@@ -791,7 +791,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
791791
// code should still be EXIT_ERR as does GNU cp
792792
Error::NotAllFilesCopied => {}
793793
// Else we caught a fatal bubbled-up error, log it to stderr
794-
_ => show_error!("{}", error),
794+
_ => show_error!("{error}"),
795795
};
796796
set_exit_code(EXIT_ERR);
797797
}
@@ -1283,7 +1283,7 @@ fn show_error_if_needed(error: &Error) {
12831283
// should return an error from GNU 9.2
12841284
}
12851285
_ => {
1286-
show_error!("{}", error);
1286+
show_error!("{error}");
12871287
}
12881288
}
12891289
}
@@ -1686,18 +1686,13 @@ pub(crate) fn copy_attributes(
16861686
handle_preserve(&attributes.context, || -> CopyResult<()> {
16871687
let context = selinux::SecurityContext::of_path(source, false, false).map_err(|e| {
16881688
format!(
1689-
"failed to get security context of {}: {}",
1689+
"failed to get security context of {}: {e}",
16901690
source.display(),
1691-
e
16921691
)
16931692
})?;
16941693
if let Some(context) = context {
16951694
context.set_for_path(dest, false, false).map_err(|e| {
1696-
format!(
1697-
"failed to set security context for {}: {}",
1698-
dest.display(),
1699-
e
1700-
)
1695+
format!("failed to set security context for {}: {e}", dest.display(),)
17011696
})?;
17021697
}
17031698

src/uu/csplit/src/patterns.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,9 +30,9 @@ impl std::fmt::Display for Pattern {
3030
match self {
3131
Self::UpToLine(n, _) => write!(f, "{n}"),
3232
Self::UpToMatch(regex, 0, _) => write!(f, "/{}/", regex.as_str()),
33-
Self::UpToMatch(regex, offset, _) => write!(f, "/{}/{:+}", regex.as_str(), offset),
33+
Self::UpToMatch(regex, offset, _) => write!(f, "/{}/{offset:+}", regex.as_str()),
3434
Self::SkipToMatch(regex, 0, _) => write!(f, "%{}%", regex.as_str()),
35-
Self::SkipToMatch(regex, offset, _) => write!(f, "%{}%{:+}", regex.as_str(), offset),
35+
Self::SkipToMatch(regex, offset, _) => write!(f, "%{}%{offset:+}", regex.as_str()),
3636
}
3737
}
3838
}
@@ -168,7 +168,7 @@ fn validate_line_numbers(patterns: &[Pattern]) -> Result<(), CsplitError> {
168168
(_, 0) => Err(CsplitError::LineNumberIsZero),
169169
// two consecutive numbers should not be equal
170170
(n, m) if n == m => {
171-
show_warning!("line number '{}' is the same as preceding line number", n);
171+
show_warning!("line number '{n}' is the same as preceding line number");
172172
Ok(n)
173173
}
174174
// a number cannot be greater than the one that follows

src/uu/dd/src/numbers.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ pub(crate) fn to_magnitude_and_suffix(n: u128, suffix_type: SuffixType) -> Strin
8383
if quotient < 10.0 {
8484
format!("{quotient:.1} {suffix}")
8585
} else {
86-
format!("{} {}", quotient.round(), suffix)
86+
format!("{} {suffix}", quotient.round())
8787
}
8888
}
8989

src/uu/dd/src/parseargs/unit_tests.rs

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -29,29 +29,28 @@ fn unimplemented_flags_should_error_non_linux() {
2929
"noctty",
3030
"nofollow",
3131
] {
32-
let args = vec![format!("iflag={}", flag)];
32+
let args = vec![format!("iflag={flag}")];
3333

3434
if Parser::new()
3535
.parse(&args.iter().map(AsRef::as_ref).collect::<Vec<_>>()[..])
3636
.is_ok()
3737
{
38-
succeeded.push(format!("iflag={}", flag));
38+
succeeded.push(format!("iflag={flag}"));
3939
}
4040

41-
let args = vec![format!("oflag={}", flag)];
41+
let args = vec![format!("oflag={flag}")];
4242

4343
if Parser::new()
4444
.parse(&args.iter().map(AsRef::as_ref).collect::<Vec<_>>()[..])
4545
.is_ok()
4646
{
47-
succeeded.push(format!("iflag={}", flag));
47+
succeeded.push(format!("iflag={flag}"));
4848
}
4949
}
5050

5151
assert!(
5252
succeeded.is_empty(),
53-
"The following flags did not panic as expected: {:?}",
54-
succeeded
53+
"The following flags did not panic as expected: {succeeded:?}",
5554
);
5655
}
5756

src/uu/df/src/blocks.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -98,9 +98,9 @@ pub(crate) fn to_magnitude_and_suffix(n: u128, suffix_type: SuffixType) -> Strin
9898
if rem % (bases[i] / 10) == 0 {
9999
format!("{quot}.{tenths_place}{suffix}")
100100
} else if tenths_place + 1 == 10 || quot >= 10 {
101-
format!("{}{}", quot + 1, suffix)
101+
format!("{}{suffix}", quot + 1)
102102
} else {
103-
format!("{}.{}{}", quot, tenths_place + 1, suffix)
103+
format!("{quot}.{}{suffix}", tenths_place + 1)
104104
}
105105
}
106106
}

0 commit comments

Comments
 (0)