codegen_rs/
variant.rs

1use std::fmt::{self, Write};
2
3use crate::fields::Fields;
4use crate::formatter::Formatter;
5use crate::docs::Docs;
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
14    /// Variant documentation
15    docs: Option<Docs>,
16}
17
18impl Variant {
19    /// Return a new enum variant with the given name.
20    pub fn new(name: &str) -> Self {
21        Self {
22            name: name.to_string(),
23            fields: Fields::Empty,
24            docs: None,
25        }
26    }
27
28    /// Add a named field to the variant.
29    pub fn named<T>(&mut self, name: &str, ty: T) -> &mut Self
30    where
31        T: Into<Type>,
32    {
33        self.fields.named(name, ty);
34        self
35    }
36
37    /// Add a tuple field to the variant.
38    pub fn tuple(&mut self, ty: &str) -> &mut Self {
39        self.fields.tuple(ty);
40        self
41    }
42
43    /// Set the variant documentation.
44    pub fn doc(&mut self, docs: &str) -> &mut Self {
45        self.docs = Some(Docs::new(docs));
46        self
47    }
48
49    /// Formats the variant using the given formatter.
50    pub fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
51        if let Some(ref docs) = self.docs {
52            docs.fmt(fmt)?;
53        }
54        write!(fmt, "{}", self.name)?;
55        self.fields.fmt(fmt)?;
56        writeln!(fmt, ",")?;
57
58        Ok(())
59    }
60}