valust_utils/numeric.rs
1//! Utilities for numeric validations.
2
3/// Returns a closure that takes an argument and checks if it is less than the given value `a`.
4///
5/// This can be passed to `#[valid]` attribute like: `#[valid(fn(larger_than(5))]`.
6pub fn larger_than<T: PartialOrd>(a: T) -> impl Fn(T) -> bool {
7 move |b| a > b
8}
9
10/// Returns a closure that takes an argument and checks if it is greater than the given value `a`.
11///
12/// This can be passed to `#[valid]` attribute like: `#[valid(fn(smaller_than(5))]`.
13pub fn smaller_than<T: PartialOrd>(a: T) -> impl Fn(T) -> bool {
14 move |b| a < b
15}
16
17/// Returns a closure that takes an argument and checks if it is equal to the given value `a`.
18///
19/// This can be passed to `#[valid]` attribute like: `#[valid(fn(equal_to(5))]`.
20pub fn equal_to<T: PartialEq>(a: T) -> impl Fn(T) -> bool {
21 move |b| a == b
22}
23
24/// Returns a closure that takes an argument and checks if it is not equal to the given value `a`.
25///
26/// This can be passed to `#[valid]` attribute like: `#[valid(fn(not_equal_to(5))]`.
27pub fn not_equal_to<T: PartialEq>(a: T) -> impl Fn(T) -> bool {
28 move |b| a != b
29}
30
31/// Returns a closure that takes an argument and checks if it is greater than or equal to the given value `a`.
32///
33/// This can be passed to `#[valid]` attribute like: `#[valid(fn(larger_than_or_equal_to(5))]`.
34pub fn larger_than_or_equal_to<T: PartialOrd>(a: T) -> impl Fn(T) -> bool {
35 move |b| a >= b
36}
37
38/// Returns a closure that takes an argument and checks if it is less than or equal to the given value `a`.
39///
40/// This can be passed to `#[valid]` attribute like: `#[valid(fn(smaller_than_or_equal_to(5))]`.
41pub fn smaller_than_or_equal_to<T: PartialOrd>(a: T) -> impl Fn(T) -> bool {
42 move |b| a <= b
43}
44
45/// Returns a closure that takes an argument and checks if it is within the given range `[a, b]`.
46///
47/// This can be passed to `#[valid]` attribute like: `#[valid(fn(in_range(1, 5))]`.
48pub fn in_range<T: PartialOrd>(a: T, b: T) -> impl Fn(T) -> bool {
49 move |c| a <= c && c <= b
50}
51
52/// Alias for [`larger_than`].
53pub fn gt<T: PartialOrd>(a: T) -> impl Fn(T) -> bool {
54 larger_than(a)
55}
56
57/// Alias for [`smaller_than`].
58pub fn lt<T: PartialOrd>(a: T) -> impl Fn(T) -> bool {
59 smaller_than(a)
60}
61
62/// Alias for [`equal_to`].
63pub fn eq<T: PartialEq>(a: T) -> impl Fn(T) -> bool {
64 equal_to(a)
65}
66
67/// Alias for [`not_equal_to`].
68pub fn ne<T: PartialEq>(a: T) -> impl Fn(T) -> bool {
69 not_equal_to(a)
70}
71
72/// Alias for [`larger_than_or_equal_to`].
73pub fn ge<T: PartialOrd>(a: T) -> impl Fn(T) -> bool {
74 larger_than_or_equal_to(a)
75}
76
77/// Alias for [`smaller_than_or_equal_to`].
78pub fn le<T: PartialOrd>(a: T) -> impl Fn(T) -> bool {
79 smaller_than_or_equal_to(a)
80}
81
82/// Alias for [`in_range`].
83pub fn between<T: PartialOrd>(a: T, b: T) -> impl Fn(T) -> bool {
84 in_range(a, b)
85}