chore: fix certain uninlined string format uses (#1310)

* Fixed uninlined args

First ran this, and fixed a few more similar issues by hand

```
cargo clippy --workspace --fix --benches --tests --bins -- -A clippy::all -W clippy::uninlined_format_args
```

Note that in a few cases, format args were passed by ref - which is actually a tiny perf hit - compiler would not be able to optimize them.

* revert change here

since it contains a non-inlineable variable I'm not a fan of using it partially here

* revert

given the other formats above/below I would prefer keeping it like this

---------

Co-authored-by: Clement Tsang <34804052+ClementTsang@users.noreply.github.com>
This commit is contained in:
Yuri Astrakhan 2023-11-15 03:47:22 -05:00 committed by GitHub
parent a6200640b9
commit 5eb4fbde5d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
18 changed files with 46 additions and 58 deletions

View File

@ -144,7 +144,7 @@ fn read_proc(
let truncated_name = stat.comm.as_str(); let truncated_name = stat.comm.as_str();
if let Ok(cmdline) = cmdline { if let Ok(cmdline) = cmdline {
if cmdline.is_empty() { if cmdline.is_empty() {
(format!("[{}]", truncated_name), truncated_name.to_string()) (format!("[{truncated_name}]"), truncated_name.to_string())
} else { } else {
( (
cmdline.join(" "), cmdline.join(" "),

View File

@ -123,7 +123,7 @@ fn counted_name(seen_names: &mut HashMap<String, u32>, name: String) -> String {
if let Some(count) = seen_names.get_mut(&name) { if let Some(count) = seen_names.get_mut(&name) {
*count += 1; *count += 1;
format!("{name} ({})", *count) format!("{name} ({count})")
} else { } else {
seen_names.insert(name.clone(), 0); seen_names.insert(name.clone(), 0);
name name

View File

@ -1018,7 +1018,7 @@ impl std::str::FromStr for BottomWidgetType {
#[cfg(feature = "battery")] #[cfg(feature = "battery")]
{ {
Err(BottomError::ConfigError(format!( Err(BottomError::ConfigError(format!(
"\"{}\" is an invalid widget name. "\"{s}\" is an invalid widget name.
Supported widget names: Supported widget names:
+--------------------------+ +--------------------------+
@ -1037,13 +1037,12 @@ Supported widget names:
| batt, battery | | batt, battery |
+--------------------------+ +--------------------------+
", ",
s
))) )))
} }
#[cfg(not(feature = "battery"))] #[cfg(not(feature = "battery"))]
{ {
Err(BottomError::ConfigError(format!( Err(BottomError::ConfigError(format!(
"\"{}\" is an invalid widget name. "\"{s}\" is an invalid widget name.
Supported widget names: Supported widget names:
+--------------------------+ +--------------------------+
@ -1060,7 +1059,6 @@ Supported widget names:
| disk | | disk |
+--------------------------+ +--------------------------+
", ",
s
))) )))
} }
} }

View File

@ -75,14 +75,10 @@ pub fn kill_process_given_pid(pid: Pid, signal: usize) -> crate::utils::error::R
return if let Some(err_code) = err_code { return if let Some(err_code) = err_code {
Err(BottomError::GenericError(format!( Err(BottomError::GenericError(format!(
"Error code {} - {}", "Error code {err_code} - {err}"
err_code, err,
))) )))
} else { } else {
Err(BottomError::GenericError(format!( Err(BottomError::GenericError(format!("Error code ??? - {err}")))
"Error code ??? - {}",
err,
)))
}; };
} }

View File

@ -54,7 +54,7 @@ pub fn parse_query(
let mut rhs: Option<Box<And>> = None; let mut rhs: Option<Box<And>> = None;
while let Some(queue_top) = query.front() { while let Some(queue_top) = query.front() {
// debug!("OR QT: {:?}", queue_top); // debug!("OR QT: {queue_top:?}");
if OR_LIST.contains(&queue_top.to_lowercase().as_str()) { if OR_LIST.contains(&queue_top.to_lowercase().as_str()) {
query.pop_front(); query.pop_front();
rhs = Some(Box::new(process_and(query)?)); rhs = Some(Box::new(process_and(query)?));
@ -90,7 +90,7 @@ pub fn parse_query(
let mut rhs: Option<Box<Prefix>> = None; let mut rhs: Option<Box<Prefix>> = None;
while let Some(queue_top) = query.front() { while let Some(queue_top) = query.front() {
// debug!("AND QT: {:?}", queue_top); // debug!("AND QT: {queue_top:?}");
if AND_LIST.contains(&queue_top.to_lowercase().as_str()) { if AND_LIST.contains(&queue_top.to_lowercase().as_str()) {
query.pop_front(); query.pop_front();
@ -810,11 +810,11 @@ impl Prefix {
impl Debug for Prefix { impl Debug for Prefix {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if let Some(or) = &self.or { if let Some(or) = &self.or {
f.write_fmt(format_args!("{:?}", or)) f.write_fmt(format_args!("{or:?}"))
} else if let Some(regex_prefix) = &self.regex_prefix { } else if let Some(regex_prefix) = &self.regex_prefix {
f.write_fmt(format_args!("{:?}", regex_prefix)) f.write_fmt(format_args!("{regex_prefix:?}"))
} else if let Some(compare_prefix) = &self.compare_prefix { } else if let Some(compare_prefix) = &self.compare_prefix {
f.write_fmt(format_args!("{:?}", compare_prefix)) f.write_fmt(format_args!("{compare_prefix:?}"))
} else { } else {
f.write_fmt(format_args!("")) f.write_fmt(format_args!(""))
} }

View File

@ -49,8 +49,7 @@ impl FromStr for ColourScheme {
"nord" => Ok(ColourScheme::Nord), "nord" => Ok(ColourScheme::Nord),
"nord-light" => Ok(ColourScheme::NordLight), "nord-light" => Ok(ColourScheme::NordLight),
_ => Err(BottomError::ConfigError(format!( _ => Err(BottomError::ConfigError(format!(
"\"{}\" is an invalid built-in color scheme.", "\"{s}\" is an invalid built-in color scheme."
s
))), ))),
} }
} }

View File

@ -70,8 +70,7 @@ pub fn str_to_colour(input_val: &str) -> error::Result<Color> {
} }
} else { } else {
Err(error::BottomError::ConfigError(format!( Err(error::BottomError::ConfigError(format!(
"value \"{}\" is not valid.", "value \"{input_val}\" is not valid.",
input_val
))) )))
} }
} }
@ -80,8 +79,7 @@ fn convert_rgb_to_color(rgb_str: &str) -> error::Result<Color> {
let rgb_list = rgb_str.split(',').collect::<Vec<&str>>(); let rgb_list = rgb_str.split(',').collect::<Vec<&str>>();
if rgb_list.len() != 3 { if rgb_list.len() != 3 {
return Err(error::BottomError::ConfigError(format!( return Err(error::BottomError::ConfigError(format!(
"value \"{}\" is an invalid RGB colour. It must be a comma separated value with 3 integers from 0 to 255 (ie: \"255, 0, 155\").", "value \"{rgb_str}\" is an invalid RGB colour. It must be a comma separated value with 3 integers from 0 to 255 (ie: \"255, 0, 155\").",
rgb_str
))); )));
} }
@ -99,8 +97,7 @@ fn convert_rgb_to_color(rgb_str: &str) -> error::Result<Color> {
Ok(Color::Rgb(rgb[0], rgb[1], rgb[2])) Ok(Color::Rgb(rgb[0], rgb[1], rgb[2]))
} else { } else {
Err(error::BottomError::ConfigError(format!( Err(error::BottomError::ConfigError(format!(
"value \"{}\" contained invalid RGB values. It must be a comma separated value with 3 integers from 0 to 255 (ie: \"255, 0, 155\").", "value \"{rgb_str}\" contained invalid RGB values. It must be a comma separated value with 3 integers from 0 to 255 (ie: \"255, 0, 155\").",
rgb_str
))) )))
} }
} }
@ -125,7 +122,7 @@ fn convert_name_to_colour(color_name: &str) -> error::Result<Color> {
"lightcyan" | "light cyan" => Ok(Color::LightCyan), "lightcyan" | "light cyan" => Ok(Color::LightCyan),
"white" => Ok(Color::White), "white" => Ok(Color::White),
_ => Err(error::BottomError::ConfigError(format!( _ => Err(error::BottomError::ConfigError(format!(
"\"{}\" is an invalid named color. "\"{color_name}\" is an invalid named color.
The following are supported strings: The following are supported strings:
+--------+-------------+---------------------+ +--------+-------------+---------------------+
@ -142,7 +139,6 @@ The following are supported strings:
| Blue | Light Green | | | Blue | Light Green | |
+--------+-------------+---------------------+ +--------+-------------+---------------------+
", ",
color_name
))), ))),
} }
} }

View File

@ -95,7 +95,7 @@ impl Painter {
let left_arrow_text = vec![ let left_arrow_text = vec![
Line::default(), Line::default(),
Line::from(Span::styled( Line::from(Span::styled(
format!("{}", left_name), format!("{left_name}"),
self.colours.text_style, self.colours.text_style,
)), )),
]; ];
@ -103,7 +103,7 @@ impl Painter {
let right_arrow_text = vec![ let right_arrow_text = vec![
Line::default(), Line::default(),
Line::from(Span::styled( Line::from(Span::styled(
format!("{}", right_name), format!("{right_name}"),
self.colours.text_style, self.colours.text_style,
)), )),
]; ];

View File

@ -176,9 +176,9 @@ impl Painter {
let num_seconds = time.whole_seconds() - time.whole_minutes() * 60; let num_seconds = time.whole_seconds() - time.whole_minutes() * 60;
if num_hours > 0 { if num_hours > 0 {
format!("{}h {}m {}s", time.whole_hours(), num_minutes, num_seconds,) format!("{num_hours}h {num_minutes}m {num_seconds}s")
} else { } else {
format!("{}m {}s", num_minutes, num_seconds,) format!("{num_minutes}m {num_seconds}s")
} }
} }

View File

@ -50,7 +50,7 @@ impl Painter {
let mut points = Vec::with_capacity(size); let mut points = Vec::with_capacity(size);
if let Some((label_percent, label_frac)) = &app_state.converted_data.mem_labels { if let Some((label_percent, label_frac)) = &app_state.converted_data.mem_labels {
let mem_label = format!("RAM:{}{}", label_percent, label_frac); let mem_label = format!("RAM:{label_percent}{label_frac}");
points.push(GraphData { points.push(GraphData {
points: &app_state.converted_data.mem_data, points: &app_state.converted_data.mem_data,
style: self.colours.ram_style, style: self.colours.ram_style,
@ -59,7 +59,7 @@ impl Painter {
} }
#[cfg(not(target_os = "windows"))] #[cfg(not(target_os = "windows"))]
if let Some((label_percent, label_frac)) = &app_state.converted_data.cache_labels { if let Some((label_percent, label_frac)) = &app_state.converted_data.cache_labels {
let cache_label = format!("CHE:{}{}", label_percent, label_frac); let cache_label = format!("CHE:{label_percent}{label_frac}");
points.push(GraphData { points.push(GraphData {
points: &app_state.converted_data.cache_data, points: &app_state.converted_data.cache_data,
style: self.colours.cache_style, style: self.colours.cache_style,
@ -67,7 +67,7 @@ impl Painter {
}); });
} }
if let Some((label_percent, label_frac)) = &app_state.converted_data.swap_labels { if let Some((label_percent, label_frac)) = &app_state.converted_data.swap_labels {
let swap_label = format!("SWP:{}{}", label_percent, label_frac); let swap_label = format!("SWP:{label_percent}{label_frac}");
points.push(GraphData { points.push(GraphData {
points: &app_state.converted_data.swap_data, points: &app_state.converted_data.swap_data,
style: self.colours.swap_style, style: self.colours.swap_style,
@ -76,7 +76,7 @@ impl Painter {
} }
#[cfg(feature = "zfs")] #[cfg(feature = "zfs")]
if let Some((label_percent, label_frac)) = &app_state.converted_data.arc_labels { if let Some((label_percent, label_frac)) = &app_state.converted_data.arc_labels {
let arc_label = format!("ARC:{}{}", label_percent, label_frac); let arc_label = format!("ARC:{label_percent}{label_frac}");
points.push(GraphData { points.push(GraphData {
points: &app_state.converted_data.arc_data, points: &app_state.converted_data.arc_data,
style: self.colours.arc_style, style: self.colours.arc_style,

View File

@ -38,10 +38,10 @@ impl Painter {
); );
} }
let rx_label = format!("RX: {}", &app_state.converted_data.rx_display); let rx_label = format!("RX: {}", app_state.converted_data.rx_display);
let tx_label = format!("TX: {}", &app_state.converted_data.tx_display); let tx_label = format!("TX: {}", app_state.converted_data.tx_display);
let total_rx_label = format!("Total RX: {}", &app_state.converted_data.total_rx_display); let total_rx_label = format!("Total RX: {}", app_state.converted_data.total_rx_display);
let total_tx_label = format!("Total TX: {}", &app_state.converted_data.total_tx_display); let total_tx_label = format!("Total TX: {}", app_state.converted_data.total_tx_display);
let net_text = vec![ let net_text = vec![
Line::from(Span::styled(rx_label, self.colours.rx_style)), Line::from(Span::styled(rx_label, self.colours.rx_style)),

View File

@ -413,13 +413,13 @@ fn adjust_network_data_point(
let base_unit = max_value_scaled; let base_unit = max_value_scaled;
let labels: Vec<String> = vec![ let labels: Vec<String> = vec![
format!("0{}{}", unit_prefix, unit_type), format!("0{unit_prefix}{unit_type}"),
format!("{:.1}", base_unit * 0.5), format!("{:.1}", base_unit * 0.5),
format!("{:.1}", base_unit), format!("{:.1}", base_unit),
format!("{:.1}", base_unit * 1.5), format!("{:.1}", base_unit * 1.5),
] ]
.into_iter() .into_iter()
.map(|s| format!("{:>5}", s)) // Pull 5 as the longest legend value is generally going to be 5 digits (if they somehow hit over 5 terabits per second) .map(|s| format!("{s:>5}")) // Pull 5 as the longest legend value is generally going to be 5 digits (if they somehow hit over 5 terabits per second)
.collect(); .collect();
(bumped_max_entry, labels) (bumped_max_entry, labels)

View File

@ -696,7 +696,7 @@ mod test {
for case in &cases { for case in &cases {
let datasets = (0..10) let datasets = (0..10)
.map(|i| { .map(|i| {
let name = format!("Dataset #{}", i); let name = format!("Dataset #{i}");
Dataset::default().name(name).data(&data) Dataset::default().name(name).data(&data)
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();

View File

@ -110,7 +110,7 @@ pub fn handle_mouse_event(event: MouseEvent, app: &mut App) {
pub fn handle_key_event_or_break( pub fn handle_key_event_or_break(
event: KeyEvent, app: &mut App, reset_sender: &Sender<CollectionThreadEvent>, event: KeyEvent, app: &mut App, reset_sender: &Sender<CollectionThreadEvent>,
) -> bool { ) -> bool {
// c_debug!("KeyEvent: {:?}", event); // c_debug!("KeyEvent: {event:?}");
if event.modifiers.is_empty() { if event.modifiers.is_empty() {
// Required catch for searching - otherwise you couldn't search with q. // Required catch for searching - otherwise you couldn't search with q.
@ -504,7 +504,7 @@ pub fn create_collection_thread(
} }
if let Ok(message) = control_receiver.try_recv() { if let Ok(message) = control_receiver.try_recv() {
// trace!("Received message in collection thread: {:?}", message); // trace!("Received message in collection thread: {message:?}");
match message { match message {
CollectionThreadEvent::Reset => { CollectionThreadEvent::Reset => {
data_state.data.cleanup(); data_state.data.cleanup();

View File

@ -534,7 +534,7 @@ pub fn get_widget_layout(
// Confirm that we have at least ONE widget left - if not, error out! // Confirm that we have at least ONE widget left - if not, error out!
if iter_id > 0 { if iter_id > 0 {
ret_bottom_layout.get_movement_mappings(); ret_bottom_layout.get_movement_mappings();
// debug!("Bottom layout: {:#?}", ret_bottom_layout); // debug!("Bottom layout: {ret_bottom_layout:#?}");
ret_bottom_layout ret_bottom_layout
} else { } else {
@ -589,8 +589,7 @@ fn get_temperature(
"kelvin" | "k" => Ok(data_harvester::temperature::TemperatureType::Kelvin), "kelvin" | "k" => Ok(data_harvester::temperature::TemperatureType::Kelvin),
"celsius" | "c" => Ok(data_harvester::temperature::TemperatureType::Celsius), "celsius" | "c" => Ok(data_harvester::temperature::TemperatureType::Celsius),
_ => Err(BottomError::ConfigError(format!( _ => Err(BottomError::ConfigError(format!(
"\"{}\" is an invalid temperature type, use \"<kelvin|k|celsius|c|fahrenheit|f>\".", "\"{temp_type}\" is an invalid temperature type, use \"<kelvin|k|celsius|c|fahrenheit|f>\"."
temp_type
))), ))),
}; };
} }

View File

@ -76,10 +76,10 @@ pub fn get_decimal_bytes(bytes: u64) -> (f64, &'static str) {
pub fn get_binary_prefix(quantity: u64, unit: &str) -> (f64, String) { pub fn get_binary_prefix(quantity: u64, unit: &str) -> (f64, String) {
match quantity { match quantity {
b if b < KIBI_LIMIT => (quantity as f64, unit.to_string()), b if b < KIBI_LIMIT => (quantity as f64, unit.to_string()),
b if b < MEBI_LIMIT => (quantity as f64 / 1024.0, format!("Ki{}", unit)), b if b < MEBI_LIMIT => (quantity as f64 / 1024.0, format!("Ki{unit}")),
b if b < GIBI_LIMIT => (quantity as f64 / 1_048_576.0, format!("Mi{}", unit)), b if b < GIBI_LIMIT => (quantity as f64 / 1_048_576.0, format!("Mi{unit}")),
b if b < TERA_LIMIT => (quantity as f64 / 1_073_741_824.0, format!("Gi{}", unit)), b if b < TERA_LIMIT => (quantity as f64 / 1_073_741_824.0, format!("Gi{unit}")),
_ => (quantity as f64 / 1_099_511_627_776.0, format!("Ti{}", unit)), _ => (quantity as f64 / 1_099_511_627_776.0, format!("Ti{unit}")),
} }
} }
@ -89,10 +89,10 @@ pub fn get_binary_prefix(quantity: u64, unit: &str) -> (f64, String) {
pub fn get_decimal_prefix(quantity: u64, unit: &str) -> (f64, String) { pub fn get_decimal_prefix(quantity: u64, unit: &str) -> (f64, String) {
match quantity { match quantity {
b if b < KILO_LIMIT => (quantity as f64, unit.to_string()), b if b < KILO_LIMIT => (quantity as f64, unit.to_string()),
b if b < MEGA_LIMIT => (quantity as f64 / 1000.0, format!("K{}", unit)), b if b < MEGA_LIMIT => (quantity as f64 / 1000.0, format!("K{unit}")),
b if b < GIGA_LIMIT => (quantity as f64 / 1_000_000.0, format!("M{}", unit)), b if b < GIGA_LIMIT => (quantity as f64 / 1_000_000.0, format!("M{unit}")),
b if b < TERA_LIMIT => (quantity as f64 / 1_000_000_000.0, format!("G{}", unit)), b if b < TERA_LIMIT => (quantity as f64 / 1_000_000_000.0, format!("G{unit}")),
_ => (quantity as f64 / 1_000_000_000_000.0, format!("T{}", unit)), _ => (quantity as f64 / 1_000_000_000_000.0, format!("T{unit}")),
} }
} }

View File

@ -69,7 +69,7 @@ impl DiskWidgetData {
pub fn free_percent_string(&self) -> KString { pub fn free_percent_string(&self) -> KString {
match self.free_percent() { match self.free_percent() {
Some(val) => format!("{:.1}%", val).into(), Some(val) => format!("{val:.1}%").into(),
None => "N/A".into(), None => "N/A".into(),
} }
} }
@ -90,7 +90,7 @@ impl DiskWidgetData {
pub fn used_percent_string(&self) -> KString { pub fn used_percent_string(&self) -> KString {
match self.used_percent() { match self.used_percent() {
Some(val) => format!("{:.1}%", val).into(), Some(val) => format!("{val:.1}%").into(),
None => "N/A".into(), None => "N/A".into(),
} }
} }

View File

@ -101,7 +101,7 @@ impl PartialOrd for MemUsage {
impl Display for MemUsage { impl Display for MemUsage {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self { match self {
MemUsage::Percent(percent) => f.write_fmt(format_args!("{:.1}%", percent)), MemUsage::Percent(percent) => f.write_fmt(format_args!("{percent:.1}%")),
MemUsage::Bytes(bytes) => f.write_str(&binary_byte_string(*bytes)), MemUsage::Bytes(bytes) => f.write_str(&binary_byte_string(*bytes)),
} }
} }