Skip to main content

rubo4e/generated/v202607/
tariftyp.rs

1#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
2#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
3#[cfg_attr(
4    feature = "strum",
5    derive(strum::EnumString, strum::EnumIter, strum::IntoStaticStr)
6)]
7#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
8#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
9/// Zur Differenzierung von Grund/Ersatzversorgungstarifen und sonstigen angebotenen Tarifen.
10#[non_exhaustive]
11pub enum Tariftyp {
12    #[cfg_attr(feature = "serde", serde(rename = "GRUND_ERSATZVERSORGUNG"))]
13    #[cfg_attr(feature = "strum", strum(serialize = "GRUND_ERSATZVERSORGUNG"))]
14    GrundErsatzversorgung,
15    #[cfg_attr(feature = "serde", serde(rename = "GRUNDVERSORGUNG"))]
16    #[cfg_attr(feature = "strum", strum(serialize = "GRUNDVERSORGUNG"))]
17    Grundversorgung,
18    #[cfg_attr(feature = "serde", serde(rename = "ERSATZVERSORGUNG"))]
19    #[cfg_attr(feature = "strum", strum(serialize = "ERSATZVERSORGUNG"))]
20    Ersatzversorgung,
21    #[cfg_attr(feature = "serde", serde(rename = "SONDERTARIF"))]
22    #[cfg_attr(feature = "strum", strum(serialize = "SONDERTARIF"))]
23    Sondertarif,
24    /// Unknown or future variant — produced when deserializing a value
25    /// that is not yet known to this version of the library.
26    #[cfg_attr(feature = "serde", serde(other, rename = "UNKNOWN"))]
27    #[cfg_attr(feature = "strum", strum(serialize = "UNKNOWN"))]
28    Unknown,
29}
30impl Tariftyp {
31    /// All variants defined by the BO4E schema, in declaration order.
32    ///
33    /// Excludes the forward-compatibility [`Tariftyp::Unknown`] catch-all, so this
34    /// is exactly the set of values that appear on the wire.  Available **without**
35    /// the `strum` feature — use it to drift-guard SQL `CHECK` lists and mappings.
36    pub const VARIANTS: &'static [Self] = &[
37        Self::GrundErsatzversorgung,
38        Self::Grundversorgung,
39        Self::Ersatzversorgung,
40        Self::Sondertarif,
41    ];
42    /// Number of schema-defined variants (equal to `VARIANTS.len()`), excluding the
43    /// [`Tariftyp::Unknown`] catch-all.  Stable for this schema version.
44    pub const COUNT: usize = Self::VARIANTS.len();
45    /// Returns an iterator over all **known** variants of `Tariftyp`.
46    ///
47    /// Yields only variants that correspond to values defined in the BO4E schema
48    /// (i.e. [`Self::VARIANTS`]), never the [`Tariftyp::Unknown`] catch-all.
49    /// Available **without** the `strum` feature.
50    ///
51    /// # Example
52    /// ```
53    /// # use rubo4e::current::Tariftyp;
54    /// // Never yields the `Unknown` catch-all, so the count matches `COUNT`.
55    /// assert_eq!(Tariftyp::iter_known().count(), Tariftyp::COUNT);
56    /// assert!(Tariftyp::iter_known().all(|v| v.is_known()));
57    /// ```
58    pub fn iter_known() -> impl Iterator<Item = Self> + Clone {
59        Self::VARIANTS.iter().copied()
60    }
61    /// Returns the canonical BO4E wire string (SCREAMING_SNAKE_CASE) for this value.
62    ///
63    /// [`Tariftyp::Unknown`] renders as `"UNKNOWN"`, matching its serialized form.
64    pub const fn as_wire(&self) -> &'static str {
65        match self {
66            Self::GrundErsatzversorgung => "GRUND_ERSATZVERSORGUNG",
67            Self::Grundversorgung => "GRUNDVERSORGUNG",
68            Self::Ersatzversorgung => "ERSATZVERSORGUNG",
69            Self::Sondertarif => "SONDERTARIF",
70            Self::Unknown => "UNKNOWN",
71        }
72    }
73    /// **Strictly** parses a BO4E wire string into a known variant.
74    ///
75    /// Unlike the lenient `serde` / [`FromStr`](std::str::FromStr) path — which maps
76    /// any unrecognized value (a typo, a legacy code, or a value from a newer schema)
77    /// to [`Tariftyp::Unknown`] — this returns
78    /// [`Err`](crate::error::UnknownVariant) for values not defined in this schema
79    /// version, including the literal `"UNKNOWN"`.  Use it at the ingest boundary to
80    /// reject bad values instead of silently degrading them.
81    ///
82    /// # Example
83    /// ```
84    /// # use rubo4e::current::Tariftyp;
85    /// assert_eq!(Tariftyp::from_wire("GRUND_ERSATZVERSORGUNG"), Ok(Tariftyp::GrundErsatzversorgung));
86    /// // Out-of-schema values are rejected rather than degraded:
87    /// assert!(Tariftyp::from_wire("NOT_A_REAL_VALUE").is_err());
88    /// // …including the `Unknown` catch-all's own wire spelling:
89    /// assert!(Tariftyp::from_wire("UNKNOWN").is_err());
90    /// ```
91    pub fn from_wire(s: &str) -> Result<Self, crate::error::UnknownVariant> {
92        match s {
93            "GRUND_ERSATZVERSORGUNG" => Ok(Self::GrundErsatzversorgung),
94            "GRUNDVERSORGUNG" => Ok(Self::Grundversorgung),
95            "ERSATZVERSORGUNG" => Ok(Self::Ersatzversorgung),
96            "SONDERTARIF" => Ok(Self::Sondertarif),
97            other => Err(crate::error::UnknownVariant::new(other)),
98        }
99    }
100    /// Returns `true` if this value is the forward-compatibility
101    /// [`Tariftyp::Unknown`] catch-all (an out-of-schema value).
102    pub const fn is_unknown(&self) -> bool {
103        matches!(self, Self::Unknown)
104    }
105    /// Returns `true` if this value is a known, schema-defined variant.
106    pub const fn is_known(&self) -> bool {
107        !self.is_unknown()
108    }
109}
110impl std::fmt::Display for Tariftyp {
111    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
112        f.write_str(self.as_wire())
113    }
114}
115impl AsRef<str> for Tariftyp {
116    fn as_ref(&self) -> &str {
117        self.as_wire()
118    }
119}
120#[cfg(feature = "versioned")]
121impl crate::bo4e_enum_sealed::Sealed for Tariftyp {}
122#[cfg(feature = "versioned")]
123impl crate::Bo4eEnum for Tariftyp {
124    const VARIANTS: &'static [Self] = Self::VARIANTS;
125    const COUNT: usize = Self::COUNT;
126    fn as_wire(&self) -> &'static str {
127        Self::as_wire(self)
128    }
129    fn from_wire(s: &str) -> Result<Self, crate::error::UnknownVariant> {
130        Self::from_wire(s)
131    }
132    fn is_unknown(&self) -> bool {
133        Self::is_unknown(self)
134    }
135}
136#[cfg(feature = "versioned")]
137impl crate::Bo4eStrict for Tariftyp {
138    fn collect_unknown_enums(&self, path: &str, out: &mut Vec<String>) {
139        if self.is_unknown() {
140            out.push(path.to_owned());
141        }
142    }
143}
144#[cfg(feature = "sqlx")]
145impl sqlx::Type<sqlx::Postgres> for Tariftyp {
146    fn type_info() -> sqlx::postgres::PgTypeInfo {
147        <String as sqlx::Type<sqlx::Postgres>>::type_info()
148    }
149}
150/// Encodes as the canonical BO4E wire string, borrowed from `as_wire` — no
151/// intermediate `String` or `serde_json::Value` is allocated.
152#[cfg(feature = "sqlx")]
153impl<'q> sqlx::Encode<'q, sqlx::Postgres> for Tariftyp {
154    fn encode_by_ref(
155        &self,
156        buf: &mut <sqlx::Postgres as sqlx::Database>::ArgumentBuffer<'q>,
157    ) -> Result<sqlx::encode::IsNull, sqlx::error::BoxDynError> {
158        let s: &str = self.as_wire();
159        <&str as sqlx::Encode<'q, sqlx::Postgres>>::encode_by_ref(&s, buf)
160    }
161}
162/// Decodes leniently, matching the `serde` path: a value the schema does not
163/// define becomes [`Tariftyp::Unknown`] rather than a decode error, so a
164/// database row written by a newer schema version still reads back.
165///
166/// Use [`Tariftyp::from_wire`] on a `String` column, or check
167/// [`Tariftyp::is_known`], where out-of-schema values must be rejected.
168#[cfg(feature = "sqlx")]
169impl<'r> sqlx::Decode<'r, sqlx::Postgres> for Tariftyp {
170    fn decode(
171        value: <sqlx::Postgres as sqlx::Database>::ValueRef<'r>,
172    ) -> Result<Self, sqlx::error::BoxDynError> {
173        let s = <&str as sqlx::Decode<sqlx::Postgres>>::decode(value)?;
174        Ok(Self::from_wire(s).unwrap_or(Self::Unknown))
175    }
176}
177/// Lets `Vec<Tariftyp>` bind to a `TEXT[]` column.  Only this crate can
178/// provide it: the trait and the enum are both foreign to any consumer, so the
179/// orphan rule rules out a downstream impl.
180#[cfg(feature = "sqlx")]
181impl sqlx::postgres::PgHasArrayType for Tariftyp {
182    fn array_type_info() -> sqlx::postgres::PgTypeInfo {
183        <String as sqlx::postgres::PgHasArrayType>::array_type_info()
184    }
185}
186#[cfg(test)]
187impl proptest::arbitrary::Arbitrary for Tariftyp {
188    type Parameters = ();
189    type Strategy = proptest::strategy::BoxedStrategy<Self>;
190    fn arbitrary_with(_: Self::Parameters) -> Self::Strategy {
191        use proptest::prelude::*;
192        proptest::sample::select(Self::VARIANTS.to_vec()).boxed()
193    }
194}