cat_gateway/service/common/objects/config/
version.rs

1//! Implement newtype for `Version`
2
3use core::fmt;
4
5use derive_more::{From, Into};
6use poem_openapi::{
7    registry::{MetaSchema, MetaSchemaRef},
8    types::{Example, ParseError, ParseFromJSON, ParseResult, ToJSON, Type},
9};
10
11/// Semantic Versioning String
12#[derive(Debug, Clone, From, Into)]
13pub(crate) struct SemVer(String);
14
15impl Type for SemVer {
16    type RawElementValueType = Self;
17    type RawValueType = Self;
18
19    const IS_REQUIRED: bool = true;
20
21    fn name() -> std::borrow::Cow<'static, str> {
22        "SemanticVersion".into()
23    }
24
25    fn schema_ref() -> MetaSchemaRef {
26        MetaSchemaRef::Inline(Box::new(
27            MetaSchema::new("string")
28        )).merge(
29            MetaSchema {
30                description: Some("Semantic Versioning string following semver.org 2.0.0 specification."),
31                example: Self::example().to_json(),
32                max_length: Some(64),
33                pattern: Some("^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9A-Za-z-][0-9A-Za-z-]*)(?:\\.(?:0|[1-9A-Za-z-][0-9A-Za-z-]*))*))?(?:\\+([0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*))?$".into()),
34                ..poem_openapi::registry::MetaSchema::ANY
35            }
36        )
37    }
38
39    fn as_raw_value(&self) -> Option<&Self::RawValueType> {
40        Some(self)
41    }
42
43    fn raw_element_iter<'a>(
44        &'a self,
45    ) -> Box<dyn Iterator<Item = &'a Self::RawElementValueType> + 'a> {
46        Box::new(self.as_raw_value().into_iter())
47    }
48}
49
50impl ParseFromJSON for SemVer {
51    fn parse_from_json(value: Option<serde_json::Value>) -> ParseResult<Self> {
52        String::parse_from_json(value)
53            .map_err(ParseError::propagate)
54            .map(Self)
55    }
56}
57
58impl ToJSON for SemVer {
59    fn to_json(&self) -> Option<serde_json::Value> {
60        Some(self.to_string().into())
61    }
62}
63
64impl fmt::Display for SemVer {
65    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66        self.0.fmt(f)
67    }
68}
69
70impl Example for SemVer {
71    fn example() -> Self {
72        Self("1.0.0".into())
73    }
74}