codegen/
variant.rs

1use std::fmt::{self, Write};
2
3use crate::fields::Fields;
4use crate::formatter::Formatter;
5
6use crate::r#type::Type;
7
8/// Defines an enum variant.
9#[derive(Debug, Clone)]
10pub struct Variant {
11    name: String,
12    fields: Fields,
13    /// Annotations for field e.g., `#[serde(rename = "variant")]`.
14    annotations: Vec<String>,
15}
16
17impl Variant {
18    /// Return a new enum variant with the given name.
19    pub fn new(name: impl Into<String>) -> Self {
20        Variant {
21            name: name.into(),
22            fields: Fields::Empty,
23            annotations: Vec::new(),
24        }
25    }
26
27    /// Add a named field to the variant.
28    pub fn named<T>(&mut self, name: &str, ty: T) -> &mut Self
29    where
30        T: Into<Type>,
31    {
32        self.fields.named(name, ty);
33        self
34    }
35
36    /// Add a tuple field to the variant.
37    pub fn tuple(&mut self, ty: &str) -> &mut Self {
38        self.fields.tuple(ty);
39        self
40    }
41
42    /// Add an anotation to the variant.
43    pub fn annotation(&mut self, annotation: impl Into<String>) -> &mut Self {
44        self.annotations.push(annotation.into());
45        self
46    }
47
48    /// Formats the variant using the given formatter.
49    pub fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
50        for a in &self.annotations {
51            write!(fmt, "{}", a)?;
52            write!(fmt, "\n")?;
53        }
54        write!(fmt, "{}", self.name)?;
55        self.fields.fmt(fmt)?;
56        write!(fmt, ",\n")?;
57
58        Ok(())
59    }
60}