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
#[cfg(feature = "json")]
use derive_more::Display;
#[cfg(feature = "json")]
use serde::{Deserialize, Serialize};
#[cfg(feature = "json")]
use std::convert::TryFrom;

/// Content of [`SchemaVersion`].
pub const SCHEMA_VERSION: &str = "2021-06-05";

/// Verifying schema version.
#[derive(Debug, Clone, Copy)]
#[cfg_attr(feature = "json", derive(Deserialize, Serialize))]
#[cfg_attr(feature = "json", serde(try_from = "String", into = "&str"))]
pub struct SchemaVersion;

/// Error when trying to parse [`SchemaVersion`].
#[cfg(feature = "json")]
#[derive(Debug, Display)]
#[display(
    fmt = "InvalidSchema: {:?}: input schema is not {:?}",
    input,
    SCHEMA_VERSION
)]
pub struct InvalidSchema {
    /// The input string.
    pub input: String,
}

#[cfg(feature = "json")]
impl TryFrom<String> for SchemaVersion {
    type Error = InvalidSchema;
    fn try_from(input: String) -> Result<Self, Self::Error> {
        if input == SCHEMA_VERSION {
            Ok(SchemaVersion)
        } else {
            Err(InvalidSchema { input })
        }
    }
}

impl<'a> From<SchemaVersion> for &'a str {
    fn from(_: SchemaVersion) -> Self {
        SCHEMA_VERSION
    }
}