hocon_rs/raw/
field.rs

1use crate::raw::comment::Comment;
2use crate::raw::include::Inclusion;
3use crate::raw::raw_string::RawString;
4use crate::raw::raw_value::RawValue;
5use std::fmt::{Display, Formatter};
6
7#[derive(Debug, Clone, PartialEq, Eq, Hash)]
8pub enum ObjectField {
9    Inclusion {
10        inclusion: Inclusion,
11        comment: Option<Comment>,
12    },
13    KeyValue {
14        key: RawString,
15        value: RawValue,
16        comment: Option<Comment>,
17    },
18    NewlineComment(Comment),
19}
20
21impl ObjectField {
22    pub fn inclusion(inclusion: Inclusion) -> ObjectField {
23        ObjectField::Inclusion {
24            inclusion,
25            comment: None,
26        }
27    }
28
29    pub fn inclusion_with_comment(
30        inclusion: Inclusion,
31        comment: impl Into<Comment>,
32    ) -> ObjectField {
33        ObjectField::Inclusion {
34            inclusion,
35            comment: Some(comment.into()),
36        }
37    }
38
39    pub fn key_value(key: impl Into<RawString>, value: impl Into<RawValue>) -> ObjectField {
40        ObjectField::KeyValue {
41            key: key.into(),
42            value: value.into(),
43            comment: None,
44        }
45    }
46
47    pub fn key_value_with_comment(
48        key: impl Into<RawString>,
49        value: impl Into<RawValue>,
50        comment: impl Into<Comment>,
51    ) -> ObjectField {
52        ObjectField::KeyValue {
53            key: key.into(),
54            value: value.into(),
55            comment: Some(comment.into()),
56        }
57    }
58
59    pub fn newline_comment(comment: impl Into<Comment>) -> ObjectField {
60        ObjectField::NewlineComment(comment.into())
61    }
62
63    pub fn set_comment(&mut self, comment: Comment) {
64        match self {
65            ObjectField::Inclusion { comment: c, .. }
66            | ObjectField::KeyValue { comment: c, .. } => *c = Some(comment),
67            ObjectField::NewlineComment(c) => *c = comment,
68        }
69    }
70}
71
72impl Display for ObjectField {
73    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
74        match self {
75            ObjectField::Inclusion { inclusion, comment } => {
76                write!(f, "{}", inclusion)?;
77                if let Some(comment) = comment {
78                    write!(f, " {}", comment)?;
79                }
80            }
81            ObjectField::KeyValue {
82                key,
83                value,
84                comment,
85            } => {
86                write!(f, "{}: {}", key, value)?;
87                if let Some(comment) = comment {
88                    write!(f, " {}", comment)?;
89                }
90            }
91            ObjectField::NewlineComment(c) => {
92                write!(f, "{}", c)?;
93            }
94        }
95        Ok(())
96    }
97}