Replace lazy_static with once_cell

This commit is contained in:
elkowar 2021-07-29 15:30:00 +02:00
parent ec4506d9e4
commit 41093cf0af
No known key found for this signature in database
GPG key ID: E321AD71B1D1F27F
12 changed files with 42 additions and 46 deletions

6
Cargo.lock generated
View file

@ -451,13 +451,13 @@ dependencies = [
"gtk-layer-shell", "gtk-layer-shell",
"gtk-layer-shell-sys", "gtk-layer-shell-sys",
"itertools 0.10.1", "itertools 0.10.1",
"lazy_static",
"libc", "libc",
"log", "log",
"maplit", "maplit",
"nix", "nix",
"notify", "notify",
"num", "num",
"once_cell",
"pretty_assertions", "pretty_assertions",
"pretty_env_logger", "pretty_env_logger",
"regex", "regex",
@ -1889,9 +1889,9 @@ dependencies = [
"itertools 0.10.1", "itertools 0.10.1",
"lalrpop", "lalrpop",
"lalrpop-util", "lalrpop-util",
"lazy_static",
"logos", "logos",
"maplit", "maplit",
"once_cell",
"regex", "regex",
"serde", "serde",
"serde_json", "serde_json",
@ -2391,8 +2391,8 @@ dependencies = [
"itertools 0.10.1", "itertools 0.10.1",
"lalrpop", "lalrpop",
"lalrpop-util", "lalrpop-util",
"lazy_static",
"maplit", "maplit",
"once_cell",
"pretty_assertions", "pretty_assertions",
"regex", "regex",
"serde", "serde",

View file

@ -5,3 +5,6 @@ members = [
"crates/yuck", "crates/yuck",
"crates/eww_shared_util" "crates/eww_shared_util"
] ]
[profile.dev]
split-debuginfo = "unpacked"

View file

@ -3,7 +3,7 @@ name = "eww"
version = "0.1.0" version = "0.1.0"
authors = ["elkowar <5300871+elkowar@users.noreply.github.com>"] authors = ["elkowar <5300871+elkowar@users.noreply.github.com>"]
edition = "2018" edition = "2018"
description= "Widget system for everyone!" description = "Widget system for everyone!"
license = "MIT" license = "MIT"
repository = "https://github.com/elkowar/eww" repository = "https://github.com/elkowar/eww"
homepage = "https://github.com/elkowar/eww" homepage = "https://github.com/elkowar/eww"
@ -44,8 +44,8 @@ itertools = "0.10"
debug_stub_derive = "0.3" debug_stub_derive = "0.3"
log = "0.4" log = "0.4"
pretty_env_logger = "0.4" pretty_env_logger = "0.4"
lazy_static = "1.4.0"
libc = "0.2" libc = "0.2"
once_cell = "1.8"
nix = "0.20" nix = "0.20"
smart-default = "0.6" smart-default = "0.6"
simple-signal = "1.1" simple-signal = "1.1"

View file

@ -3,11 +3,10 @@
//! `recv_exit()` function which can be awaited to receive an event in case of application termination. //! `recv_exit()` function which can be awaited to receive an event in case of application termination.
use anyhow::*; use anyhow::*;
use once_cell::sync::Lazy;
use tokio::sync::broadcast; use tokio::sync::broadcast;
lazy_static::lazy_static! { pub static APPLICATION_EXIT_SENDER: Lazy<broadcast::Sender<()>> = Lazy::new(|| broadcast::channel(2).0);
static ref APPLICATION_EXIT_SENDER: broadcast::Sender<()> = broadcast::channel(2).0;
}
/// Notify all listening tasks of the termination of the eww application process. /// Notify all listening tasks of the termination of the eww application process.
pub fn send_exit() -> Result<()> { pub fn send_exit() -> Result<()> {

View file

@ -1,13 +1,11 @@
use crate::util::IterAverage; use crate::util::IterAverage;
use anyhow::*; use anyhow::*;
use itertools::Itertools; use itertools::Itertools;
use lazy_static::lazy_static; use once_cell::sync::Lazy;
use std::{fs::read_to_string, sync::Mutex}; use std::{fs::read_to_string, sync::Mutex};
use sysinfo::{ComponentExt, DiskExt, NetworkExt, NetworksExt, ProcessorExt, System, SystemExt}; use sysinfo::{ComponentExt, DiskExt, NetworkExt, NetworksExt, ProcessorExt, System, SystemExt};
lazy_static! { static SYSTEM: Lazy<Mutex<System>> = Lazy::new(|| Mutex::new(System::new()));
static ref SYSTEM: Mutex<System> = Mutex::new(System::new());
}
pub fn disk() -> String { pub fn disk() -> String {
let mut c = SYSTEM.lock().unwrap(); let mut c = SYSTEM.lock().unwrap();
@ -63,7 +61,6 @@ pub fn get_avg_cpu_usage() -> String {
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
pub fn get_battery_capacity() -> Result<String> { pub fn get_battery_capacity() -> Result<String> {
use regex::Regex;
let capacity = String::from_utf8( let capacity = String::from_utf8(
std::process::Command::new("pmset") std::process::Command::new("pmset")
.args(&["-g", "batt"]) .args(&["-g", "batt"])
@ -75,7 +72,7 @@ pub fn get_battery_capacity() -> Result<String> {
// Example output of that command: // Example output of that command:
// Now drawing from 'Battery Power' // Now drawing from 'Battery Power'
//-InternalBattery-0 (id=11403363) 100%; discharging; (no estimate) present: true //-InternalBattery-0 (id=11403363) 100%; discharging; (no estimate) present: true
let regex = Regex::new(r"[0-9]*%")?; let regex = regex!(r"[0-9]*%");
let mut number = regex.captures(&capacity).unwrap().get(0).unwrap().as_str().to_string(); let mut number = regex.captures(&capacity).unwrap().get(0).unwrap().as_str().to_string();
// Removes the % at the end // Removes the % at the end

View file

@ -5,14 +5,13 @@ use codespan_reporting::{
term::{self, Chars}, term::{self, Chars},
}; };
use eww_shared_util::Span; use eww_shared_util::Span;
use once_cell::sync::Lazy;
use simplexpr::eval::EvalError; use simplexpr::eval::EvalError;
use yuck::{config::file_provider::YuckFiles, error::AstError, format_diagnostic::ToDiagnostic, gen_diagnostic}; use yuck::{config::file_provider::YuckFiles, error::AstError, format_diagnostic::ToDiagnostic, gen_diagnostic};
use crate::error::DiagError; use crate::error::DiagError;
lazy_static::lazy_static! { pub static ERROR_HANDLING_CTX: Lazy<Arc<Mutex<YuckFiles>>> = Lazy::new(|| Arc::new(Mutex::new(YuckFiles::new())));
pub static ref ERROR_HANDLING_CTX: Arc<Mutex<YuckFiles>> = Arc::new(Mutex::new(YuckFiles::new()));
}
pub fn clear_files() { pub fn clear_files() {
*ERROR_HANDLING_CTX.lock().unwrap() = YuckFiles::new(); *ERROR_HANDLING_CTX.lock().unwrap() = YuckFiles::new();

View file

@ -33,6 +33,14 @@ macro_rules! loop_select {
} }
} }
#[macro_export]
macro_rules! regex {
($re:literal $(,)?) => {{
static RE: once_cell::sync::OnceCell<regex::Regex> = once_cell::sync::OnceCell::new();
RE.get_or_init(|| regex::Regex::new($re).unwrap())
}};
}
/// Parse a string with a concrete set of options into some data-structure, /// Parse a string with a concrete set of options into some data-structure,
/// and return a nicely formatted error message on invalid values. I.e.: /// and return a nicely formatted error message on invalid values. I.e.:
/// ```rs /// ```rs
@ -142,10 +150,7 @@ impl<I: Iterator<Item = f32>> IterAverage for I {
/// by the actual env-variables. If the env-var isn't found, will replace the /// by the actual env-variables. If the env-var isn't found, will replace the
/// reference with an empty string. /// reference with an empty string.
pub fn replace_env_var_references(input: String) -> String { pub fn replace_env_var_references(input: String) -> String {
lazy_static::lazy_static! { regex!(r"\$\{([^\s]*)\}")
static ref ENV_VAR_PATTERN: regex::Regex = regex::Regex::new(r"\$\{([^\s]*)\}").unwrap();
}
ENV_VAR_PATTERN
.replace_all(&input, |var_name: &regex::Captures| std::env::var(var_name.get(1).unwrap().as_str()).unwrap_or_default()) .replace_all(&input, |var_name: &regex::Captures| std::env::var(var_name.get(1).unwrap().as_str()).unwrap_or_default())
.into_owned() .into_owned()
} }

View file

@ -14,8 +14,8 @@ itertools = "0.10"
thiserror = "1.0" thiserror = "1.0"
maplit = "1.0" maplit = "1.0"
logos = "0.12" logos = "0.12"
lazy_static = "1.4"
once_cell = "1.8"
serde = {version = "1.0", features = ["derive"]} serde = {version = "1.0", features = ["derive"]}
serde_json = "1.0" serde_json = "1.0"

View file

@ -1,10 +1,9 @@
use eww_shared_util::{Span, Spanned}; use eww_shared_util::{Span, Spanned};
use logos::Logos; use logos::Logos;
use once_cell::sync::Lazy;
use regex::Regex; use regex::Regex;
lazy_static::lazy_static! { static ESCAPE_REPLACE_REGEX: Lazy<Regex> = Lazy::new(|| Regex::new(r"\\(.)").unwrap());
static ref ESCAPE_REPLACE_REGEX: Regex = Regex::new(r"\\(.)").unwrap();
}
#[rustfmt::skip] #[rustfmt::skip]
#[derive(Logos, Debug, PartialEq, Eq, Clone, strum::Display, strum::EnumString)] #[derive(Logos, Debug, PartialEq, Eq, Clone, strum::Display, strum::EnumString)]

View file

@ -23,8 +23,8 @@ derive_more = "0.99"
smart-default = "0.6" smart-default = "0.6"
serde = {version = "1.0", features = ["derive"]} serde = {version = "1.0", features = ["derive"]}
serde_json = "1.0" serde_json = "1.0"
lazy_static = "1.4"
pretty_assertions = "0.7" pretty_assertions = "0.7"
once_cell = "1.8"
strum = { version = "0.21", features = ["derive"] } strum = { version = "0.21", features = ["derive"] }
anyhow = "1" anyhow = "1"

View file

@ -1,3 +1,4 @@
use once_cell::sync::Lazy;
use regex::{Regex, RegexSet}; use regex::{Regex, RegexSet};
use super::parse_error; use super::parse_error;
@ -41,26 +42,20 @@ impl std::fmt::Display for Token {
} }
macro_rules! regex_rules { macro_rules! regex_rules {
($( ($( $regex:literal => $token:expr),*) => {
$regex:literal => $token:expr),* static LEXER_REGEX_SET: Lazy<RegexSet> = Lazy::new(|| { RegexSet::new(&[
) => {
lazy_static::lazy_static! {
static ref LEXER_REGEX_SET: RegexSet = RegexSet::new(&[
$(format!("^{}", $regex)),* $(format!("^{}", $regex)),*
]).unwrap(); ]).unwrap()});
static ref LEXER_REGEXES: Vec<Regex> = vec![ static LEXER_REGEXES: Lazy<Vec<Regex>> = Lazy::new(|| { vec![
$(Regex::new(&format!("^{}", $regex)).unwrap()),* $(Regex::new(&format!("^{}", $regex)).unwrap()),*
]; ]});
static ref LEXER_FNS: Vec<Box<dyn Fn(String) -> Token + Sync>> = vec![ static LEXER_FNS: Lazy<Vec<Box<dyn Fn(String) -> Token + Sync + Send>>> = Lazy::new(|| { vec![
$(Box::new($token)),* $(Box::new($token)),*
]; ]});
}
} }
} }
lazy_static::lazy_static! { static ESCAPE_REPLACE_REGEX: Lazy<regex::Regex> = Lazy::new(|| Regex::new(r"\\(.)").unwrap());
static ref ESCAPE_REPLACE_REGEX: Regex = Regex::new(r"\\(.)").unwrap();
}
regex_rules! { regex_rules! {
r"\(" => |_| Token::LPren, r"\(" => |_| Token::LPren,

View file

@ -1,4 +1,5 @@
use derive_more::*; use derive_more::*;
use once_cell::sync::Lazy;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use smart_default::SmartDefault; use smart_default::SmartDefault;
use std::{fmt, str::FromStr}; use std::{fmt, str::FromStr};
@ -37,9 +38,7 @@ impl FromStr for NumWithUnit {
type Err = Error; type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> { fn from_str(s: &str) -> Result<Self, Self::Err> {
lazy_static::lazy_static! { static PATTERN: Lazy<regex::Regex> = Lazy::new(|| regex::Regex::new("^(-?\\d+)(.*)$").unwrap());
static ref PATTERN: regex::Regex = regex::Regex::new("^(-?\\d+)(.*)$").unwrap();
};
let captures = PATTERN.captures(s).ok_or_else(|| Error::NumParseFailed(s.to_string()))?; let captures = PATTERN.captures(s).ok_or_else(|| Error::NumParseFailed(s.to_string()))?;
let value = captures.get(1).unwrap().as_str().parse::<i32>().map_err(|_| Error::NumParseFailed(s.to_string()))?; let value = captures.get(1).unwrap().as_str().parse::<i32>().map_err(|_| Error::NumParseFailed(s.to_string()))?;