cloudevents/event/
spec_version.rs

1use super::{v03, v10};
2use std::convert::TryFrom;
3use std::fmt;
4use std::fmt::Formatter;
5
6pub(crate) const SPEC_VERSIONS: [&str; 2] = ["0.3", "1.0"];
7
8/// CloudEvent specification version.
9#[derive(PartialEq, Eq, Hash, Debug, Clone)]
10pub enum SpecVersion {
11    /// CloudEvents v0.3
12    V03,
13    /// CloudEvents v1.0
14    V10,
15}
16
17impl SpecVersion {
18    /// Returns the string representation of [`SpecVersion`].
19    #[inline]
20    pub fn as_str(&self) -> &str {
21        match self {
22            SpecVersion::V03 => "0.3",
23            SpecVersion::V10 => "1.0",
24        }
25    }
26
27    /// Get all attribute names for this [`SpecVersion`].
28    #[inline]
29    pub fn attribute_names(&self) -> &'static [&'static str] {
30        match self {
31            SpecVersion::V03 => &v03::ATTRIBUTE_NAMES,
32            SpecVersion::V10 => &v10::ATTRIBUTE_NAMES,
33        }
34    }
35}
36
37impl fmt::Display for SpecVersion {
38    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
39        write!(f, "{}", self.as_str())
40    }
41}
42
43/// Error representing an unknown [`SpecVersion`] string identifier
44#[derive(Debug)]
45pub struct UnknownSpecVersion {
46    spec_version_value: String,
47}
48
49impl fmt::Display for UnknownSpecVersion {
50    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
51        write!(f, "Invalid specversion {}", self.spec_version_value)
52    }
53}
54
55impl std::error::Error for UnknownSpecVersion {}
56
57impl TryFrom<&str> for SpecVersion {
58    type Error = UnknownSpecVersion;
59
60    fn try_from(value: &str) -> Result<Self, UnknownSpecVersion> {
61        match value {
62            "0.3" => Ok(SpecVersion::V03),
63            "1.0" => Ok(SpecVersion::V10),
64            _ => Err(UnknownSpecVersion {
65                spec_version_value: value.to_string(),
66            }),
67        }
68    }
69}