other: Switch to once_cell (#324)

Switch from lazy_static to once_cell.
This commit is contained in:
Clement Tsang 2020-11-22 13:44:40 -08:00 committed by GitHub
parent 5abb1ce1a3
commit 6aa0dd64a6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
12 changed files with 233 additions and 211 deletions

2
Cargo.lock generated
View File

@ -125,9 +125,9 @@ dependencies = [
"heim", "heim",
"indexmap", "indexmap",
"itertools", "itertools",
"lazy_static",
"libc", "libc",
"log", "log",
"once_cell",
"predicates", "predicates",
"regex", "regex",
"serde", "serde",

View File

@ -35,8 +35,8 @@ dirs-next = "2.0.0"
futures = "0.3.8" futures = "0.3.8"
indexmap = "1.6.0" indexmap = "1.6.0"
itertools = "0.9.0" itertools = "0.9.0"
lazy_static = "1.4.0"
libc = "0.2" libc = "0.2"
once_cell = "1.5.2"
regex = "1.4.2" regex = "1.4.2"
serde = {version = "1.0", features = ["derive"] } serde = {version = "1.0", features = ["derive"] }
sysinfo = "0.15.3" sysinfo = "0.15.3"

View File

@ -1,4 +1,3 @@
use lazy_static::lazy_static;
/// In charge of cleaning, processing, and managing data. I couldn't think of /// In charge of cleaning, processing, and managing data. I couldn't think of
/// a better name for the file. Since I called data collection "harvesting", /// a better name for the file. Since I called data collection "harvesting",
/// then this is the farmer I guess. /// then this is the farmer I guess.
@ -13,6 +12,8 @@ use lazy_static::lazy_static;
/// call the purging function. Failure to do so *will* result in a growing /// call the purging function. Failure to do so *will* result in a growing
/// memory usage and higher CPU usage - you will be trying to process more and /// memory usage and higher CPU usage - you will be trying to process more and
/// more points as this is used! /// more points as this is used!
use once_cell::sync::Lazy;
use std::{time::Instant, vec::Vec}; use std::{time::Instant, vec::Vec};
use crate::{ use crate::{
@ -245,9 +246,7 @@ impl DataCollection {
if let Some(trim) = device.name.split('/').last() { if let Some(trim) = device.name.split('/').last() {
let io_device = if cfg!(target_os = "macos") { let io_device = if cfg!(target_os = "macos") {
// Must trim one level further! // Must trim one level further!
lazy_static! { static DISK_REGEX: Lazy<Regex> = Lazy::new(|| Regex::new(r"disk\d+").unwrap());
static ref DISK_REGEX: Regex = Regex::new(r"disk\d+").unwrap();
}
if let Some(disk_trim) = DISK_REGEX.find(trim) { if let Some(disk_trim) = DISK_REGEX.find(trim) {
io.get(disk_trim.as_str()) io.get(disk_trim.as_str())
} else { } else {

View File

@ -11,7 +11,7 @@ use std::collections::{hash_map::RandomState, HashMap};
#[cfg(not(target_os = "linux"))] #[cfg(not(target_os = "linux"))]
use sysinfo::{ProcessExt, ProcessorExt, System, SystemExt}; use sysinfo::{ProcessExt, ProcessorExt, System, SystemExt};
/// Maximum character length of a /proc/<PID>/stat process name. /// Maximum character length of a /proc/<PID>/stat process name that we'll accept.
#[cfg(target_os = "linux")] #[cfg(target_os = "linux")]
const MAX_STAT_NAME_LEN: usize = 15; const MAX_STAT_NAME_LEN: usize = 15;

View File

@ -1,4 +1,4 @@
use lazy_static::lazy_static; use once_cell::sync::Lazy;
use std::collections::HashMap; use std::collections::HashMap;
use tui::style::{Color, Style}; use tui::style::{Color, Style};
@ -14,8 +14,8 @@ pub const STANDARD_HIGHLIGHT_COLOUR: Color = Color::LightBlue;
pub const AVG_COLOUR: Color = Color::Red; pub const AVG_COLOUR: Color = Color::Red;
pub const ALL_COLOUR: Color = Color::Green; pub const ALL_COLOUR: Color = Color::Green;
lazy_static! { static COLOR_NAME_LOOKUP_TABLE: Lazy<HashMap<&'static str, Color>> = Lazy::new(|| {
static ref COLOR_NAME_LOOKUP_TABLE: HashMap<&'static str, Color> = [ [
("reset", Color::Reset), ("reset", Color::Reset),
("black", Color::Black), ("black", Color::Black),
("red", Color::Red), ("red", Color::Red),
@ -33,12 +33,12 @@ lazy_static! {
("lightblue", Color::LightBlue), ("lightblue", Color::LightBlue),
("lightmagenta", Color::LightMagenta), ("lightmagenta", Color::LightMagenta),
("lightcyan", Color::LightCyan), ("lightcyan", Color::LightCyan),
("white", Color::White) ("white", Color::White),
] ]
.iter() .iter()
.copied() .copied()
.collect(); .collect()
} });
pub fn convert_hex_to_color(hex: &str) -> error::Result<Color> { pub fn convert_hex_to_color(hex: &str) -> error::Result<Color> {
fn hex_err(hex: &str) -> error::Result<u8> { fn hex_err(hex: &str) -> error::Result<u8> {

View File

@ -1,4 +1,4 @@
use lazy_static::lazy_static; use once_cell::sync::Lazy;
use std::borrow::Cow; use std::borrow::Cow;
use unicode_segmentation::UnicodeSegmentation; use unicode_segmentation::UnicodeSegmentation;
@ -26,12 +26,12 @@ const CPU_LEGEND_HEADER: [&str; 2] = ["CPU", "Use%"];
const AVG_POSITION: usize = 1; const AVG_POSITION: usize = 1;
const ALL_POSITION: usize = 0; const ALL_POSITION: usize = 0;
lazy_static! { static CPU_LEGEND_HEADER_LENS: Lazy<Vec<u16>> = Lazy::new(|| {
static ref CPU_LEGEND_HEADER_LENS: Vec<u16> = CPU_LEGEND_HEADER CPU_LEGEND_HEADER
.iter() .iter()
.map(|entry| entry.len() as u16) .map(|entry| entry.len() as u16)
.collect::<Vec<_>>(); .collect::<Vec<_>>()
} });
pub trait CpuGraphWidget { pub trait CpuGraphWidget {
fn draw_cpu<B: Backend>( fn draw_cpu<B: Backend>(

View File

@ -1,4 +1,4 @@
use lazy_static::lazy_static; use once_cell::sync::Lazy;
use tui::{ use tui::{
backend::Backend, backend::Backend,
layout::{Constraint, Direction, Layout, Rect}, layout::{Constraint, Direction, Layout, Rect},
@ -21,12 +21,12 @@ use unicode_segmentation::UnicodeSegmentation;
const DISK_HEADERS: [&str; 7] = ["Disk", "Mount", "Used", "Free", "Total", "R/s", "W/s"]; const DISK_HEADERS: [&str; 7] = ["Disk", "Mount", "Used", "Free", "Total", "R/s", "W/s"];
lazy_static! { static DISK_HEADERS_LENS: Lazy<Vec<u16>> = Lazy::new(|| {
static ref DISK_HEADERS_LENS: Vec<u16> = DISK_HEADERS DISK_HEADERS
.iter() .iter()
.map(|entry| entry.len() as u16) .map(|entry| entry.len() as u16)
.collect::<Vec<_>>(); .collect::<Vec<_>>()
} });
pub trait DiskTableWidget { pub trait DiskTableWidget {
fn draw_disk_table<B: Backend>( fn draw_disk_table<B: Backend>(

View File

@ -1,4 +1,4 @@
use lazy_static::lazy_static; use once_cell::sync::Lazy;
use std::cmp::max; use std::cmp::max;
use unicode_segmentation::UnicodeSegmentation; use unicode_segmentation::UnicodeSegmentation;
@ -21,12 +21,12 @@ use tui::{
const NETWORK_HEADERS: [&str; 4] = ["RX", "TX", "Total RX", "Total TX"]; const NETWORK_HEADERS: [&str; 4] = ["RX", "TX", "Total RX", "Total TX"];
lazy_static! { static NETWORK_HEADERS_LENS: Lazy<Vec<u16>> = Lazy::new(|| {
static ref NETWORK_HEADERS_LENS: Vec<u16> = NETWORK_HEADERS NETWORK_HEADERS
.iter() .iter()
.map(|entry| entry.len() as u16) .map(|entry| entry.len() as u16)
.collect::<Vec<_>>(); .collect::<Vec<_>>()
} });
pub trait NetworkGraphWidget { pub trait NetworkGraphWidget {
fn draw_network<B: Backend>( fn draw_network<B: Backend>(

View File

@ -19,6 +19,81 @@ use std::borrow::Cow;
use unicode_segmentation::{GraphemeIndices, UnicodeSegmentation}; use unicode_segmentation::{GraphemeIndices, UnicodeSegmentation};
use unicode_width::UnicodeWidthStr; use unicode_width::UnicodeWidthStr;
use once_cell::sync::Lazy;
static PROCESS_HEADERS_HARD_WIDTH_NO_GROUP: Lazy<Vec<Option<u16>>> = Lazy::new(|| {
vec![
Some(7),
None,
Some(8),
Some(8),
Some(8),
Some(8),
Some(7),
Some(8),
]
});
static PROCESS_HEADERS_HARD_WIDTH_GROUPED: Lazy<Vec<Option<u16>>> = Lazy::new(|| {
vec![
Some(7),
None,
Some(8),
Some(8),
Some(8),
Some(8),
Some(7),
Some(8),
None,
]
});
static PROCESS_HEADERS_SOFT_WIDTH_MAX_GROUPED_COMMAND: Lazy<Vec<Option<f64>>> =
Lazy::new(|| vec![None, Some(0.7), None, None, None, None, None, None]);
static PROCESS_HEADERS_SOFT_WIDTH_MAX_GROUPED_TREE: Lazy<Vec<Option<f64>>> =
Lazy::new(|| vec![None, Some(0.5), None, None, None, None, None, None]);
static PROCESS_HEADERS_SOFT_WIDTH_MAX_GROUPED_ELSE: Lazy<Vec<Option<f64>>> =
Lazy::new(|| vec![None, Some(0.4), None, None, None, None, None, None]);
static PROCESS_HEADERS_SOFT_WIDTH_MAX_NO_GROUP_COMMAND: Lazy<Vec<Option<f64>>> = Lazy::new(|| {
vec![
None,
Some(0.7),
None,
None,
None,
None,
None,
None,
Some(0.2),
]
});
static PROCESS_HEADERS_SOFT_WIDTH_MAX_NO_GROUP_TREE: Lazy<Vec<Option<f64>>> = Lazy::new(|| {
vec![
None,
Some(0.5),
None,
None,
None,
None,
None,
None,
Some(0.2),
]
});
static PROCESS_HEADERS_SOFT_WIDTH_MAX_NO_GROUP_ELSE: Lazy<Vec<Option<f64>>> = Lazy::new(|| {
vec![
None,
Some(0.3),
None,
None,
None,
None,
None,
None,
Some(0.2),
]
});
pub trait ProcessTableWidget { pub trait ProcessTableWidget {
/// Draws and handles all process-related drawing. Use this. /// Draws and handles all process-related drawing. Use this.
/// - `widget_id` here represents the widget ID of the process widget itself! /// - `widget_id` here represents the widget ID of the process widget itself!
@ -222,28 +297,9 @@ impl ProcessTableWidget for Painter {
// Calculate widths // Calculate widths
let hard_widths = if proc_widget_state.is_grouped { let hard_widths = if proc_widget_state.is_grouped {
vec![ &*PROCESS_HEADERS_HARD_WIDTH_GROUPED
Some(7),
None,
Some(8),
Some(8),
Some(8),
Some(8),
Some(7),
Some(8),
]
} else { } else {
vec![ &*PROCESS_HEADERS_HARD_WIDTH_NO_GROUP
Some(7),
None,
Some(8),
Some(8),
Some(8),
Some(8),
Some(7),
Some(8),
None,
]
}; };
if recalculate_column_widths { if recalculate_column_widths {
@ -274,7 +330,7 @@ impl ProcessTableWidget for Painter {
.table_width_state .table_width_state
.desired_column_widths .desired_column_widths
.iter() .iter()
.zip(&hard_widths) .zip(hard_widths)
.map(|(current, hard)| { .map(|(current, hard)| {
if let Some(hard) = hard { if let Some(hard) = hard {
if *hard > *current { if *hard > *current {
@ -290,48 +346,18 @@ impl ProcessTableWidget for Painter {
let soft_widths_max = if proc_widget_state.is_grouped { let soft_widths_max = if proc_widget_state.is_grouped {
if proc_widget_state.is_using_command { if proc_widget_state.is_using_command {
vec![None, Some(0.7), None, None, None, None, None, None] &*PROCESS_HEADERS_SOFT_WIDTH_MAX_GROUPED_COMMAND
} else if proc_widget_state.is_tree_mode { } else if proc_widget_state.is_tree_mode {
vec![None, Some(0.5), None, None, None, None, None, None] &*PROCESS_HEADERS_SOFT_WIDTH_MAX_GROUPED_TREE
} else { } else {
vec![None, Some(0.4), None, None, None, None, None, None] &*PROCESS_HEADERS_SOFT_WIDTH_MAX_GROUPED_ELSE
} }
} else if proc_widget_state.is_using_command { } else if proc_widget_state.is_using_command {
vec![ &*PROCESS_HEADERS_SOFT_WIDTH_MAX_NO_GROUP_COMMAND
None,
Some(0.7),
None,
None,
None,
None,
None,
None,
Some(0.2),
]
} else if proc_widget_state.is_tree_mode { } else if proc_widget_state.is_tree_mode {
vec![ &*PROCESS_HEADERS_SOFT_WIDTH_MAX_NO_GROUP_TREE
None,
Some(0.5),
None,
None,
None,
None,
None,
None,
Some(0.2),
]
} else { } else {
vec![ &*PROCESS_HEADERS_SOFT_WIDTH_MAX_NO_GROUP_ELSE
None,
Some(0.3),
None,
None,
None,
None,
None,
None,
Some(0.2),
]
}; };
proc_widget_state.table_width_state.calculated_column_widths = proc_widget_state.table_width_state.calculated_column_widths =
@ -339,7 +365,7 @@ impl ProcessTableWidget for Painter {
draw_loc.width, draw_loc.width,
&hard_widths, &hard_widths,
&soft_widths_min, &soft_widths_min,
&soft_widths_max, soft_widths_max,
&(proc_widget_state &(proc_widget_state
.table_width_state .table_width_state
.desired_column_widths .desired_column_widths
@ -363,7 +389,7 @@ impl ProcessTableWidget for Painter {
let ccw = &proc_widget_state.table_width_state.calculated_column_widths; let ccw = &proc_widget_state.table_width_state.calculated_column_widths;
let process_rows = sliced_vec.iter().map(|(data, disabled)| { let process_rows = sliced_vec.iter().map(|(data, disabled)| {
let truncated_data = data.iter().zip(&hard_widths).enumerate().map( let truncated_data = data.iter().zip(hard_widths).enumerate().map(
|(itx, ((entry, alternative), width))| { |(itx, ((entry, alternative), width))| {
if let (Some(desired_col_width), Some(calculated_col_width)) = if let (Some(desired_col_width), Some(calculated_col_width)) =
(dcw.get(itx), ccw.get(itx)) (dcw.get(itx), ccw.get(itx))

View File

@ -1,4 +1,4 @@
use lazy_static::lazy_static; use once_cell::sync::Lazy;
use tui::{ use tui::{
backend::Backend, backend::Backend,
layout::{Constraint, Direction, Layout, Rect}, layout::{Constraint, Direction, Layout, Rect},
@ -21,12 +21,13 @@ use unicode_segmentation::UnicodeSegmentation;
const TEMP_HEADERS: [&str; 2] = ["Sensor", "Temp"]; const TEMP_HEADERS: [&str; 2] = ["Sensor", "Temp"];
lazy_static! { static TEMP_HEADERS_LENS: Lazy<Vec<u16>> = Lazy::new(|| {
static ref TEMP_HEADERS_LENS: Vec<u16> = TEMP_HEADERS TEMP_HEADERS
.iter() .iter()
.map(|entry| entry.len() as u16) .map(|entry| entry.len() as u16)
.collect::<Vec<_>>(); .collect::<Vec<_>>()
} });
pub trait TempTableWidget { pub trait TempTableWidget {
fn draw_temp_table<B: Backend>( fn draw_temp_table<B: Backend>(
&self, f: &mut Frame<'_, B>, app_state: &mut app::App, draw_loc: Rect, draw_border: bool, &self, f: &mut Frame<'_, B>, app_state: &mut app::App, draw_loc: Rect, draw_border: bool,

View File

@ -1,6 +1,5 @@
use lazy_static::lazy_static;
use crate::options::ConfigColours; use crate::options::ConfigColours;
use once_cell::sync::Lazy;
// Default widget ID // Default widget ID
pub const DEFAULT_WIDGET_ID: u64 = 56709; pub const DEFAULT_WIDGET_ID: u64 = 56709;
@ -24,22 +23,19 @@ pub const TABLE_GAP_HEIGHT_LIMIT: u16 = 7;
pub const TIME_LABEL_HEIGHT_LIMIT: u16 = 7; pub const TIME_LABEL_HEIGHT_LIMIT: u16 = 7;
// Side borders // Side borders
lazy_static! { pub static SIDE_BORDERS: Lazy<tui::widgets::Borders> =
pub static ref SIDE_BORDERS: tui::widgets::Borders = Lazy::new(|| tui::widgets::Borders::from_bits_truncate(20));
tui::widgets::Borders::from_bits_truncate(20); pub static TOP_LEFT_RIGHT: Lazy<tui::widgets::Borders> =
pub static ref TOP_LEFT_RIGHT: tui::widgets::Borders = Lazy::new(|| tui::widgets::Borders::from_bits_truncate(22));
tui::widgets::Borders::from_bits_truncate(22); pub static BOTTOM_LEFT_RIGHT: Lazy<tui::widgets::Borders> =
pub static ref BOTTOM_LEFT_RIGHT: tui::widgets::Borders = Lazy::new(|| tui::widgets::Borders::from_bits_truncate(28));
tui::widgets::Borders::from_bits_truncate(28); pub static DEFAULT_TEXT_STYLE: Lazy<tui::style::Style> =
pub static ref DEFAULT_TEXT_STYLE: tui::style::Style = Lazy::new(|| tui::style::Style::default().fg(tui::style::Color::Gray));
tui::style::Style::default().fg(tui::style::Color::Gray); pub static DEFAULT_HEADER_STYLE: Lazy<tui::style::Style> =
pub static ref DEFAULT_HEADER_STYLE: tui::style::Style = Lazy::new(|| tui::style::Style::default().fg(tui::style::Color::LightBlue));
tui::style::Style::default().fg(tui::style::Color::LightBlue);
}
// Colour profiles // Colour profiles
lazy_static! { pub static DEFAULT_LIGHT_MODE_COLOUR_PALETTE: Lazy<ConfigColours> = Lazy::new(|| ConfigColours {
pub static ref DEFAULT_LIGHT_MODE_COLOUR_PALETTE: ConfigColours = ConfigColours {
text_color: Some("black".to_string()), text_color: Some("black".to_string()),
border_color: Some("black".to_string()), border_color: Some("black".to_string()),
table_header_color: Some("black".to_string()), table_header_color: Some("black".to_string()),
@ -48,8 +44,8 @@ lazy_static! {
graph_color: Some("black".to_string()), graph_color: Some("black".to_string()),
disabled_text_color: Some("gray".to_string()), disabled_text_color: Some("gray".to_string()),
..ConfigColours::default() ..ConfigColours::default()
}; });
pub static ref GRUVBOX_COLOUR_PALETTE: ConfigColours = ConfigColours { pub static GRUVBOX_COLOUR_PALETTE: Lazy<ConfigColours> = Lazy::new(|| ConfigColours {
table_header_color: Some("#83a598".to_string()), table_header_color: Some("#83a598".to_string()),
all_cpu_color: Some("#8ec07c".to_string()), all_cpu_color: Some("#8ec07c".to_string()),
avg_cpu_color: Some("#fb4934".to_string()), avg_cpu_color: Some("#fb4934".to_string()),
@ -91,9 +87,9 @@ lazy_static! {
graph_color: Some("#ebdbb2".to_string()), graph_color: Some("#ebdbb2".to_string()),
high_battery_color: Some("#98971a".to_string()), high_battery_color: Some("#98971a".to_string()),
medium_battery_color: Some("#fabd2f".to_string()), medium_battery_color: Some("#fabd2f".to_string()),
low_battery_color: Some("#fb4934".to_string()) low_battery_color: Some("#fb4934".to_string()),
}; });
pub static ref GRUVBOX_LIGHT_COLOUR_PALETTE: ConfigColours = ConfigColours { pub static GRUVBOX_LIGHT_COLOUR_PALETTE: Lazy<ConfigColours> = Lazy::new(|| ConfigColours {
table_header_color: Some("#076678".to_string()), table_header_color: Some("#076678".to_string()),
all_cpu_color: Some("#8ec07c".to_string()), all_cpu_color: Some("#8ec07c".to_string()),
avg_cpu_color: Some("#fb4934".to_string()), avg_cpu_color: Some("#fb4934".to_string()),
@ -135,9 +131,8 @@ lazy_static! {
graph_color: Some("#3c3836".to_string()), graph_color: Some("#3c3836".to_string()),
high_battery_color: Some("#98971a".to_string()), high_battery_color: Some("#98971a".to_string()),
medium_battery_color: Some("#d79921".to_string()), medium_battery_color: Some("#d79921".to_string()),
low_battery_color: Some("#cc241d".to_string()) low_battery_color: Some("#cc241d".to_string()),
}; });
}
// Help text // Help text
pub const HELP_CONTENTS_TEXT: [&str; 8] = [ pub const HELP_CONTENTS_TEXT: [&str; 8] = [
@ -277,8 +272,8 @@ pub const BASIC_MEM_HELP_TEXT: [&str; 2] = [
"% Toggle between values and percentages for memory usage", "% Toggle between values and percentages for memory usage",
]; ];
lazy_static! { pub static HELP_TEXT: Lazy<Vec<Vec<&'static str>>> = Lazy::new(|| {
pub static ref HELP_TEXT: Vec<Vec<&'static str>> = vec![ vec![
HELP_CONTENTS_TEXT.to_vec(), HELP_CONTENTS_TEXT.to_vec(),
GENERAL_HELP_TEXT.to_vec(), GENERAL_HELP_TEXT.to_vec(),
CPU_HELP_TEXT.to_vec(), CPU_HELP_TEXT.to_vec(),
@ -287,8 +282,8 @@ lazy_static! {
SORT_HELP_TEXT.to_vec(), SORT_HELP_TEXT.to_vec(),
BATTERY_HELP_TEXT.to_vec(), BATTERY_HELP_TEXT.to_vec(),
BASIC_MEM_HELP_TEXT.to_vec(), BASIC_MEM_HELP_TEXT.to_vec(),
]; ]
} });
// Default layouts // Default layouts
pub const DEFAULT_LAYOUT: &str = r##" pub const DEFAULT_LAYOUT: &str = r##"

View File

@ -62,6 +62,7 @@ pub struct ConvertedProcessData {
pub tw_f64: f64, pub tw_f64: f64,
pub process_state: String, pub process_state: String,
pub process_char: char, pub process_char: char,
/// Prefix printed before the process when displayed. /// Prefix printed before the process when displayed.
pub process_description_prefix: Option<String>, pub process_description_prefix: Option<String>,
/// Whether to mark this process entry as disabled (mostly for tree mode). /// Whether to mark this process entry as disabled (mostly for tree mode).