refactor: remove once_cell (#1361)

* refactor: remove once_cell

* some missing fixes
This commit is contained in:
Clement Tsang 2023-12-23 04:35:42 -05:00 committed by GitHub
parent 854f3aed95
commit a1168cac67
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
8 changed files with 289 additions and 283 deletions

1
Cargo.lock generated
View file

@ -176,7 +176,6 @@ dependencies = [
"log", "log",
"mach2", "mach2",
"nvml-wrapper", "nvml-wrapper",
"once_cell",
"predicates", "predicates",
"ratatui", "ratatui",
"regex", "regex",

View file

@ -93,10 +93,7 @@ indexmap = "2.1.0"
itertools = "0.12.0" itertools = "0.12.0"
kstring = { version = "2.0.0", features = ["arc"] } kstring = { version = "2.0.0", features = ["arc"] }
log = { version = "0.4.20", optional = true } log = { version = "0.4.20", optional = true }
nvml-wrapper = { version = "0.9.0", optional = true, features = [ nvml-wrapper = { version = "0.9.0", optional = true, features = ["legacy-functions"] }
"legacy-functions",
] }
once_cell = "1.18.0"
regex = "1.10.2" regex = "1.10.2"
serde = { version = "=1.0.193", features = ["derive"] } serde = { version = "=1.0.193", features = ["derive"] }
starship-battery = { version = "0.8.2", optional = true } starship-battery = { version = "0.8.2", optional = true }
@ -136,9 +133,7 @@ filedescriptor = "0.8.2"
[dev-dependencies] [dev-dependencies]
assert_cmd = "2.0.12" assert_cmd = "2.0.12"
cargo-husky = { version = "1.5.0", default-features = false, features = [ cargo-husky = { version = "1.5.0", default-features = false, features = ["user-hooks"] }
"user-hooks",
] }
predicates = "3.0.3" predicates = "3.0.3"
[build-dependencies] [build-dependencies]

View file

@ -364,13 +364,12 @@ impl DataCollection {
let io_device = { let io_device = {
cfg_if::cfg_if! { cfg_if::cfg_if! {
if #[cfg(target_os = "macos")] { if #[cfg(target_os = "macos")] {
use once_cell::sync::Lazy; use std::sync::OnceLock;
use regex::Regex; use regex::Regex;
// Must trim one level further for macOS! // Must trim one level further for macOS!
static DISK_REGEX: Lazy<Regex> = static DISK_REGEX: OnceLock<Regex> = OnceLock::new();
Lazy::new(|| Regex::new(r"disk\d+").unwrap()); if let Some(new_name) = DISK_REGEX.get_or_init(|| Regex::new(r"disk\d+").unwrap()).find(checked_name) {
if let Some(new_name) = DISK_REGEX.find(checked_name) {
io.get(new_name.as_str()) io.get(new_name.as_str())
} else { } else {
None None

View file

@ -1,8 +1,9 @@
use std::sync::OnceLock;
use hashbrown::HashMap; use hashbrown::HashMap;
use nvml_wrapper::enum_wrappers::device::TemperatureSensor; use nvml_wrapper::enum_wrappers::device::TemperatureSensor;
use nvml_wrapper::enums::device::UsedGpuMemory; use nvml_wrapper::enums::device::UsedGpuMemory;
use nvml_wrapper::{error::NvmlError, Nvml}; use nvml_wrapper::{error::NvmlError, Nvml};
use once_cell::sync::Lazy;
use crate::app::Filter; use crate::app::Filter;
@ -10,7 +11,7 @@ use crate::app::layout_manager::UsedWidgets;
use crate::data_harvester::memory::MemHarvest; use crate::data_harvester::memory::MemHarvest;
use crate::data_harvester::temperature::{is_temp_filtered, TempHarvest, TemperatureType}; use crate::data_harvester::temperature::{is_temp_filtered, TempHarvest, TemperatureType};
pub static NVML_DATA: Lazy<Result<Nvml, NvmlError>> = Lazy::new(Nvml::init); pub static NVML_DATA: OnceLock<Result<Nvml, NvmlError>> = OnceLock::new();
pub struct GpusData { pub struct GpusData {
pub memory: Option<Vec<(String, MemHarvest)>>, pub memory: Option<Vec<(String, MemHarvest)>>,
@ -23,7 +24,7 @@ pub struct GpusData {
pub fn get_nvidia_vecs( pub fn get_nvidia_vecs(
temp_type: &TemperatureType, filter: &Option<Filter>, widgets_to_harvest: &UsedWidgets, temp_type: &TemperatureType, filter: &Option<Filter>, widgets_to_harvest: &UsedWidgets,
) -> Option<GpusData> { ) -> Option<GpusData> {
if let Ok(nvml) = &*NVML_DATA { if let Ok(nvml) = NVML_DATA.get_or_init(Nvml::init) {
if let Ok(num_gpu) = nvml.device_count() { if let Ok(num_gpu) = nvml.device_count() {
let mut temp_vec = Vec::with_capacity(num_gpu as usize); let mut temp_vec = Vec::with_capacity(num_gpu as usize);
let mut mem_vec = Vec::with_capacity(num_gpu as usize); let mut mem_vec = Vec::with_capacity(num_gpu as usize);

View file

@ -5,11 +5,11 @@ use std::{
fs::File, fs::File,
io::{self, BufRead, BufReader, Read}, io::{self, BufRead, BufReader, Read},
path::PathBuf, path::PathBuf,
sync::OnceLock,
}; };
use anyhow::anyhow; use anyhow::anyhow;
use libc::uid_t; use libc::uid_t;
use once_cell::sync::Lazy;
use rustix::{ use rustix::{
fd::OwnedFd, fd::OwnedFd,
fs::{Mode, OFlags}, fs::{Mode, OFlags},
@ -18,7 +18,7 @@ use rustix::{
use crate::Pid; use crate::Pid;
static PAGESIZE: Lazy<u64> = Lazy::new(|| rustix::param::page_size() as u64); static PAGESIZE: OnceLock<u64> = OnceLock::new();
#[inline] #[inline]
fn next_part<'a>(iter: &mut impl Iterator<Item = &'a str>) -> Result<&'a str, io::Error> { fn next_part<'a>(iter: &mut impl Iterator<Item = &'a str>) -> Result<&'a str, io::Error> {
@ -103,7 +103,7 @@ impl Stat {
/// Returns the Resident Set Size in bytes. /// Returns the Resident Set Size in bytes.
#[inline] #[inline]
pub fn rss_bytes(&self) -> u64 { pub fn rss_bytes(&self) -> u64 {
self.rss * *PAGESIZE self.rss * PAGESIZE.get_or_init(|| rustix::param::page_size() as u64)
} }
} }

View file

@ -132,19 +132,19 @@ impl CanvasStyling {
match colour_scheme { match colour_scheme {
ColourScheme::Default => {} ColourScheme::Default => {}
ColourScheme::DefaultLight => { ColourScheme::DefaultLight => {
canvas_colours.set_colours_from_palette(&DEFAULT_LIGHT_MODE_COLOUR_PALETTE)?; canvas_colours.set_colours_from_palette(&default_light_mode_colour_palette())?;
} }
ColourScheme::Gruvbox => { ColourScheme::Gruvbox => {
canvas_colours.set_colours_from_palette(&GRUVBOX_COLOUR_PALETTE)?; canvas_colours.set_colours_from_palette(&gruvbox_colour_palette())?;
} }
ColourScheme::GruvboxLight => { ColourScheme::GruvboxLight => {
canvas_colours.set_colours_from_palette(&GRUVBOX_LIGHT_COLOUR_PALETTE)?; canvas_colours.set_colours_from_palette(&gruvbox_light_colour_palette())?;
} }
ColourScheme::Nord => { ColourScheme::Nord => {
canvas_colours.set_colours_from_palette(&NORD_COLOUR_PALETTE)?; canvas_colours.set_colours_from_palette(&nord_colour_palette())?;
} }
ColourScheme::NordLight => { ColourScheme::NordLight => {
canvas_colours.set_colours_from_palette(&NORD_LIGHT_COLOUR_PALETTE)?; canvas_colours.set_colours_from_palette(&nord_light_colour_palette())?;
} }
ColourScheme::Custom => { ColourScheme::Custom => {
if let Some(colors) = &config.colors { if let Some(colors) = &config.colors {

View file

@ -1,4 +1,3 @@
use once_cell::sync::Lazy;
use tui::widgets::Borders; use tui::widgets::Borders;
use crate::options::ConfigColours; use crate::options::ConfigColours;
@ -23,13 +22,11 @@ pub const TIME_LABEL_HEIGHT_LIMIT: u16 = 7;
// Side borders // Side borders
pub const SIDE_BORDERS: Borders = Borders::LEFT.union(Borders::RIGHT); pub const SIDE_BORDERS: Borders = Borders::LEFT.union(Borders::RIGHT);
pub static DEFAULT_TEXT_STYLE: Lazy<tui::style::Style> =
Lazy::new(|| tui::style::Style::default().fg(tui::style::Color::Gray));
pub static DEFAULT_HEADER_STYLE: Lazy<tui::style::Style> =
Lazy::new(|| tui::style::Style::default().fg(tui::style::Color::LightBlue));
// Colour profiles // Colour profiles
pub static DEFAULT_LIGHT_MODE_COLOUR_PALETTE: Lazy<ConfigColours> = Lazy::new(|| ConfigColours { // TODO: Generate these with a macro or something...
pub fn default_light_mode_colour_palette() -> ConfigColours {
ConfigColours {
text_color: Some("black".into()), text_color: Some("black".into()),
border_color: Some("black".into()), border_color: Some("black".into()),
table_header_color: Some("black".into()), table_header_color: Some("black".into()),
@ -65,9 +62,11 @@ pub static DEFAULT_LIGHT_MODE_COLOUR_PALETTE: Lazy<ConfigColours> = Lazy::new(||
"Red".into(), "Red".into(),
]), ]),
..ConfigColours::default() ..ConfigColours::default()
}); }
}
pub static GRUVBOX_COLOUR_PALETTE: Lazy<ConfigColours> = Lazy::new(|| ConfigColours { pub fn gruvbox_colour_palette() -> ConfigColours {
ConfigColours {
table_header_color: Some("#83a598".into()), table_header_color: Some("#83a598".into()),
all_cpu_color: Some("#8ec07c".into()), all_cpu_color: Some("#8ec07c".into()),
avg_cpu_color: Some("#fb4934".into()), avg_cpu_color: Some("#fb4934".into()),
@ -122,9 +121,11 @@ pub static GRUVBOX_COLOUR_PALETTE: Lazy<ConfigColours> = Lazy::new(|| ConfigColo
high_battery_color: Some("#98971a".into()), high_battery_color: Some("#98971a".into()),
medium_battery_color: Some("#fabd2f".into()), medium_battery_color: Some("#fabd2f".into()),
low_battery_color: Some("#fb4934".into()), low_battery_color: Some("#fb4934".into()),
}); }
}
pub static GRUVBOX_LIGHT_COLOUR_PALETTE: Lazy<ConfigColours> = Lazy::new(|| ConfigColours { pub fn gruvbox_light_colour_palette() -> ConfigColours {
ConfigColours {
table_header_color: Some("#076678".into()), table_header_color: Some("#076678".into()),
all_cpu_color: Some("#8ec07c".into()), all_cpu_color: Some("#8ec07c".into()),
avg_cpu_color: Some("#fb4934".into()), avg_cpu_color: Some("#fb4934".into()),
@ -179,9 +180,11 @@ pub static GRUVBOX_LIGHT_COLOUR_PALETTE: Lazy<ConfigColours> = Lazy::new(|| Conf
high_battery_color: Some("#98971a".into()), high_battery_color: Some("#98971a".into()),
medium_battery_color: Some("#d79921".into()), medium_battery_color: Some("#d79921".into()),
low_battery_color: Some("#cc241d".into()), low_battery_color: Some("#cc241d".into()),
}); }
}
pub static NORD_COLOUR_PALETTE: Lazy<ConfigColours> = Lazy::new(|| ConfigColours { pub fn nord_colour_palette() -> ConfigColours {
ConfigColours {
table_header_color: Some("#81a1c1".into()), table_header_color: Some("#81a1c1".into()),
all_cpu_color: Some("#88c0d0".into()), all_cpu_color: Some("#88c0d0".into()),
avg_cpu_color: Some("#8fbcbb".into()), avg_cpu_color: Some("#8fbcbb".into()),
@ -224,9 +227,11 @@ pub static NORD_COLOUR_PALETTE: Lazy<ConfigColours> = Lazy::new(|| ConfigColours
high_battery_color: Some("#a3be8c".into()), high_battery_color: Some("#a3be8c".into()),
medium_battery_color: Some("#ebcb8b".into()), medium_battery_color: Some("#ebcb8b".into()),
low_battery_color: Some("#bf616a".into()), low_battery_color: Some("#bf616a".into()),
}); }
}
pub static NORD_LIGHT_COLOUR_PALETTE: Lazy<ConfigColours> = Lazy::new(|| ConfigColours { pub fn nord_light_colour_palette() -> ConfigColours {
ConfigColours {
table_header_color: Some("#5e81ac".into()), table_header_color: Some("#5e81ac".into()),
all_cpu_color: Some("#81a1c1".into()), all_cpu_color: Some("#81a1c1".into()),
avg_cpu_color: Some("#8fbcbb".into()), avg_cpu_color: Some("#8fbcbb".into()),
@ -269,7 +274,8 @@ pub static NORD_LIGHT_COLOUR_PALETTE: Lazy<ConfigColours> = Lazy::new(|| ConfigC
high_battery_color: Some("#a3be8c".into()), high_battery_color: Some("#a3be8c".into()),
medium_battery_color: Some("#ebcb8b".into()), medium_battery_color: Some("#ebcb8b".into()),
low_battery_color: Some("#bf616a".into()), low_battery_color: Some("#bf616a".into()),
}); }
}
// Help text // Help text
pub const HELP_CONTENTS_TEXT: [&str; 10] = [ pub const HELP_CONTENTS_TEXT: [&str; 10] = [

View file

@ -1,5 +1,16 @@
#[cfg(feature = "logging")] #[cfg(feature = "logging")]
pub static OFFSET: once_cell::sync::Lazy<time::UtcOffset> = once_cell::sync::Lazy::new(|| { use std::sync::OnceLock;
#[cfg(feature = "logging")]
pub static OFFSET: OnceLock<time::UtcOffset> = OnceLock::new();
#[cfg(feature = "logging")]
pub fn init_logger(
min_level: log::LevelFilter, debug_file_name: Option<&std::ffi::OsStr>,
) -> Result<(), fern::InitError> {
let dispatch = fern::Dispatch::new()
.format(|out, message, record| {
let offset = OFFSET.get_or_init(|| {
use time::util::local_offset::Soundness; use time::util::local_offset::Soundness;
// SAFETY: We only invoke this once, quickly, and it should be invoked in a single-thread context. // SAFETY: We only invoke this once, quickly, and it should be invoked in a single-thread context.
@ -11,22 +22,17 @@ pub static OFFSET: once_cell::sync::Lazy<time::UtcOffset> = once_cell::sync::Laz
// mode when specifically using certain feature flags (e.g. dev-logging feature enables this behaviour). // mode when specifically using certain feature flags (e.g. dev-logging feature enables this behaviour).
time::util::local_offset::set_soundness(Soundness::Unsound); time::util::local_offset::set_soundness(Soundness::Unsound);
let res = time::UtcOffset::current_local_offset().unwrap_or(time::UtcOffset::UTC); let res =
time::UtcOffset::current_local_offset().unwrap_or(time::UtcOffset::UTC);
time::util::local_offset::set_soundness(Soundness::Sound); time::util::local_offset::set_soundness(Soundness::Sound);
res res
} }
}); });
#[cfg(feature = "logging")]
pub fn init_logger(
min_level: log::LevelFilter, debug_file_name: Option<&std::ffi::OsStr>,
) -> Result<(), fern::InitError> {
let dispatch = fern::Dispatch::new()
.format(|out, message, record| {
let offset_time = { let offset_time = {
let utc = time::OffsetDateTime::now_utc(); let utc = time::OffsetDateTime::now_utc();
utc.checked_to_offset(*OFFSET).unwrap_or(utc) utc.checked_to_offset(*offset).unwrap_or(utc)
}; };
out.finish(format_args!( out.finish(format_args!(