rust_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    /// The name of the variant.
12    name: String,
13    /// The variant's fields.
14    fields: Fields,
15}
16
17impl Variant {
18    /// Return a new enum variant with the given name.
19    /// 
20    /// # Arguments
21    /// 
22    /// * `name` - The name of the enum variant.
23    /// 
24    /// # Examples
25    /// 
26    /// ```
27    /// use rust_codegen::Variant;
28    /// 
29    /// let foo_variant = Variant::new("Foo");
30    /// ```
31    pub fn new(name: &str) -> Self {
32        Variant {
33            name: name.to_string(),
34            fields: Fields::Empty,
35        }
36    }
37
38    /// Add a named field to the variant.
39    /// 
40    /// # Arguments
41    /// 
42    /// * `name` - The name of the field.
43    /// * `ty` - The type of the field.
44    /// 
45    /// # Examples
46    /// 
47    /// ```
48    /// use rust_codegen::Variant;
49    /// 
50    /// let mut foo_variant = Variant::new("Foo");
51    /// foo_variant.named("Bar", "String");
52    /// ```
53    pub fn named<T>(&mut self, name: &str, ty: T) -> &mut Self
54    where
55        T: Into<Type>,
56    {
57        self.fields.named(name, ty);
58        self
59    }
60
61    /// Add a tuple field to the variant.
62    /// 
63    /// # Arguments
64    /// 
65    /// * `ty` - The type of the tuple.
66    /// 
67    /// # Examples
68    /// 
69    /// ```
70    /// use rust_codegen::Variant;
71    /// 
72    /// let mut foo_variant = Variant::new("Foo");
73    /// foo_variant.tuple("i32");
74    /// ```
75    pub fn tuple(&mut self, ty: &str) -> &mut Self {
76        self.fields.tuple(ty);
77        self
78    }
79
80    /// Formats the variant using the given formatter.
81    /// 
82    /// # Arguments
83    /// 
84    /// * `fmt` - The formatter to use.
85    /// 
86    /// # Examples
87    /// 
88    /// ```
89    /// use rust_codegen::{Formatter,Variant};
90    /// 
91    /// let mut dest = String::new();
92    /// let mut fmt = Formatter::new(&mut dest);
93    /// 
94    /// let mut foo_variant = Variant::new("Foo");
95    /// foo_variant.fmt(&mut fmt);
96    /// ```
97    pub fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
98        write!(fmt, "{}", self.name)?;
99        self.fields.fmt(fmt)?;
100        write!(fmt, ",\n")?;
101
102        Ok(())
103    }
104}