1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
use crate::*;
use std::net::{Ipv4Addr, Ipv6Addr};
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime};

#[derive(Clone, Debug, Default, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct StringType {
    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub default: Option<LiteralValue>,

    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub enum_values: Option<Vec<String>>,

    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub format: Option<String>,

    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub max_length: Option<usize>,

    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub min_length: Option<usize>,

    #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
    pub pattern: Option<String>,
}

impl StringType {
    /// Create a string schema with the provided default value.
    pub fn new(value: impl AsRef<str>) -> Self {
        StringType {
            default: Some(LiteralValue::String(value.as_ref().to_owned())),
            ..StringType::default()
        }
    }
}

macro_rules! impl_string {
    ($type:ty) => {
        impl Schematic for $type {
            fn build_schema(mut schema: SchemaBuilder) -> Schema {
                schema.string_default()
            }
        }
    };
}

macro_rules! impl_string_format {
    ($type:ty, $format:expr) => {
        impl Schematic for $type {
            fn build_schema(mut schema: SchemaBuilder) -> Schema {
                schema.string(StringType {
                    format: Some($format.into()),
                    ..StringType::default()
                })
            }
        }
    };
}

impl Schematic for char {
    fn build_schema(mut schema: SchemaBuilder) -> Schema {
        schema.string(StringType {
            max_length: Some(1),
            min_length: Some(1),
            ..StringType::default()
        })
    }
}

impl_string!(str);
impl_string!(&str);
impl_string!(String);

impl_string_format!(Path, "path");
impl_string_format!(&Path, "path");
impl_string_format!(PathBuf, "path");

impl_string_format!(Ipv4Addr, "ipv4");
impl_string_format!(Ipv6Addr, "ipv6");

impl_string_format!(SystemTime, "time");
impl_string_format!(Duration, "duration");