bracket/render/
assert.rs

1//! Utility functions for type assertions.
2use serde_json::Value;
3use std::fmt;
4
5/// JSON types used for type assertions.
6#[derive(Copy, Clone, Eq, PartialEq)]
7pub enum Type {
8    /// The `null` JSON type.
9    Null,
10    /// The `boolean` JSON type.
11    Bool,
12    /// The `number` JSON type.
13    Number,
14    /// The `string` JSON type.
15    String,
16    /// The `object` JSON type.
17    Object,
18    /// The `array` JSON type.
19    Array,
20}
21
22impl fmt::Display for Type {
23    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
24        write!(f, "{}", {
25            match *self {
26                Self::Null => "null",
27                Self::Bool => "boolean",
28                Self::Number => "number",
29                Self::String => "string",
30                Self::Object => "object",
31                Self::Array => "array",
32            }
33        })
34    }
35}
36
37impl From<&Value> for Type {
38    fn from(value: &Value) -> Self {
39        match value {
40            Value::Null => Self::Null,
41            Value::Bool(_) => Self::Bool,
42            Value::Number(_) => Self::Number,
43            Value::String(_) => Self::String,
44            Value::Object(_) => Self::Object,
45            Value::Array(_) => Self::Array,
46        }
47    }
48}
49
50/// Assert on the type of a value.
51///
52/// The type of the value must be one of the given types.
53///
54/// If the type assertion fails the returned value contains a string
55/// of the current type that caused the failure.
56pub fn assert(value: &Value, kinds: &[Type]) -> (bool, Option<String>) {
57    for kind in kinds {
58        if !assert_type(value, kind) {
59            return (false, Some(kind.to_string()));
60        }
61    }
62    (true, None)
63}
64
65fn assert_type(value: &Value, kind: &Type) -> bool {
66    match value {
67        Value::Null => kind == &Type::Null,
68        Value::Bool(_) => kind == &Type::Bool,
69        Value::String(_) => kind == &Type::String,
70        Value::Number(_) => kind == &Type::Number,
71        Value::Object(_) => kind == &Type::Object,
72        Value::Array(_) => kind == &Type::Array,
73    }
74}