File: pattern.rs

package info (click to toggle)
rust-garde 0.22.1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 940 kB
  • sloc: makefile: 2
file content (93 lines) | stat: -rw-r--r-- 2,342 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
use regex::Regex;

use super::util;

mod sub {
    use std::sync::LazyLock;

    use once_cell::sync::Lazy;

    use super::*;

    pub static LAZY_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^abcd|efgh$").unwrap());
    pub static LAZY_RE_ONCE_CELL: Lazy<Regex> = Lazy::new(|| Regex::new(r"^abcd|efgh$").unwrap());
}

#[derive(Debug, garde::Validate)]
struct Test<'a> {
    #[garde(pattern(r"^abcd|efgh$"))]
    field: &'a str,

    #[garde(pattern(sub::LAZY_RE))]
    field_path: &'a str,

    #[garde(pattern(sub::LAZY_RE_ONCE_CELL))]
    field_path_once_cell: &'a str,

    #[garde(pattern(create_regex()))]
    field_call: &'a str,

    #[garde(inner(pattern(r"^abcd|efgh$")))]
    inner: &'a [&'a str],
}

#[cfg(not(all(feature = "js-sys", target_arch = "wasm32", target_os = "unknown")))]
fn create_regex() -> Regex {
    Regex::new(r"^abcd|efgh$").unwrap()
}

#[cfg(all(feature = "js-sys", target_arch = "wasm32", target_os = "unknown"))]
fn create_regex() -> ::js_sys::RegExp {
    ::js_sys::RegExp::new(r"^abcd|efgh$", "u")
}

#[cfg_attr(not(all(target_arch = "wasm32", target_os = "unknown")), test)]
#[cfg_attr(
    all(target_arch = "wasm32", target_os = "unknown"),
    wasm_bindgen_test::wasm_bindgen_test
)]
fn pattern_valid() {
    util::check_ok(
        &[
            Test {
                field: "abcd",
                field_path: "abcd",
                field_path_once_cell: "abcd",
                field_call: "abcd",
                inner: &["abcd"],
            },
            Test {
                field: "efgh",
                field_path: "efgh",
                field_path_once_cell: "abcd",
                field_call: "efgh",
                inner: &["efgh"],
            },
        ],
        &(),
    )
}

#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
#[test]
fn pattern_invalid() {
    util::check_fail!(
        &[
            Test {
                field: "dcba",
                field_path: "dcba",
                field_path_once_cell: "abcd",
                field_call: "dcba",
                inner: &["dcba"]
            },
            Test {
                field: "hgfe",
                field_path: "hgfe",
                field_path_once_cell: "abcd",
                field_call: "hgfe",
                inner: &["hgfe"]
            }
        ],
        &()
    )
}