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-sys",
"itertools 0.10.1",
"lazy_static",
"libc",
"log",
"maplit",
"nix",
"notify",
"num",
"once_cell",
"pretty_assertions",
"pretty_env_logger",
"regex",
@ -1889,9 +1889,9 @@ dependencies = [
"itertools 0.10.1",
"lalrpop",
"lalrpop-util",
"lazy_static",
"logos",
"maplit",
"once_cell",
"regex",
"serde",
"serde_json",
@ -2391,8 +2391,8 @@ dependencies = [
"itertools 0.10.1",
"lalrpop",
"lalrpop-util",
"lazy_static",
"maplit",
"once_cell",
"pretty_assertions",
"regex",
"serde",

View file

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

View file

@ -3,7 +3,7 @@ name = "eww"
version = "0.1.0"
authors = ["elkowar <5300871+elkowar@users.noreply.github.com>"]
edition = "2018"
description= "Widget system for everyone!"
description = "Widget system for everyone!"
license = "MIT"
repository = "https://github.com/elkowar/eww"
homepage = "https://github.com/elkowar/eww"
@ -44,8 +44,8 @@ itertools = "0.10"
debug_stub_derive = "0.3"
log = "0.4"
pretty_env_logger = "0.4"
lazy_static = "1.4.0"
libc = "0.2"
once_cell = "1.8"
nix = "0.20"
smart-default = "0.6"
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.
use anyhow::*;
use once_cell::sync::Lazy;
use tokio::sync::broadcast;
lazy_static::lazy_static! {
static ref APPLICATION_EXIT_SENDER: broadcast::Sender<()> = broadcast::channel(2).0;
}
pub static APPLICATION_EXIT_SENDER: Lazy<broadcast::Sender<()>> = Lazy::new(|| broadcast::channel(2).0);
/// Notify all listening tasks of the termination of the eww application process.
pub fn send_exit() -> Result<()> {

View file

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

View file

@ -5,14 +5,13 @@ use codespan_reporting::{
term::{self, Chars},
};
use eww_shared_util::Span;
use once_cell::sync::Lazy;
use simplexpr::eval::EvalError;
use yuck::{config::file_provider::YuckFiles, error::AstError, format_diagnostic::ToDiagnostic, gen_diagnostic};
use crate::error::DiagError;
lazy_static::lazy_static! {
pub static ref ERROR_HANDLING_CTX: Arc<Mutex<YuckFiles>> = Arc::new(Mutex::new(YuckFiles::new()));
}
pub static ERROR_HANDLING_CTX: Lazy<Arc<Mutex<YuckFiles>>> = Lazy::new(|| Arc::new(Mutex::new(YuckFiles::new())));
pub fn clear_files() {
*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,
/// and return a nicely formatted error message on invalid values. I.e.:
/// ```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
/// reference with an empty string.
pub fn replace_env_var_references(input: String) -> String {
lazy_static::lazy_static! {
static ref ENV_VAR_PATTERN: regex::Regex = regex::Regex::new(r"\$\{([^\s]*)\}").unwrap();
}
ENV_VAR_PATTERN
regex!(r"\$\{([^\s]*)\}")
.replace_all(&input, |var_name: &regex::Captures| std::env::var(var_name.get(1).unwrap().as_str()).unwrap_or_default())
.into_owned()
}

View file

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

View file

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

View file

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

View file

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

View file

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