vos_core/constraint/integer_constraint/
mod.rs

1use super::*;
2
3/// ```vos
4/// n: i32[=1]
5/// n: i32[<1]
6/// n: i32[1..=2]
7/// n: i32[1 < n < 2]
8/// ```
9#[derive(Clone, Debug, Default, Serialize, Deserialize)]
10pub struct IntegerConstraint {
11    pub kind: IntegerKind,
12    /// Minimum length of utf8 string
13    pub min: Option<BigInt>,
14    /// Maximum length of utf8 string
15    pub max: Option<BigInt>,
16    /// Minimum number of unicode characters
17    pub min_length: Option<BigInt>,
18    /// Maximum number of unicode characters
19    pub max_length: Option<BigInt>,
20    /// Check if number is multiple of `x`
21    pub multiple_of: Option<BigInt>,
22    #[serde(skip_serializing_if = "Vec::is_empty")]
23    pub examples: Vec<BigInt>,
24    #[serde(flatten)]
25    pub info: SharedConstraint,
26}
27
28#[derive(Copy, Clone, Debug, Serialize, Deserialize)]
29#[non_exhaustive]
30pub enum IntegerKind {
31    Integer,
32    Integer8,
33    Integer16,
34    Integer32,
35    Integer64,
36    Integer128,
37    Integer256,
38    Unsigned8,
39    Unsigned16,
40    Unsigned32,
41    Unsigned64,
42    Unsigned128,
43    Unsigned256,
44}
45
46impl Default for IntegerKind {
47    fn default() -> Self {
48        Self::Integer32
49    }
50}
51
52impl IntegerConstraint {}
53
54impl IntegerConstraint {
55    /// ```vos
56    /// i: i32[>1];
57    /// i: i32[>=2];
58    /// type Integer: i32 {
59    ///     .min: -1
60    /// }
61    /// ```
62    pub fn min(&mut self, n: &str, inclusive: bool) -> VosResult {
63        let mut limit = BigInt::from_str(n)?;
64        if !inclusive {
65            limit += 1;
66        }
67        self.min = Some(limit);
68        Ok(())
69    }
70    /// ```vos
71    /// i: i32[<1];
72    /// i: i32[<=0];
73    /// type Integer: i32 {
74    ///     .max: +1
75    /// }
76    /// ```
77    pub fn max(mut self, n: &str, inclusive: bool) -> VosResult {
78        let mut limit = BigInt::from_str(n)?;
79        if !inclusive {
80            limit -= 1;
81        }
82        self.max = Some(limit);
83        Ok(())
84    }
85    /// ```vos
86    /// type Positive: i32 {
87    ///     .positive
88    /// }
89    /// ```
90    pub fn positive(mut self) -> VosResult {
91        self.min = Some(BigInt::zero());
92        Ok(())
93    }
94    /// ```vos
95    /// type Positive: i32 {
96    ///     .positive
97    /// }
98    /// ```
99    pub fn negative(mut self) -> VosResult {
100        self.max = Some(BigInt::zero());
101        Ok(())
102    }
103}