Skip to main content

layline_codegen/model/
enumeration.rs

1//! Enumerations.
2
3use alloc::string::String;
4use alloc::vec::Vec;
5
6use super::Scalar;
7
8/// An enumeration of named values, with an optional fallback variant for unlisted values.
9#[derive(Debug, Clone, PartialEq, Eq)]
10#[non_exhaustive]
11pub struct EnumDef {
12    /// The type name.
13    pub name: String,
14    /// The value's type.
15    pub repr: Scalar,
16    /// The variants, in declaration order.
17    pub variants: Vec<Variant>,
18    /// The fallback variant, which holds an unlisted value. `None` means every value is listed.
19    pub other: Option<String>,
20    /// Documentation.
21    pub doc: Option<String>,
22}
23
24impl EnumDef {
25    /// An enumeration with no fallback, so it must list every value.
26    #[must_use]
27    pub fn new(name: &str, repr: Scalar, variants: Vec<Variant>) -> Self {
28        Self { name: String::from(name), repr, variants, other: None, doc: None }
29    }
30
31    /// Adds a fallback variant `other(repr)` that holds any unlisted value.
32    #[must_use]
33    pub fn with_other(self, other: &str) -> Self {
34        Self { other: Some(String::from(other)), ..self }
35    }
36
37    /// Sets the documentation.
38    #[must_use]
39    pub fn with_doc(self, doc: &str) -> Self {
40        Self { doc: Some(String::from(doc)), ..self }
41    }
42}
43
44/// One variant of an [`EnumDef`].
45#[derive(Debug, Clone, PartialEq, Eq)]
46#[non_exhaustive]
47pub struct Variant {
48    /// The value on the wire.
49    pub value: i64,
50    /// The variant name.
51    pub name: String,
52    /// Documentation.
53    pub doc: Option<String>,
54}
55
56impl Variant {
57    /// `name = value`, undocumented.
58    #[must_use]
59    pub fn new(value: i64, name: &str) -> Self {
60        Self { value, name: String::from(name), doc: None }
61    }
62
63    /// Sets the documentation.
64    #[must_use]
65    pub fn with_doc(self, doc: &str) -> Self {
66        Self { doc: Some(String::from(doc)), ..self }
67    }
68}