diff --git a/CHANGELOG.md b/CHANGELOG.md index 2edf8d4d..cdee5137 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,8 @@ ## Changelog +## Unreleased +- Implement `AsRegex` for `std::sync::LazyLock` + ## 0.19.0 (2024/11/03) - Swap to using proc-macro-error-2 instead of proc-macro-error for Syn diff --git a/validator/src/validation/regex.rs b/validator/src/validation/regex.rs index f1ed8614..fc030b60 100644 --- a/validator/src/validation/regex.rs +++ b/validator/src/validation/regex.rs @@ -1,7 +1,7 @@ use std::borrow::Cow; use std::cell::OnceCell; use std::rc::Rc; -use std::sync::{Arc, Mutex, OnceLock}; +use std::sync::{Arc, LazyLock, Mutex, OnceLock}; use regex::Regex; @@ -54,6 +54,12 @@ impl AsRegex for &Arc>> { } } +impl AsRegex for LazyLock { + fn as_regex(&self) -> Cow { + Cow::Borrowed(self) + } +} + pub trait ValidateRegex { fn validate_regex(&self, regex: impl AsRegex) -> bool; } diff --git a/validator_derive_tests/tests/regex.rs b/validator_derive_tests/tests/regex.rs index a1065959..bfef4077 100644 --- a/validator_derive_tests/tests/regex.rs +++ b/validator_derive_tests/tests/regex.rs @@ -1,6 +1,6 @@ use once_cell::sync::Lazy; use std::cell::OnceCell; -use std::sync::{Mutex, OnceLock}; +use std::sync::{LazyLock, Mutex, OnceLock}; use regex::Regex; use validator::Validate; @@ -10,6 +10,7 @@ static RE2: Lazy = Lazy::new(|| Regex::new(r"^[a-z]{2}$").unwrap()); static REGEX_ONCE_LOCK: OnceLock = OnceLock::new(); static REGEX_MUTEX_ONCE_CELL: Mutex> = Mutex::new(OnceCell::new()); static REGEX_MUTEX_ONCE_LOCK: Mutex> = Mutex::new(OnceLock::new()); +static REGEX_LAZY_LOCK: LazyLock = LazyLock::new(|| Regex::new(r"^[a-z]{2}$").unwrap()); #[test] fn can_validate_valid_regex() { @@ -124,3 +125,18 @@ fn can_specify_mutex_once_lock_for_regex() { let t = TestStruct { val: "aaa".to_string() }; assert!(t.validate().is_err()); } + +#[test] +fn can_specify_lazy_lock_for_regex() { + #[derive(Debug, Validate)] + struct TestStruct { + #[validate(regex(path = crate::REGEX_LAZY_LOCK))] + val: String, + } + + let t = TestStruct { val: "aa".to_string() }; + assert!(t.validate().is_ok()); + + let t = TestStruct { val: "aaa".to_string() }; + assert!(t.validate().is_err()); +}