inline format arguments

In a few cases, removed the unneeded `&` - this causes a minor slowdown because compiler cannot eliminate those (yet).
This commit is contained in:
Yuri Astrakhan 2025-02-27 00:30:05 -05:00
parent 4998f58847
commit bc99136f14
14 changed files with 32 additions and 44 deletions

View File

@ -1,5 +1,5 @@
// Output the square of a number. // Output the square of a number.
fn print_square(num: f64) { fn print_square(num: f64) {
let result = f64::powf(num, 2.0); let result = f64::powf(num, 2.0);
println!("The square of {:.2} is {:.2}.", num, result); println!("The square of {num:.2} is {result:.2}.");
} }

View File

@ -191,11 +191,11 @@ impl HighlightingAssets {
Some(theme) => theme, Some(theme) => theme,
None => { None => {
if theme == "ansi-light" || theme == "ansi-dark" { if theme == "ansi-light" || theme == "ansi-dark" {
bat_warning!("Theme '{}' is deprecated, using 'ansi' instead.", theme); bat_warning!("Theme '{theme}' is deprecated, using 'ansi' instead.");
return self.get_theme("ansi"); return self.get_theme("ansi");
} }
if !theme.is_empty() { if !theme.is_empty() {
bat_warning!("Unknown theme '{}', using default.", theme) bat_warning!("Unknown theme '{theme}', using default.")
} }
self.get_theme_set() self.get_theme_set()
.get( .get(
@ -343,8 +343,7 @@ fn asset_from_cache<T: serde::de::DeserializeOwned>(
) -> Result<T> { ) -> Result<T> {
let contents = fs::read(path).map_err(|_| { let contents = fs::read(path).map_err(|_| {
format!( format!(
"Could not load cached {} '{}'", "Could not load cached {description} '{}'",
description,
path.to_string_lossy() path.to_string_lossy()
) )
})?; })?;

View File

@ -47,9 +47,8 @@ fn build_theme_set(source_dir: &Path, include_integrated_assets: bool) -> Result
let res = theme_set.add_from_folder(&theme_dir); let res = theme_set.add_from_folder(&theme_dir);
if let Err(err) = res { if let Err(err) = res {
println!( println!(
"Failed to load one or more themes from '{}' (reason: '{}')", "Failed to load one or more themes from '{}' (reason: '{err}')",
theme_dir.to_string_lossy(), theme_dir.to_string_lossy(),
err,
); );
} }
} else { } else {
@ -162,15 +161,10 @@ fn asset_to_cache<T: serde::Serialize>(
description: &str, description: &str,
compressed: bool, compressed: bool,
) -> Result<()> { ) -> Result<()> {
print!("Writing {} to {} ... ", description, path.to_string_lossy()); print!("Writing {description} to {} ... ", path.to_string_lossy());
let contents = asset_to_contents(asset, description, compressed)?; let contents = asset_to_contents(asset, description, compressed)?;
std::fs::write(path, &contents[..]).map_err(|_| { std::fs::write(path, &contents[..])
format!( .map_err(|_| format!("Could not save {description} to {}", path.to_string_lossy()))?;
"Could not save {} to {}",
description,
path.to_string_lossy()
)
})?;
println!("okay"); println!("okay");
Ok(()) Ok(())
} }

View File

@ -50,7 +50,7 @@ fn clear_asset(path: PathBuf, description: &str) {
println!("skipped (not present)"); println!("skipped (not present)");
} }
Err(err) => { Err(err) => {
println!("could not remove the cache file {:?}: {}", &path, err); println!("could not remove the cache file {path:?}: {err}");
} }
Ok(_) => println!("okay"), Ok(_) => println!("okay"),
} }

View File

@ -16,7 +16,7 @@ static VERSION: Lazy<String> = Lazy::new(|| {
if git_version.is_empty() { if git_version.is_empty() {
crate_version!().to_string() crate_version!().to_string()
} else { } else {
format!("{} ({})", crate_version!(), git_version) format!("{} ({git_version})", crate_version!())
} }
}); });

View File

@ -88,9 +88,8 @@ pub fn generate_config_file() -> bat::error::Result<()> {
fs::write(&config_file, default_config).map_err(|e| { fs::write(&config_file, default_config).map_err(|e| {
format!( format!(
"Failed to create config file at '{}': {}", "Failed to create config file at '{}': {e}",
config_file.to_string_lossy(), config_file.to_string_lossy(),
e
) )
})?; })?;

View File

@ -161,7 +161,7 @@ pub fn get_languages(config: &Config, cache_dir: &Path) -> Result<String> {
}; };
for lang in languages { for lang in languages {
write!(result, "{:width$}{}", lang.name, separator, width = longest).ok(); write!(result, "{:width$}{separator}", lang.name, width = longest).ok();
// Number of characters on this line so far, wrap before `desired_width` // Number of characters on this line so far, wrap before `desired_width`
let mut num_chars = 0; let mut num_chars = 0;
@ -172,7 +172,7 @@ pub fn get_languages(config: &Config, cache_dir: &Path) -> Result<String> {
let new_chars = word.len() + comma_separator.len(); let new_chars = word.len() + comma_separator.len();
if num_chars + new_chars >= desired_width { if num_chars + new_chars >= desired_width {
num_chars = 0; num_chars = 0;
write!(result, "\n{:width$}{}", "", separator, width = longest).ok(); write!(result, "\n{:width$}{separator}", "", width = longest).ok();
} }
num_chars += new_chars; num_chars += new_chars;
@ -222,9 +222,8 @@ pub fn list_themes(
if config.colored_output { if config.colored_output {
writeln!( writeln!(
stdout, stdout,
"Theme: {}{}\n", "Theme: {}{default_theme_info}\n",
Style::new().bold().paint(theme.to_string()), Style::new().bold().paint(theme.to_string()),
default_theme_info
)?; )?;
config.theme = theme.to_string(); config.theme = theme.to_string();
Controller::new(&config, &assets) Controller::new(&config, &assets)
@ -358,7 +357,7 @@ fn run() -> Result<bool> {
"fish" => println!("{}", completions::FISH_COMPLETION), "fish" => println!("{}", completions::FISH_COMPLETION),
"ps1" => println!("{}", completions::PS1_COMPLETION), "ps1" => println!("{}", completions::PS1_COMPLETION),
"zsh" => println!("{}", completions::ZSH_COMPLETION), "zsh" => println!("{}", completions::ZSH_COMPLETION),
_ => unreachable!("No completion for shell '{}' available.", shell), _ => unreachable!("No completion for shell '{shell}' available."),
} }
return Ok(true); return Ok(true);
} }

View File

@ -60,14 +60,13 @@ pub fn default_error_handler(error: &Error, output: &mut dyn Write) {
Error::SerdeYamlError(_) => { Error::SerdeYamlError(_) => {
writeln!( writeln!(
output, output,
"{}: Error while parsing metadata.yaml file: {}", "{}: Error while parsing metadata.yaml file: {error}",
Red.paint("[bat error]"), Red.paint("[bat error]"),
error
) )
.ok(); .ok();
} }
_ => { _ => {
writeln!(output, "{}: {}", Red.paint("[bat error]"), error).ok(); writeln!(output, "{}: {error}", Red.paint("[bat error]")).ok();
} }
}; };
} }

View File

@ -217,14 +217,14 @@ impl<'a> Input<'a> {
metadata: self.metadata, metadata: self.metadata,
reader: { reader: {
let mut file = File::open(&path) let mut file = File::open(&path)
.map_err(|e| format!("'{}': {}", path.to_string_lossy(), e))?; .map_err(|e| format!("'{}': {e}", path.to_string_lossy()))?;
if file.metadata()?.is_dir() { if file.metadata()?.is_dir() {
return Err(format!("'{}' is a directory.", path.to_string_lossy()).into()); return Err(format!("'{}' is a directory.", path.to_string_lossy()).into());
} }
if let Some(stdout) = stdout_identifier { if let Some(stdout) = stdout_identifier {
let input_identifier = Identifier::try_from(file).map_err(|e| { let input_identifier = Identifier::try_from(file).map_err(|e| {
format!("{}: Error identifying file: {}", path.to_string_lossy(), e) format!("{}: Error identifying file: {e}", path.to_string_lossy())
})?; })?;
if stdout.surely_conflicts_with(&input_identifier) { if stdout.surely_conflicts_with(&input_identifier) {
return Err(format!( return Err(format!(

View File

@ -39,7 +39,7 @@ impl LessOpenPreprocessor {
// Note that $LESSCLOSE has no such requirement // Note that $LESSCLOSE has no such requirement
if lessopen.match_indices("%s").count() != 1 { if lessopen.match_indices("%s").count() != 1 {
let error_msg = "LESSOPEN ignored: must contain exactly one %s"; let error_msg = "LESSOPEN ignored: must contain exactly one %s";
bat_warning!("{}", error_msg); bat_warning!("{error_msg}");
return Err(error_msg.into()); return Err(error_msg.into());
} }
@ -110,7 +110,7 @@ impl LessOpenPreprocessor {
if self.preprocess_stdin { if self.preprocess_stdin {
if let Some(stdout) = stdout_identifier { if let Some(stdout) = stdout_identifier {
let input_identifier = Identifier::try_from(clircle::Stdio::Stdin) let input_identifier = Identifier::try_from(clircle::Stdio::Stdin)
.map_err(|e| format!("Stdin: Error identifying file: {}", e))?; .map_err(|e| format!("Stdin: Error identifying file: {e}"))?;
if stdout.surely_conflicts_with(&input_identifier) { if stdout.surely_conflicts_with(&input_identifier) {
return Err("IO circle detected. The input from stdin is also an output. Aborting to avoid infinite loop.".into()); return Err("IO circle detected. The input from stdin is also an output. Aborting to avoid infinite loop.".into());
} }

View File

@ -341,7 +341,7 @@ impl<'a> InteractivePrinter<'a> {
self.print_horizontal_line_term(handle, self.colors.grid)?; self.print_horizontal_line_term(handle, self.colors.grid)?;
} else { } else {
let hline = "".repeat(self.config.term_width - (self.panel_width + 1)); let hline = "".repeat(self.config.term_width - (self.panel_width + 1));
let hline = format!("{}{}{}", "".repeat(self.panel_width), grid_char, hline); let hline = format!("{}{grid_char}{hline}", "".repeat(self.panel_width));
writeln!(handle, "{}", self.colors.grid.paint(hline))?; writeln!(handle, "{}", self.colors.grid.paint(hline))?;
} }
@ -355,8 +355,7 @@ impl<'a> InteractivePrinter<'a> {
let text_truncated: String = text.chars().take(self.panel_width - 1).collect(); let text_truncated: String = text.chars().take(self.panel_width - 1).collect();
let text_filled: String = format!( let text_filled: String = format!(
"{}{}", "{text_truncated}{}",
text_truncated,
" ".repeat(self.panel_width - 1 - text_truncated.len()) " ".repeat(self.panel_width - 1 - text_truncated.len())
); );
if self.config.style_components.grid() { if self.config.style_components.grid() {
@ -521,13 +520,12 @@ impl Printer for InteractivePrinter<'_> {
.try_for_each(|component| match component { .try_for_each(|component| match component {
StyleComponent::HeaderFilename => { StyleComponent::HeaderFilename => {
let header_filename = format!( let header_filename = format!(
"{}{}{}", "{}{}{mode}",
description description
.kind() .kind()
.map(|kind| format!("{kind}: ")) .map(|kind| format!("{kind}: "))
.unwrap_or_else(|| "".into()), .unwrap_or_else(|| "".into()),
self.colors.header_value.paint(description.title()), self.colors.header_value.paint(description.title()),
mode
); );
self.print_header_multiline_component(handle, &header_filename) self.print_header_multiline_component(handle, &header_filename)
} }
@ -704,7 +702,7 @@ impl Printer for InteractivePrinter<'_> {
"{}{}", "{}{}",
as_terminal_escaped( as_terminal_escaped(
style, style,
&format!("{}{}", self.ansi_style, text_trimmed), &format!("{}{text_trimmed}", self.ansi_style),
true_color, true_color,
colored_output, colored_output,
italics, italics,
@ -794,7 +792,7 @@ impl Printer for InteractivePrinter<'_> {
"{}{}\n{}", "{}{}\n{}",
as_terminal_escaped( as_terminal_escaped(
style, style,
&format!("{}{}", self.ansi_style, line_buf), &format!("{}{line_buf}", self.ansi_style),
self.config.true_color, self.config.true_color,
self.config.colored_output, self.config.colored_output,
self.config.use_italic_text, self.config.use_italic_text,
@ -821,7 +819,7 @@ impl Printer for InteractivePrinter<'_> {
"{}", "{}",
as_terminal_escaped( as_terminal_escaped(
style, style,
&format!("{}{}", self.ansi_style, line_buf), &format!("{}{line_buf}", self.ansi_style),
self.config.true_color, self.config.true_color,
self.config.colored_output, self.config.colored_output,
self.config.use_italic_text, self.config.use_italic_text,

View File

@ -212,15 +212,15 @@ impl Attributes {
} }
fn update_with_charset(&mut self, kind: char, set: impl Iterator<Item = char>) -> bool { fn update_with_charset(&mut self, kind: char, set: impl Iterator<Item = char>) -> bool {
self.charset = format!("\x1B{}{}", kind, set.take(1).collect::<String>()); self.charset = format!("\x1B{kind}{}", set.take(1).collect::<String>());
true true
} }
fn parse_color(color: u16, parameters: &mut dyn Iterator<Item = u16>) -> String { fn parse_color(color: u16, parameters: &mut dyn Iterator<Item = u16>) -> String {
match color % 10 { match color % 10 {
8 => match parameters.next() { 8 => match parameters.next() {
Some(5) /* 256-color */ => format!("\x1B[{};5;{}m", color, join(";", 1, parameters)), Some(5) /* 256-color */ => format!("\x1B[{color};5;{}m", join(";", 1, parameters)),
Some(2) /* 24-bit color */ => format!("\x1B[{};2;{}m", color, join(";", 3, parameters)), Some(2) /* 24-bit color */ => format!("\x1B[{color};2;{}m", join(";", 3, parameters)),
Some(c) => format!("\x1B[{color};{c}m"), Some(c) => format!("\x1B[{color};{c}m"),
_ => "".to_owned(), _ => "".to_owned(),
}, },

View File

@ -75,7 +75,7 @@ fn create_sample_directory() -> Result<TempDir, git2::Error> {
// Copy over `sample.rs` // Copy over `sample.rs`
let sample_path = temp_dir.path().join("sample.rs"); let sample_path = temp_dir.path().join("sample.rs");
println!("{:?}", &sample_path); println!("{sample_path:?}");
fs::copy("tests/snapshots/sample.rs", &sample_path).expect("successful copy"); fs::copy("tests/snapshots/sample.rs", &sample_path).expect("successful copy");
// Commit // Commit

View File

@ -19,7 +19,7 @@ fn get_mocked_pagers_dir() -> PathBuf {
pub fn from(base: &str) -> String { pub fn from(base: &str) -> String {
let mut cmd_and_args = shell_words::split(base).unwrap(); let mut cmd_and_args = shell_words::split(base).unwrap();
let suffix = if cfg!(windows) { ".bat" } else { "" }; let suffix = if cfg!(windows) { ".bat" } else { "" };
let mut out_cmd = format!("{}{}", cmd_and_args.first().unwrap(), suffix); let mut out_cmd = format!("{}{suffix}", cmd_and_args.first().unwrap());
if (cmd_and_args.len() > 1) { if (cmd_and_args.len() > 1) {
out_cmd.push(' '); out_cmd.push(' ');