refactor: remove some simple as-casts (#697)

Remove some simple as casts that are easy to change to .into(), or easy to check.
This commit is contained in:
Clement Tsang 2022-03-27 22:01:06 -04:00 committed by GitHub
parent 747497cc8a
commit d297ee4639
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
14 changed files with 86 additions and 83 deletions

View File

@ -1,7 +1,6 @@
use std::{ use std::{
cmp::{max, min}, cmp::{max, min},
collections::HashMap, collections::HashMap,
// io::Write,
path::PathBuf, path::PathBuf,
time::Instant, time::Instant,
}; };
@ -1383,7 +1382,7 @@ impl App {
if current_key_press_inst if current_key_press_inst
.duration_since(self.last_key_press) .duration_since(self.last_key_press)
.as_millis() .as_millis()
> constants::MAX_KEY_TIMEOUT_IN_MILLISECONDS as u128 > constants::MAX_KEY_TIMEOUT_IN_MILLISECONDS.into()
{ {
self.reset_multi_tap_keys(); self.reset_multi_tap_keys();
} }
@ -1450,10 +1449,10 @@ impl App {
'1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' => { '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' => {
let potential_index = caught_char.to_digit(10); let potential_index = caught_char.to_digit(10);
if let Some(potential_index) = potential_index { if let Some(potential_index) = potential_index {
if (potential_index as usize) < self.help_dialog_state.index_shortcuts.len() let potential_index = potential_index as usize;
{ if (potential_index) < self.help_dialog_state.index_shortcuts.len() {
self.help_scroll_to_or_max( self.help_scroll_to_or_max(
self.help_dialog_state.index_shortcuts[potential_index as usize], self.help_dialog_state.index_shortcuts[potential_index],
); );
} }
} }

View File

@ -121,7 +121,7 @@ impl DataCollection {
current_time current_time
.duration_since(*instant) .duration_since(*instant)
.as_millis() .as_millis()
.cmp(&(max_time_millis as u128)) .cmp(&(max_time_millis.into()))
.reverse() .reverse()
}) { }) {
Ok(index) => index, Ok(index) => index,

View File

@ -270,7 +270,7 @@ impl KillDialog for Painter {
let layout = Layout::default() let layout = Layout::default()
.direction(Direction::Vertical) .direction(Direction::Vertical)
.constraints(vec![Constraint::Min(1); button_rect.height as usize]) .constraints(vec![Constraint::Min(1); button_rect.height.into()])
.split(button_rect); .split(button_rect);
let prev_offset: usize = app_state.delete_dialog_state.scroll_pos; let prev_offset: usize = app_state.delete_dialog_state.scroll_pos;
@ -278,15 +278,15 @@ impl KillDialog for Painter {
0 0
} else if selected < prev_offset + 1 { } else if selected < prev_offset + 1 {
selected - 1 selected - 1
} else if selected > prev_offset + (layout.len() as usize) - 1 { } else if selected > prev_offset + layout.len() - 1 {
selected - (layout.len() as usize) + 1 selected - layout.len() + 1
} else { } else {
prev_offset prev_offset
}; };
let scroll_offset: usize = app_state.delete_dialog_state.scroll_pos; let scroll_offset: usize = app_state.delete_dialog_state.scroll_pos;
let mut buttons = signal_text[scroll_offset + 1 let mut buttons = signal_text
..min((layout.len() as usize) + scroll_offset, signal_text.len())] [scroll_offset + 1..min((layout.len()) + scroll_offset, signal_text.len())]
.iter() .iter()
.map(|text| Span::raw(*text)) .map(|text| Span::raw(*text))
.collect::<Vec<Span<'_>>>(); .collect::<Vec<Span<'_>>>();

View File

@ -98,7 +98,7 @@ pub fn get_column_widths(
let amount_per_slot = total_width_left / column_widths.len() as u16; let amount_per_slot = total_width_left / column_widths.len() as u16;
total_width_left %= column_widths.len() as u16; total_width_left %= column_widths.len() as u16;
for (index, width) in column_widths.iter_mut().enumerate() { for (index, width) in column_widths.iter_mut().enumerate() {
if (index as u16) < total_width_left { if index < total_width_left.into() {
*width += amount_per_slot + 1; *width += amount_per_slot + 1;
} else { } else {
*width += amount_per_slot; *width += amount_per_slot;

View File

@ -165,7 +165,7 @@ impl BatteryDisplayWidget for Painter {
margined_draw_loc, margined_draw_loc,
); );
} else { } else {
let mut contents = vec![Spans::default(); table_gap as usize]; let mut contents = vec![Spans::default(); table_gap.into()];
contents.push(Spans::from(Span::styled( contents.push(Spans::from(Span::styled(
"No data found for this battery", "No data found for this battery",

View File

@ -70,7 +70,7 @@ impl CpuBasicWidget for Painter {
const COMBINED_SPACING: usize = const COMBINED_SPACING: usize =
CPU_NAME_SPACE + BAR_BOUND_SPACE + PERCENTAGE_SPACE + MARGIN_SPACE; CPU_NAME_SPACE + BAR_BOUND_SPACE + PERCENTAGE_SPACE + MARGIN_SPACE;
const REDUCED_SPACING: usize = CPU_NAME_SPACE + PERCENTAGE_SPACE + MARGIN_SPACE; const REDUCED_SPACING: usize = CPU_NAME_SPACE + PERCENTAGE_SPACE + MARGIN_SPACE;
let chunk_width = chunks[0].width as usize; let chunk_width: usize = chunks[0].width.into();
// Inspired by htop. // Inspired by htop.
// We do +4 as if it's too few bars in the bar length, it's kinda pointless. // We do +4 as if it's too few bars in the bar length, it's kinda pointless.

View File

@ -159,7 +159,7 @@ impl CpuGraphWidget for Painter {
Axis::default().bounds([time_start, 0.0]) Axis::default().bounds([time_start, 0.0])
} else if let Some(time) = cpu_widget_state.autohide_timer { } else if let Some(time) = cpu_widget_state.autohide_timer {
if std::time::Instant::now().duration_since(time).as_millis() if std::time::Instant::now().duration_since(time).as_millis()
< AUTOHIDE_TIMEOUT_MILLISECONDS as u128 < AUTOHIDE_TIMEOUT_MILLISECONDS.into()
{ {
Axis::default() Axis::default()
.bounds([time_start, 0.0]) .bounds([time_start, 0.0])

View File

@ -128,17 +128,19 @@ impl DiskTableWidget for Painter {
if *desired_col_width > *calculated_col_width if *desired_col_width > *calculated_col_width
&& *calculated_col_width > 0 && *calculated_col_width > 0
{ {
let calculated_col_width: usize =
(*calculated_col_width).into();
let graphemes = let graphemes =
UnicodeSegmentation::graphemes(entry.as_str(), true) UnicodeSegmentation::graphemes(entry.as_str(), true)
.collect::<Vec<&str>>(); .collect::<Vec<&str>>();
if graphemes.len() > *calculated_col_width as usize if graphemes.len() > calculated_col_width
&& *calculated_col_width > 1 && calculated_col_width > 1
{ {
// Truncate with ellipsis // Truncate with ellipsis
let first_n = graphemes let first_n =
[..(*calculated_col_width as usize - 1)] graphemes[..(calculated_col_width - 1)].concat();
.concat();
return Text::raw(format!("{}", first_n)); return Text::raw(format!("{}", first_n));
} }
} }
@ -171,7 +173,7 @@ impl DiskTableWidget for Painter {
app_state.canvas_data.disk_data.len() app_state.canvas_data.disk_data.len()
); );
if title_string.len() <= draw_loc.width as usize { if title_string.len() <= draw_loc.width.into() {
title_string title_string
} else { } else {
" Disk ".to_string() " Disk ".to_string()
@ -186,7 +188,7 @@ impl DiskTableWidget for Painter {
let (chosen_title_base, expanded_title_base) = { let (chosen_title_base, expanded_title_base) = {
let temp_title_base = format!("{}{}", title_base, ESCAPE_ENDING); let temp_title_base = format!("{}{}", title_base, ESCAPE_ENDING);
if temp_title_base.len() > draw_loc.width as usize { if temp_title_base.len() > draw_loc.width.into() {
( (
" Disk ".to_string(), " Disk ".to_string(),
format!("{}{}", " Disk ", ESCAPE_ENDING), format!("{}{}", " Disk ", ESCAPE_ENDING),
@ -254,7 +256,7 @@ impl DiskTableWidget for Painter {
.table_width_state .table_width_state
.calculated_column_widths .calculated_column_widths
.iter() .iter()
.map(|calculated_width| Constraint::Length(*calculated_width as u16)) .map(|calculated_width| Constraint::Length(*calculated_width))
.collect::<Vec<_>>()), .collect::<Vec<_>>()),
), ),
margined_draw_loc, margined_draw_loc,

View File

@ -50,7 +50,7 @@ impl MemGraphWidget for Painter {
Axis::default().bounds([time_start, 0.0]) Axis::default().bounds([time_start, 0.0])
} else if let Some(time) = mem_widget_state.autohide_timer { } else if let Some(time) = mem_widget_state.autohide_timer {
if std::time::Instant::now().duration_since(time).as_millis() if std::time::Instant::now().duration_since(time).as_millis()
< AUTOHIDE_TIMEOUT_MILLISECONDS as u128 < AUTOHIDE_TIMEOUT_MILLISECONDS.into()
{ {
Axis::default() Axis::default()
.bounds([time_start, 0.0]) .bounds([time_start, 0.0])

View File

@ -438,7 +438,7 @@ impl NetworkGraphWidget for Painter {
Axis::default().bounds([time_start, 0.0]) Axis::default().bounds([time_start, 0.0])
} else if let Some(time) = network_widget_state.autohide_timer { } else if let Some(time) = network_widget_state.autohide_timer {
if std::time::Instant::now().duration_since(time).as_millis() if std::time::Instant::now().duration_since(time).as_millis()
< AUTOHIDE_TIMEOUT_MILLISECONDS as u128 < AUTOHIDE_TIMEOUT_MILLISECONDS.into()
{ {
Axis::default() Axis::default()
.bounds([time_start, 0.0]) .bounds([time_start, 0.0])
@ -761,7 +761,7 @@ impl NetworkGraphWidget for Painter {
.widths( .widths(
&(intrinsic_widths &(intrinsic_widths
.iter() .iter()
.map(|calculated_width| Constraint::Length(*calculated_width as u16)) .map(|calculated_width| Constraint::Length(*calculated_width))
.collect::<Vec<_>>()), .collect::<Vec<_>>()),
), ),
draw_loc, draw_loc,

View File

@ -215,7 +215,7 @@ impl ProcessTableWidget for Painter {
finalized_process_data.len() finalized_process_data.len()
); );
if title.len() <= draw_loc.width as usize { if title.len() <= draw_loc.width.into() {
title title
} else { } else {
" Processes ".to_string() " Processes ".to_string()
@ -239,7 +239,7 @@ impl ProcessTableWidget for Painter {
let (chosen_title_base, expanded_title_base) = { let (chosen_title_base, expanded_title_base) = {
let temp_title_base = format!("{}{}", title_base, ESCAPE_ENDING); let temp_title_base = format!("{}{}", title_base, ESCAPE_ENDING);
if temp_title_base.len() > draw_loc.width as usize { if temp_title_base.len() > draw_loc.width.into() {
( (
" Processes ".to_string(), " Processes ".to_string(),
format!("{}{}", " Processes ", ESCAPE_ENDING), format!("{}{}", " Processes ", ESCAPE_ENDING),
@ -442,19 +442,21 @@ impl ProcessTableWidget for Painter {
if *desired_col_width > *calculated_col_width if *desired_col_width > *calculated_col_width
&& *calculated_col_width > 0 && *calculated_col_width > 0
{ {
let calculated_col_width: usize =
(*calculated_col_width).into();
let graphemes = let graphemes =
UnicodeSegmentation::graphemes(entry.as_str(), true) UnicodeSegmentation::graphemes(entry.as_str(), true)
.collect::<Vec<&str>>(); .collect::<Vec<&str>>();
if let Some(alternative) = alternative { if let Some(alternative) = alternative {
Text::raw(alternative) Text::raw(alternative)
} else if graphemes.len() > *calculated_col_width as usize } else if graphemes.len() > calculated_col_width
&& *calculated_col_width > 1 && calculated_col_width > 1
{ {
// Truncate with ellipsis // Truncate with ellipsis
let first_n = graphemes let first_n =
[..(*calculated_col_width as usize - 1)] graphemes[..(calculated_col_width - 1)].concat();
.concat();
Text::raw(format!("{}", first_n)) Text::raw(format!("{}", first_n))
} else { } else {
Text::raw(entry) Text::raw(entry)
@ -493,9 +495,7 @@ impl ProcessTableWidget for Painter {
.table_width_state .table_width_state
.calculated_column_widths .calculated_column_widths
.iter() .iter()
.map(|calculated_width| { .map(|calculated_width| Constraint::Length(*calculated_width))
Constraint::Length(*calculated_width as u16)
})
.collect::<Vec<_>>()), .collect::<Vec<_>>()),
), ),
margined_draw_loc, margined_draw_loc,

View File

@ -111,17 +111,19 @@ impl TempTableWidget for Painter {
if *desired_col_width > *calculated_col_width if *desired_col_width > *calculated_col_width
&& *calculated_col_width > 0 && *calculated_col_width > 0
{ {
let calculated_col_width: usize =
(*calculated_col_width).into();
let graphemes = let graphemes =
UnicodeSegmentation::graphemes(entry.as_str(), true) UnicodeSegmentation::graphemes(entry.as_str(), true)
.collect::<Vec<&str>>(); .collect::<Vec<&str>>();
if graphemes.len() > *calculated_col_width as usize if graphemes.len() > calculated_col_width
&& *calculated_col_width > 1 && calculated_col_width > 1
{ {
// Truncate with ellipsis // Truncate with ellipsis
let first_n = graphemes let first_n =
[..(*calculated_col_width as usize - 1)] graphemes[..(calculated_col_width - 1)].concat();
.concat();
Text::raw(format!("{}", first_n)) Text::raw(format!("{}", first_n))
} else { } else {
Text::raw(entry) Text::raw(entry)
@ -160,7 +162,7 @@ impl TempTableWidget for Painter {
app_state.canvas_data.temp_sensor_data.len() app_state.canvas_data.temp_sensor_data.len()
); );
if title_string.len() <= draw_loc.width as usize { if title_string.len() <= draw_loc.width.into() {
title_string title_string
} else { } else {
" Temperatures ".to_string() " Temperatures ".to_string()
@ -175,7 +177,7 @@ impl TempTableWidget for Painter {
let (chosen_title_base, expanded_title_base) = { let (chosen_title_base, expanded_title_base) = {
let temp_title_base = format!("{}{}", title_base, ESCAPE_ENDING); let temp_title_base = format!("{}{}", title_base, ESCAPE_ENDING);
if temp_title_base.len() > draw_loc.width as usize { if temp_title_base.len() > draw_loc.width.into() {
( (
" Temperatures ".to_string(), " Temperatures ".to_string(),
format!("{}{}", " Temperatures ", ESCAPE_ENDING), format!("{}{}", " Temperatures ", ESCAPE_ENDING),
@ -243,7 +245,7 @@ impl TempTableWidget for Painter {
.table_width_state .table_width_state
.calculated_column_widths .calculated_column_widths
.iter() .iter()
.map(|calculated_width| Constraint::Length(*calculated_width as u16)) .map(|calculated_width| Constraint::Length(*calculated_width))
.collect::<Vec<_>>()), .collect::<Vec<_>>()),
), ),
margined_draw_loc, margined_draw_loc,

View File

@ -3,6 +3,7 @@ use serde::{Deserialize, Serialize};
use std::{ use std::{
borrow::Cow, borrow::Cow,
collections::{HashMap, HashSet}, collections::{HashMap, HashSet},
convert::TryInto,
path::PathBuf, path::PathBuf,
str::FromStr, str::FromStr,
time::Instant, time::Instant,
@ -592,28 +593,28 @@ fn get_update_rate_in_milliseconds(
matches: &clap::ArgMatches, config: &Config, matches: &clap::ArgMatches, config: &Config,
) -> error::Result<u64> { ) -> error::Result<u64> {
let update_rate_in_milliseconds = if let Some(update_rate) = matches.value_of("rate") { let update_rate_in_milliseconds = if let Some(update_rate) = matches.value_of("rate") {
update_rate.parse::<u128>()? update_rate.parse::<u64>().map_err(|_| {
BottomError::ConfigError(
"could not parse as a valid 64-bit unsigned integer".to_string(),
)
})?
} else if let Some(flags) = &config.flags { } else if let Some(flags) = &config.flags {
if let Some(rate) = flags.rate { if let Some(rate) = flags.rate {
rate as u128 rate
} else { } else {
DEFAULT_REFRESH_RATE_IN_MILLISECONDS as u128 DEFAULT_REFRESH_RATE_IN_MILLISECONDS
} }
} else { } else {
DEFAULT_REFRESH_RATE_IN_MILLISECONDS as u128 DEFAULT_REFRESH_RATE_IN_MILLISECONDS
}; };
if update_rate_in_milliseconds < 250 { if update_rate_in_milliseconds < 250 {
return Err(BottomError::ConfigError( return Err(BottomError::ConfigError(
"set your update rate to be at least 250 milliseconds.".to_string(), "set your update rate to be at least 250 milliseconds.".to_string(),
)); ));
} else if update_rate_in_milliseconds as u128 > std::u64::MAX as u128 {
return Err(BottomError::ConfigError(
"set your update rate to be at most unsigned INT_MAX.".to_string(),
));
} }
Ok(update_rate_in_milliseconds as u64) Ok(update_rate_in_milliseconds)
} }
fn get_temperature( fn get_temperature(
@ -704,56 +705,64 @@ fn get_use_basic_mode(matches: &clap::ArgMatches, config: &Config) -> bool {
fn get_default_time_value(matches: &clap::ArgMatches, config: &Config) -> error::Result<u64> { fn get_default_time_value(matches: &clap::ArgMatches, config: &Config) -> error::Result<u64> {
let default_time = if let Some(default_time_value) = matches.value_of("default_time_value") { let default_time = if let Some(default_time_value) = matches.value_of("default_time_value") {
default_time_value.parse::<u128>()? default_time_value.parse::<u64>().map_err(|_| {
BottomError::ConfigError(
"could not parse as a valid 64-bit unsigned integer".to_string(),
)
})?
} else if let Some(flags) = &config.flags { } else if let Some(flags) = &config.flags {
if let Some(default_time_value) = flags.default_time_value { if let Some(default_time_value) = flags.default_time_value {
default_time_value as u128 default_time_value
} else { } else {
DEFAULT_TIME_MILLISECONDS as u128 DEFAULT_TIME_MILLISECONDS
} }
} else { } else {
DEFAULT_TIME_MILLISECONDS as u128 DEFAULT_TIME_MILLISECONDS
}; };
if default_time < 30000 { if default_time < 30000 {
return Err(BottomError::ConfigError( return Err(BottomError::ConfigError(
"set your default value to be at least 30000 milliseconds.".to_string(), "set your default value to be at least 30000 milliseconds.".to_string(),
)); ));
} else if default_time as u128 > STALE_MAX_MILLISECONDS as u128 { } else if default_time > STALE_MAX_MILLISECONDS {
return Err(BottomError::ConfigError(format!( return Err(BottomError::ConfigError(format!(
"set your default value to be at most {} milliseconds.", "set your default value to be at most {} milliseconds.",
STALE_MAX_MILLISECONDS STALE_MAX_MILLISECONDS
))); )));
} }
Ok(default_time as u64) Ok(default_time)
} }
fn get_time_interval(matches: &clap::ArgMatches, config: &Config) -> error::Result<u64> { fn get_time_interval(matches: &clap::ArgMatches, config: &Config) -> error::Result<u64> {
let time_interval = if let Some(time_interval) = matches.value_of("time_delta") { let time_interval = if let Some(time_interval) = matches.value_of("time_delta") {
time_interval.parse::<u128>()? time_interval.parse::<u64>().map_err(|_| {
BottomError::ConfigError(
"could not parse as a valid 64-bit unsigned integer".to_string(),
)
})?
} else if let Some(flags) = &config.flags { } else if let Some(flags) = &config.flags {
if let Some(time_interval) = flags.time_delta { if let Some(time_interval) = flags.time_delta {
time_interval as u128 time_interval
} else { } else {
TIME_CHANGE_MILLISECONDS as u128 TIME_CHANGE_MILLISECONDS
} }
} else { } else {
TIME_CHANGE_MILLISECONDS as u128 TIME_CHANGE_MILLISECONDS
}; };
if time_interval < 1000 { if time_interval < 1000 {
return Err(BottomError::ConfigError( return Err(BottomError::ConfigError(
"set your time delta to be at least 1000 milliseconds.".to_string(), "set your time delta to be at least 1000 milliseconds.".to_string(),
)); ));
} else if time_interval > STALE_MAX_MILLISECONDS as u128 { } else if time_interval > STALE_MAX_MILLISECONDS {
return Err(BottomError::ConfigError(format!( return Err(BottomError::ConfigError(format!(
"set your time delta to be at most {} milliseconds.", "set your time delta to be at most {} milliseconds.",
STALE_MAX_MILLISECONDS STALE_MAX_MILLISECONDS
))); )));
} }
Ok(time_interval as u64) Ok(time_interval)
} }
pub fn get_app_grouping(matches: &clap::ArgMatches, config: &Config) -> bool { pub fn get_app_grouping(matches: &clap::ArgMatches, config: &Config) -> bool {
@ -853,20 +862,17 @@ fn get_default_widget_and_count(
} else if let Some(flags) = &config.flags { } else if let Some(flags) = &config.flags {
flags flags
.default_widget_count .default_widget_count
.map(|widget_count| widget_count as u128) .map(|widget_count| widget_count.into())
} else { } else {
None None
}; };
match (widget_type, widget_count) { match (widget_type, widget_count) {
(Some(widget_type), Some(widget_count)) => { (Some(widget_type), Some(widget_count)) => {
if widget_count > std::u64::MAX as u128 { let widget_count = widget_count.try_into().map_err(|_| BottomError::ConfigError(
Err(BottomError::ConfigError( "set your widget count to be at most unsigned INT_MAX.".to_string()
"set your widget count to be at most unsigned INT_MAX.".to_string(), ))?;
)) Ok((Some(widget_type), widget_count))
} else {
Ok((Some(widget_type), widget_count as u64))
}
} }
(Some(widget_type), None) => Ok((Some(widget_type), 1)), (Some(widget_type), None) => Ok((Some(widget_type), 1)),
(None, Some(_widget_count)) => Err(BottomError::ConfigError( (None, Some(_widget_count)) => Err(BottomError::ConfigError(

View File

@ -33,9 +33,7 @@ fn test_large_default_time() {
.arg("18446744073709551616") .arg("18446744073709551616")
.assert() .assert()
.failure() .failure()
.stderr(predicate::str::contains( .stderr(predicate::str::contains("could not parse"));
"set your default value to be at most",
));
} }
#[test] #[test]
@ -61,9 +59,7 @@ fn test_large_delta_time() {
.arg("18446744073709551616") .arg("18446744073709551616")
.assert() .assert()
.failure() .failure()
.stderr(predicate::str::contains( .stderr(predicate::str::contains("could not parse"));
"set your time delta to be at most",
));
} }
#[test] #[test]
@ -89,9 +85,7 @@ fn test_large_rate() {
.arg("18446744073709551616") .arg("18446744073709551616")
.assert() .assert()
.failure() .failure()
.stderr(predicate::str::contains( .stderr(predicate::str::contains("could not parse"));
"set your update rate to be at most unsigned INT_MAX.",
));
} }
#[test] #[test]
@ -118,7 +112,7 @@ fn test_invalid_rate() {
.arg("100-1000") .arg("100-1000")
.assert() .assert()
.failure() .failure()
.stderr(predicate::str::contains("invalid digit")); .stderr(predicate::str::contains("could not parse"));
} }
#[test] #[test]