introspect_core/enum/builder.rs
1use crate::Enum;
2
3/// An error related to a [`Builder`].
4#[derive(Debug)]
5pub enum Error {
6 /// An identifier was never added to the [`Builder`].
7 MissingIdentifier,
8}
9
10impl std::fmt::Display for Error {
11 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
12 match self {
13 Error::MissingIdentifier => write!(f, "missing identifier"),
14 }
15 }
16}
17
18impl std::error::Error for Error {}
19
20/// A [`Result`](std::result::Result) with an [`Error`].
21pub type Result<T> = std::result::Result<T, Error>;
22
23/// A builder for a [`Enum`].
24#[derive(Debug, Default)]
25pub struct Builder {
26 /// An identifier for the enum.
27 identifier: Option<String>,
28
29 /// The documentation for the enum, if it exists.
30 documentation: Option<String>,
31}
32
33impl Builder {
34 /// Sets the identifier for this [`Builder`].
35 ///
36 /// # Examples
37 ///
38 /// ```
39 /// use introspect_core as core;
40 ///
41 /// let builder = core::r#enum::Builder::default()
42 /// .identifier("Name");
43 /// ```
44 pub fn identifier<S: Into<String>>(mut self, value: S) -> Self {
45 self.identifier = Some(value.into());
46 self
47 }
48
49 /// Sets the documentation for this [`Builder`].
50 ///
51 /// # Examples
52 ///
53 /// ```
54 /// use introspect_core as core;
55 ///
56 /// let builder = core::r#enum::Builder::default()
57 /// .documentation("Documentation.");
58 /// ```
59 pub fn documentation<S: Into<String>>(mut self, value: S) -> Self {
60 self.documentation = Some(value.into());
61 self
62 }
63
64 /// Consume `self` to produce an immutable [`Enum`].
65 ///
66 /// # Examples
67 ///
68 /// ```
69 /// use introspect_core as core;
70 ///
71 /// let enum_ = core::r#enum::Builder::default()
72 /// .identifier("Name")
73 /// .documentation("Documentation.")
74 /// .try_build()?;
75 ///
76 /// # Ok::<(), Box<dyn std::error::Error>>(())
77 /// ```
78 pub fn try_build(self) -> Result<Enum> {
79 let identifier = match self.identifier {
80 Some(identifier) => identifier,
81 None => return Err(Error::MissingIdentifier),
82 };
83
84 Ok(Enum {
85 identifier,
86 documentation: self.documentation,
87 })
88 }
89}