Skip to main content

tanzim_validate/
boolean.rs

1use crate::error::{Error, ErrorKind};
2use crate::{Meta, Validator};
3use tanzim_value::{Value, ValueType};
4
5/// (`boolean` feature) Accepts only a boolean value. No coercion, no options.
6#[derive(Debug, Clone, Default)]
7pub struct Bool {
8    meta: Meta,
9}
10
11impl Bool {
12    pub fn new() -> Self {
13        Self::default()
14    }
15
16    /// Attach human-facing metadata (name, description, examples, default, output conversion).
17    pub fn with_meta(mut self, meta: Meta) -> Self {
18        self.meta = meta;
19        self
20    }
21}
22
23impl Validator for Bool {
24    fn meta(&self) -> &Meta {
25        &self.meta
26    }
27
28    fn meta_mut(&mut self) -> &mut Meta {
29        &mut self.meta
30    }
31
32    fn check(&self, value: &mut Value) -> Result<(), Error> {
33        if value.is_bool() {
34            Ok(())
35        } else {
36            Err(Error::new(ErrorKind::Type {
37                expected: ValueType::Bool,
38                found: value.type_name(),
39            }))
40        }
41    }
42}
43
44#[cfg(test)]
45mod tests {
46    use super::*;
47
48    #[test]
49    fn accepts_bool() {
50        let mut value = Value::Bool(true);
51        assert!(Bool::new().validate(&mut value).is_ok());
52    }
53
54    #[test]
55    fn rejects_non_bool() {
56        let mut value = Value::Int(1);
57        let error = Bool::new().validate(&mut value).unwrap_err();
58        assert!(matches!(error.kind, ErrorKind::Type { .. }));
59    }
60}