From 25a41a7a45e01fabdbacc5f6e6fdf281b45e2d98 Mon Sep 17 00:00:00 2001 From: Narthana Epa Date: Sat, 6 Jul 2024 14:41:09 +1000 Subject: [PATCH] Replace lazy-static with once_lock --- Cargo.lock | 7 ------- Cargo.toml | 1 - src/words.rs | 23 ++++++++++++++++++----- 3 files changed, 18 insertions(+), 13 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 399a88e..652af72 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -205,12 +205,6 @@ dependencies = [ "either", ] -[[package]] -name = "lazy_static" -version = "1.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" - [[package]] name = "libc" version = "0.2.134" @@ -446,7 +440,6 @@ dependencies = [ "clap", "eyre", "itertools", - "lazy_static", "rand", "rand_chacha", "rayon", diff --git a/Cargo.toml b/Cargo.toml index 73907b3..e688ef6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,7 +10,6 @@ license = "MIT" clap = { version = "4.5.7", features = ["derive"] } eyre = "0.6.12" itertools = "0.13.0" -lazy_static = "1.5.0" rand = "0.8.5" regex = "1.10.5" diff --git a/src/words.rs b/src/words.rs index 10789fb..414dbca 100644 --- a/src/words.rs +++ b/src/words.rs @@ -1,14 +1,15 @@ use eyre::Result; -use lazy_static::lazy_static; use regex::Regex; use std::{ fs::File, io::{BufRead, BufReader}, path::Path, + sync::OnceLock, }; -lazy_static! { - static ref RE: Regex = Regex::new("^[a-z]{4,}$").unwrap(); +fn re() -> &'static Regex { + static RE: OnceLock = OnceLock::new(); + RE.get_or_init(|| Regex::new("^[a-z]{4,}$").unwrap()) } pub(crate) fn list(path: Option>) -> Result> { @@ -29,7 +30,7 @@ impl Words for WordsFromFixture { let bytes = include_bytes!("fixtures/words"); Ok(String::from_utf8_lossy(bytes) .split('\n') - .filter(|w| RE.is_match(w)) + .filter(|w| re().is_match(w)) .map(std::borrow::ToOwned::to_owned) .collect()) } @@ -45,7 +46,19 @@ impl> Words for WordsFromFile

{ Ok(BufReader::new(file) .lines() .map_while(std::result::Result::ok) - .filter(|w| RE.is_match(w)) + .filter(|w| re().is_match(w)) .collect()) } } + +#[cfg(test)] +mod tests { + #[test] + fn test_re() { + let re = super::re(); + assert!(re.is_match("abcd")); + assert!(!re.is_match("abc")); + assert!(!re.is_match("abc!")); + assert!(!re.is_match("1234")); + } +}