Skip to main content

utopia_validators/
scalar.rs

1//! Booleans, integers, floats, numbers, ranges, ports and hex colors.
2
3use php_std::filter::{self, FILTER_FLAG_IPV4, FILTER_FLAG_IPV6, FILTER_VALIDATE_IP, Options};
4use php_std::format::number_format;
5
6use crate::{Input, Number, decimal};
7
8/// PHP `$a <= $b` on two numbers: exact between ints, as floats otherwise (NaN is never
9/// smaller or equal).
10pub fn number_le(a: Number, b: Number) -> bool {
11    match (a, b) {
12        (Number::Int(a), Number::Int(b)) => a <= b,
13        _ => a.as_f64() <= b.as_f64(),
14    }
15}
16
17/// PHP `number_format($number)`, appended to `out`: rounded to an integer, digits grouped
18/// by `,`. An int is written straight into `out`.
19fn grouped(number: Number, out: &mut Vec<u8>) {
20    let Number::Int(int) = number else {
21        out.extend(number_format(number, 0, b".", b","));
22        return;
23    };
24    if int < 0 {
25        out.push(b'-');
26    }
27    let mut digits = [0u8; 20];
28    let mut n = int.unsigned_abs();
29    let mut start = digits.len();
30    loop {
31        start -= 1;
32        digits[start] = b'0' + (n % 10) as u8;
33        n /= 10;
34        if n == 0 {
35            break;
36        }
37    }
38    let digits = &digits[start..];
39    for (i, &digit) in digits.iter().enumerate() {
40        if i > 0 && (digits.len() - i).is_multiple_of(3) {
41            out.push(b',');
42        }
43        out.push(digit);
44    }
45}
46
47/// A boolean; when `loose`, also `'true'`, `'false'`, `'1'`, `'0'`, `1` and `0`.
48///
49/// PHP: `Boolean::isValid()`.
50pub fn boolean(loose: bool, value: Input<'_>) -> bool {
51    match value {
52        Input::Bool(_) => true,
53        Input::Str(s) => loose && matches!(s, b"true" | b"false" | b"1" | b"0"),
54        Input::Int(i) => loose && (i == 1 || i == 0),
55        _ => false,
56    }
57}
58
59/// An int or a float; when `loose`, anything `is_numeric()`.
60///
61/// PHP: `FloatValidator::isValid()`.
62pub fn float(loose: bool, value: Input<'_>) -> bool {
63    if loose {
64        return value.numeric().is_some();
65    }
66    matches!(value, Input::Int(_) | Input::Float(_))
67}
68
69/// Anything `is_numeric()`: ints, floats (`NAN` and `INF` included) and numeric strings.
70///
71/// PHP: `Numeric::isValid()`.
72pub fn numeric(value: Input<'_>) -> bool {
73    value.numeric().is_some()
74}
75
76/// Why `new Integer()` refuses its arguments; [`IntegerError::message`] is the
77/// `InvalidArgumentException`'s.
78#[derive(Debug, Clone, Copy, PartialEq, Eq)]
79pub enum IntegerError {
80    /// `$bits` is not 8, 16, 32 or 64.
81    Bits,
82    /// An unsigned 64-bit integer.
83    Unsigned64,
84}
85
86impl IntegerError {
87    /// The exception's message, as `Integer.php` words it.
88    pub fn message(self) -> &'static str {
89        match self {
90            IntegerError::Bits => "Bits must be 8, 16, 32, or 64",
91            IntegerError::Unsigned64 => "64-bit unsigned integers are not supported due to PHP integer limitations",
92        }
93    }
94}
95
96/// An integer of `bits` bits, signed or `unsigned`.
97///
98/// PHP: `Integer`'s `$bits` and `$unsigned`.
99#[derive(Debug, Clone, Copy, PartialEq, Eq)]
100pub struct Integer {
101    /// The size in bits.
102    pub bits: i64,
103    /// Whether the range starts at 0.
104    pub unsigned: bool,
105}
106
107impl Integer {
108    /// The constructor's checks of `$bits` and `$unsigned` (on a 64-bit build, the third,
109    /// that the size fits the build's integers, follows from the first two).
110    ///
111    /// PHP: `new Integer($loose, $bits, $unsigned)`.
112    pub fn new(bits: i64, unsigned: bool) -> Result<Self, IntegerError> {
113        if !matches!(bits, 8 | 16 | 32 | 64) {
114            return Err(IntegerError::Bits);
115        }
116        if bits == 64 && unsigned {
117            return Err(IntegerError::Unsigned64);
118        }
119        Ok(Self { bits, unsigned })
120    }
121
122    /// The largest valid value.
123    ///
124    /// PHP: `getMax()` (private): `(1 << $bits) - 1` unsigned, `PHP_INT_MAX >> (64 - $bits)`
125    /// signed.
126    pub fn max(self) -> i64 {
127        if self.unsigned {
128            let shifted = if (0..64).contains(&self.bits) { 1i64 << self.bits } else { 0 };
129            shifted.wrapping_sub(1)
130        } else {
131            let shift = 64 - self.bits;
132            if (0..64).contains(&shift) { i64::MAX >> shift } else { 0 }
133        }
134    }
135
136    /// The smallest valid value.
137    ///
138    /// PHP: `getMin()` (private).
139    pub fn min(self) -> i64 {
140        if self.unsigned { 0 } else { -self.max() - 1 }
141    }
142
143    /// An int within the bounds; when `loose`, also a numeric string that `+ 0` makes one.
144    /// A float is never valid, `1.0` included.
145    ///
146    /// PHP: `Integer::isValid()`.
147    pub fn accepts(self, loose: bool, value: Input<'_>) -> bool {
148        let value = if loose {
149            value.numeric()
150        } else if let Input::Int(i) = value {
151            Some(Number::Int(i))
152        } else {
153            None
154        };
155        match value {
156            Some(Number::Int(i)) => i >= self.min() && i <= self.max(),
157            _ => false,
158        }
159    }
160
161    /// `Value must be a valid signed 32-bit integer between -2,147,483,648 and 2,147,483,647`.
162    ///
163    /// PHP: `Integer::getDescription()`.
164    /// Appended to `out`.
165    pub fn description(self, out: &mut Vec<u8>) {
166        out.extend_from_slice(b"Value must be a valid ");
167        out.extend_from_slice(if self.unsigned { b"unsigned " } else { b"signed " });
168        decimal(self.bits, out);
169        out.extend_from_slice(b"-bit integer between ");
170        grouped(Number::Int(self.min()), out);
171        out.extend_from_slice(b" and ");
172        grouped(Number::Int(self.max()), out);
173    }
174
175    /// The OpenAPI format, `int32` or `uint8`, ..., given what `isUnsigned()` answers.
176    ///
177    /// PHP: `Integer::getFormat()`.
178    pub fn format(bits: i64, unsigned: bool) -> String {
179        format!("{}{bits}", if unsigned { "uint" } else { "int" })
180    }
181}
182
183/// The number `Range::isValid()` compares with its bounds, for a value that passed
184/// `is_numeric()`: as `'integer'`, an int (from `+ 0`, so a numeric string that makes one) or
185/// a float that already is `INF`/`-INF` (PHP checks `$value === INF` before `+ 0`, so a
186/// string such as `'1e400'` that overflows to `INF` is not one); as `'double'`, any number as
187/// a float; `None` when the value is not one, and for any other format.
188pub fn range_number(format: &[u8], value: Input<'_>) -> Option<Number> {
189    let number = value.numeric()?;
190    match format {
191        b"integer" => match (value, number) {
192            (Input::Float(f), _) if f.is_infinite() => Some(number),
193            (_, Number::Int(_)) => Some(number),
194            (_, Number::Float(_)) => None,
195        },
196        b"double" => Some(Number::Float(number.as_f64())),
197        _ => None,
198    }
199}
200
201/// A number from `min` to `max`, both included, of `format` (see [`range_number`]).
202///
203/// PHP: `Range::isValid()`.
204pub fn range(min: Number, max: Number, format: &[u8], value: Input<'_>) -> bool {
205    range_number(format, value).is_some_and(|number| number_le(min, number) && number_le(number, max))
206}
207
208/// `Value must be a valid range between 1 and 10`, both bounds as `number_format()` prints
209/// them.
210///
211/// PHP: `Range::getDescription()`.
212/// Appended to `out`.
213pub fn range_description(min: Number, max: Number, out: &mut Vec<u8>) {
214    out.extend_from_slice(b"Value must be a valid range between ");
215    grouped(min, out);
216    out.extend_from_slice(b" and ");
217    grouped(max, out);
218}
219
220/// A port from 1 to 65535, optionally after an IPv4 address or a bracketed IPv6 one and a
221/// colon (`127.0.0.1:80`, `[::1]:443`). An int is checked as its decimal string.
222///
223/// PHP: `Port::isValid()`.
224pub fn port(value: Input<'_>) -> bool {
225    let digits;
226    let value = match value {
227        Input::Int(i) => {
228            digits = i.to_string();
229            digits.as_bytes()
230        }
231        Input::Str(s) => s,
232        _ => return false,
233    };
234    match value.iter().rposition(|&b| b == b':') {
235        None => port_number(value),
236        Some(at) => port_host(&value[..at]) && port_number(&value[at + 1..]),
237    }
238}
239
240/// An IPv4 address, or an IPv6 address in brackets.
241///
242/// PHP: `Port::isValidHost()` (private).
243pub fn port_host(host: &[u8]) -> bool {
244    let (address, flag) = match host {
245        [b'[', .., b']'] => (&host[1..host.len() - 1], FILTER_FLAG_IPV6),
246        // `substr('[', 1, -1)`: a lone bracket both starts and ends the string.
247        [b'['] => (&host[..0], FILTER_FLAG_IPV6),
248        _ => (host, FILTER_FLAG_IPV4),
249    };
250    matches!(
251        filter::filter_var(&filter::Value::Str(address.to_vec()), FILTER_VALIDATE_IP, &Options::Flags(flag)),
252        Ok(filter::Filtered { value: filter::Value::Str(_), .. })
253    )
254}
255
256/// Decimal digits without a leading zero, from 1 to 65535.
257///
258/// PHP: `Port::isValidPort()` (private).
259pub fn port_number(port: &[u8]) -> bool {
260    if port.is_empty() || !port.iter().all(u8::is_ascii_digit) || port[0] == b'0' {
261        return false;
262    }
263    // `(int)` of a longer run of digits saturates far above 65535.
264    port.len() <= 5 && port.iter().fold(0u32, |n, &d| n * 10 + u32::from(d - b'0')) <= 65535
265}
266
267/// A string of 3 or 6 hex digits, no `#`. The pattern's `$` also matches before a final
268/// newline, so one trailing `"\n"` is allowed.
269///
270/// PHP: `HexColor::isValid()` (`/^([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/`).
271pub fn hex_color(value: Input<'_>) -> bool {
272    let Input::Str(s) = value else {
273        return false;
274    };
275    let s = s.strip_suffix(b"\n").unwrap_or(s);
276    matches!(s.len(), 3 | 6) && s.iter().all(u8::is_ascii_hexdigit)
277}
278
279#[cfg(test)]
280mod tests {
281    use super::*;
282
283    #[test]
284    fn integer_bounds() {
285        let signed = Integer::new(32, false).unwrap();
286        assert_eq!((signed.min(), signed.max()), (-2_147_483_648, 2_147_483_647));
287        let byte = Integer::new(8, true).unwrap();
288        assert_eq!((byte.min(), byte.max()), (0, 255));
289        let wide = Integer::new(64, false).unwrap();
290        assert_eq!((wide.min(), wide.max()), (i64::MIN, i64::MAX));
291        assert_eq!(Integer::new(12, false), Err(IntegerError::Bits));
292        assert_eq!(Integer::new(64, true), Err(IntegerError::Unsigned64));
293    }
294
295    #[test]
296    fn integer_accepts() {
297        let int = Integer::new(8, false).unwrap();
298        assert!(int.accepts(false, Input::Int(127)) && !int.accepts(false, Input::Int(128)));
299        assert!(!int.accepts(false, Input::Str(b"5")) && int.accepts(true, Input::Str(b" 5 ")));
300        assert!(!int.accepts(true, Input::Str(b"1e1")) && !int.accepts(true, Input::Float(1.0)));
301        let mut description = Vec::new();
302        int.description(&mut description);
303        assert_eq!(description, b"Value must be a valid signed 8-bit integer between -128 and 127");
304        let mut description = Vec::new();
305        range_description(Number::Int(i64::MIN), Number::Int(-1000), &mut description);
306        assert_eq!(description, b"Value must be a valid range between -9,223,372,036,854,775,808 and -1,000");
307        let mut description = Vec::new();
308        range_description(Number::Int(0), Number::Float(1.5e3), &mut description);
309        assert_eq!(description, b"Value must be a valid range between 0 and 1,500");
310    }
311
312    #[test]
313    fn ranges() {
314        let (one, ten) = (Number::Int(1), Number::Int(10));
315        assert!(range(one, ten, b"integer", Input::Str(b"5")) && !range(one, ten, b"integer", Input::Float(5.0)));
316        assert!(range(one, ten, b"double", Input::Float(5.5)) && !range(one, ten, b"string", Input::Int(5)));
317        assert!(range(Number::Float(f64::NEG_INFINITY), ten, b"integer", Input::Float(f64::NEG_INFINITY)));
318        assert!(!range(one, ten, b"double", Input::Float(f64::NAN)));
319        let unbounded = Number::Float(f64::INFINITY);
320        assert!(
321            range(one, unbounded, b"integer", Input::Float(f64::INFINITY))
322                && !range(one, unbounded, b"integer", Input::Str(b"1e400"))
323        );
324    }
325
326    #[test]
327    fn ports_and_colors() {
328        assert!(port(Input::Int(80)) && port(Input::Str(b"127.0.0.1:8080")) && port(Input::Str(b"[::1]:443")));
329        assert!(!port(Input::Str(b"080")) && !port(Input::Str(b"65536")) && !port(Input::Str(b"[::1]")));
330        assert!(!port(Input::Str(b"::1:80")) && !port(Input::Int(0)) && !port(Input::Str(b"")));
331        assert!(hex_color(Input::Str(b"fff")) && hex_color(Input::Str(b"A0B1C2\n")) && !hex_color(Input::Str(b"#fff")));
332        assert!(!hex_color(Input::Str(b"ffff")) && !hex_color(Input::Str(b"fff\n\n")));
333    }
334}