Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
## Changelog

## Unreleased
- Implement `AsRegex` for `std::sync::LazyLock<Regex>`

## 0.19.0 (2024/11/03)

- Swap to using proc-macro-error-2 instead of proc-macro-error for Syn
Expand Down
8 changes: 7 additions & 1 deletion validator/src/validation/regex.rs
Original file line number Diff line number Diff line change
@@ -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;

Expand Down Expand Up @@ -54,6 +54,12 @@ impl AsRegex for &Arc<Mutex<OnceLock<Regex>>> {
}
}

impl AsRegex for LazyLock<Regex> {
fn as_regex(&self) -> Cow<Regex> {
Cow::Borrowed(self)
}
}

pub trait ValidateRegex {
fn validate_regex(&self, regex: impl AsRegex) -> bool;
}
Expand Down
18 changes: 17 additions & 1 deletion validator_derive_tests/tests/regex.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -10,6 +10,7 @@ static RE2: Lazy<Regex> = Lazy::new(|| Regex::new(r"^[a-z]{2}$").unwrap());
static REGEX_ONCE_LOCK: OnceLock<Regex> = OnceLock::new();
static REGEX_MUTEX_ONCE_CELL: Mutex<OnceCell<Regex>> = Mutex::new(OnceCell::new());
static REGEX_MUTEX_ONCE_LOCK: Mutex<OnceLock<Regex>> = Mutex::new(OnceLock::new());
static REGEX_LAZY_LOCK: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^[a-z]{2}$").unwrap());

#[test]
fn can_validate_valid_regex() {
Expand Down Expand Up @@ -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());
}