Skip to main content

ftracker_identifiers/country/
schema.rs

1//! [`JsonSchema`] implementation for [`CountryCode`].
2//!
3//! Enabled by the `schemars` feature. The schema is a structural, pattern constrained string. It
4//! captures the two uppercase letter shape, but a regex cannot express which two letter codes ISO
5//! 3166-1 actually assigns. Deserialization (via the `serde` feature) still enforces membership.
6
7#[cfg(not(feature = "std"))]
8extern crate alloc;
9
10#[cfg(not(feature = "std"))]
11use alloc::borrow::Cow;
12#[cfg(feature = "std")]
13use std::borrow::Cow;
14
15use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
16
17use super::CountryCode;
18
19impl JsonSchema for CountryCode {
20    fn schema_name() -> Cow<'static, str> {
21        Cow::Borrowed("CountryCode")
22    }
23
24    fn json_schema(_: &mut SchemaGenerator) -> Schema {
25        json_schema!({
26            "type": "string",
27            "format": "iso3166-1-alpha2",
28            "minLength": 2,
29            "maxLength": 2,
30            "pattern": "^[A-Z]{2}$",
31            "description": "ISO 3166-1 alpha-2 country code. \
32            The pattern is structural; membership in the assigned set is enforced on deserialization."
33        })
34    }
35}
36
37#[cfg(test)]
38mod tests {
39    use super::super::CountryCode;
40    use schemars::schema_for;
41
42    #[test]
43    fn schema_is_a_pattern_constrained_string() {
44        let schema = schema_for!(CountryCode);
45        let json = serde_json::to_value(&schema).unwrap();
46
47        assert_eq!(json["type"], "string");
48        assert_eq!(json["format"], "iso3166-1-alpha2");
49        assert_eq!(json["minLength"], 2);
50        assert_eq!(json["maxLength"], 2);
51        assert_eq!(json["pattern"], "^[A-Z]{2}$");
52    }
53}