1 use std::str::FromStr;
2 
3 use crate::array_of_tables::ArrayOfTables;
4 use crate::datetime::*;
5 use crate::table::TableLike;
6 use crate::{Array, InlineTable, Table, Value};
7 
8 /// Type representing either a value, a table, an array of tables, or none.
9 #[derive(Debug, Clone)]
10 pub enum Item {
11     /// Type representing none.
12     None,
13     /// Type representing value.
14     Value(Value),
15     /// Type representing table.
16     Table(Table),
17     /// Type representing array of tables.
18     ArrayOfTables(ArrayOfTables),
19 }
20 
21 impl Item {
22     /// Sets `self` to the given item iff `self` is none and
23     /// returns a mutable reference to `self`.
or_insert(&mut self, item: Item) -> &mut Item24     pub fn or_insert(&mut self, item: Item) -> &mut Item {
25         if self.is_none() {
26             *self = item
27         }
28         self
29     }
30 }
31 // TODO: This should be generated by macro or derive
32 /// Downcasting
33 impl Item {
34     /// Text description of value type
type_name(&self) -> &'static str35     pub fn type_name(&self) -> &'static str {
36         match self {
37             Item::None => "none",
38             Item::Value(v) => v.type_name(),
39             Item::Table(..) => "table",
40             Item::ArrayOfTables(..) => "array of tables",
41         }
42     }
43 
44     /// Index into a TOML array or map. A string index can be used to access a
45     /// value in a map, and a usize index can be used to access an element of an
46     /// array.
47     ///
48     /// Returns `None` if:
49     /// - The type of `self` does not match the type of the
50     ///   index, for example if the index is a string and `self` is an array or a
51     ///   number.
52     /// - The given key does not exist in the map
53     ///   or the given index is not within the bounds of the array.
get<I: crate::index::Index>(&self, index: I) -> Option<&Item>54     pub fn get<I: crate::index::Index>(&self, index: I) -> Option<&Item> {
55         index.index(self)
56     }
57 
58     /// Mutably index into a TOML array or map. A string index can be used to
59     /// access a value in a map, and a usize index can be used to access an
60     /// element of an array.
61     ///
62     /// Returns `None` if:
63     /// - The type of `self` does not match the type of the
64     ///   index, for example if the index is a string and `self` is an array or a
65     ///   number.
66     /// - The given key does not exist in the map
67     ///   or the given index is not within the bounds of the array.
get_mut<I: crate::index::Index>(&mut self, index: I) -> Option<&mut Item>68     pub fn get_mut<I: crate::index::Index>(&mut self, index: I) -> Option<&mut Item> {
69         index.index_mut(self)
70     }
71 
72     /// Casts `self` to value.
as_value(&self) -> Option<&Value>73     pub fn as_value(&self) -> Option<&Value> {
74         match *self {
75             Item::Value(ref v) => Some(v),
76             _ => None,
77         }
78     }
79     /// Casts `self` to table.
as_table(&self) -> Option<&Table>80     pub fn as_table(&self) -> Option<&Table> {
81         match *self {
82             Item::Table(ref t) => Some(t),
83             _ => None,
84         }
85     }
86     /// Casts `self` to array of tables.
as_array_of_tables(&self) -> Option<&ArrayOfTables>87     pub fn as_array_of_tables(&self) -> Option<&ArrayOfTables> {
88         match *self {
89             Item::ArrayOfTables(ref a) => Some(a),
90             _ => None,
91         }
92     }
93     /// Casts `self` to mutable value.
as_value_mut(&mut self) -> Option<&mut Value>94     pub fn as_value_mut(&mut self) -> Option<&mut Value> {
95         match *self {
96             Item::Value(ref mut v) => Some(v),
97             _ => None,
98         }
99     }
100     /// Casts `self` to mutable table.
as_table_mut(&mut self) -> Option<&mut Table>101     pub fn as_table_mut(&mut self) -> Option<&mut Table> {
102         match *self {
103             Item::Table(ref mut t) => Some(t),
104             _ => None,
105         }
106     }
107     /// Casts `self` to mutable array of tables.
as_array_of_tables_mut(&mut self) -> Option<&mut ArrayOfTables>108     pub fn as_array_of_tables_mut(&mut self) -> Option<&mut ArrayOfTables> {
109         match *self {
110             Item::ArrayOfTables(ref mut a) => Some(a),
111             _ => None,
112         }
113     }
114     /// Casts `self` to value.
into_value(self) -> Result<Value, Self>115     pub fn into_value(self) -> Result<Value, Self> {
116         match self {
117             Item::None => Err(self),
118             Item::Value(v) => Ok(v),
119             Item::Table(v) => Ok(Value::InlineTable(v.into_inline_table())),
120             Item::ArrayOfTables(v) => Ok(Value::Array(v.into_array())),
121         }
122     }
123     /// In-place convert to a value
make_value(&mut self)124     pub fn make_value(&mut self) {
125         let mut other = Item::None;
126         std::mem::swap(self, &mut other);
127         let mut other = other.into_value().map(Item::Value).unwrap_or(Item::None);
128         std::mem::swap(self, &mut other);
129     }
130     /// Casts `self` to table.
into_table(self) -> Result<Table, Self>131     pub fn into_table(self) -> Result<Table, Self> {
132         match self {
133             Item::Table(t) => Ok(t),
134             Item::Value(v) => match v {
135                 Value::InlineTable(t) => Ok(t.into_table()),
136                 _ => Err(Item::Value(v)),
137             },
138             _ => Err(self),
139         }
140     }
141     /// Casts `self` to array of tables.
into_array_of_tables(self) -> Result<ArrayOfTables, Self>142     pub fn into_array_of_tables(self) -> Result<ArrayOfTables, Self> {
143         match self {
144             Item::ArrayOfTables(a) => Ok(a),
145             _ => Err(self),
146         }
147     }
148     /// Returns true iff `self` is a value.
is_value(&self) -> bool149     pub fn is_value(&self) -> bool {
150         self.as_value().is_some()
151     }
152     /// Returns true iff `self` is a table.
is_table(&self) -> bool153     pub fn is_table(&self) -> bool {
154         self.as_table().is_some()
155     }
156     /// Returns true iff `self` is an array of tables.
is_array_of_tables(&self) -> bool157     pub fn is_array_of_tables(&self) -> bool {
158         self.as_array_of_tables().is_some()
159     }
160     /// Returns true iff `self` is `None`.
is_none(&self) -> bool161     pub fn is_none(&self) -> bool {
162         matches!(*self, Item::None)
163     }
164 
165     // Duplicate Value downcasting API
166 
167     /// Casts `self` to integer.
as_integer(&self) -> Option<i64>168     pub fn as_integer(&self) -> Option<i64> {
169         self.as_value().and_then(Value::as_integer)
170     }
171 
172     /// Returns true iff `self` is an integer.
is_integer(&self) -> bool173     pub fn is_integer(&self) -> bool {
174         self.as_integer().is_some()
175     }
176 
177     /// Casts `self` to float.
as_float(&self) -> Option<f64>178     pub fn as_float(&self) -> Option<f64> {
179         self.as_value().and_then(Value::as_float)
180     }
181 
182     /// Returns true iff `self` is a float.
is_float(&self) -> bool183     pub fn is_float(&self) -> bool {
184         self.as_float().is_some()
185     }
186 
187     /// Casts `self` to boolean.
as_bool(&self) -> Option<bool>188     pub fn as_bool(&self) -> Option<bool> {
189         self.as_value().and_then(Value::as_bool)
190     }
191 
192     /// Returns true iff `self` is a boolean.
is_bool(&self) -> bool193     pub fn is_bool(&self) -> bool {
194         self.as_bool().is_some()
195     }
196 
197     /// Casts `self` to str.
as_str(&self) -> Option<&str>198     pub fn as_str(&self) -> Option<&str> {
199         self.as_value().and_then(Value::as_str)
200     }
201 
202     /// Returns true iff `self` is a string.
is_str(&self) -> bool203     pub fn is_str(&self) -> bool {
204         self.as_str().is_some()
205     }
206 
207     /// Casts `self` to date-time.
as_datetime(&self) -> Option<&Datetime>208     pub fn as_datetime(&self) -> Option<&Datetime> {
209         self.as_value().and_then(Value::as_datetime)
210     }
211 
212     /// Returns true iff `self` is a date-time.
is_datetime(&self) -> bool213     pub fn is_datetime(&self) -> bool {
214         self.as_datetime().is_some()
215     }
216 
217     /// Casts `self` to array.
as_array(&self) -> Option<&Array>218     pub fn as_array(&self) -> Option<&Array> {
219         self.as_value().and_then(Value::as_array)
220     }
221 
222     /// Casts `self` to mutable array.
as_array_mut(&mut self) -> Option<&mut Array>223     pub fn as_array_mut(&mut self) -> Option<&mut Array> {
224         self.as_value_mut().and_then(Value::as_array_mut)
225     }
226 
227     /// Returns true iff `self` is an array.
is_array(&self) -> bool228     pub fn is_array(&self) -> bool {
229         self.as_array().is_some()
230     }
231 
232     /// Casts `self` to inline table.
as_inline_table(&self) -> Option<&InlineTable>233     pub fn as_inline_table(&self) -> Option<&InlineTable> {
234         self.as_value().and_then(Value::as_inline_table)
235     }
236 
237     /// Casts `self` to mutable inline table.
as_inline_table_mut(&mut self) -> Option<&mut InlineTable>238     pub fn as_inline_table_mut(&mut self) -> Option<&mut InlineTable> {
239         self.as_value_mut().and_then(Value::as_inline_table_mut)
240     }
241 
242     /// Returns true iff `self` is an inline table.
is_inline_table(&self) -> bool243     pub fn is_inline_table(&self) -> bool {
244         self.as_inline_table().is_some()
245     }
246 
247     /// Casts `self` to either a table or an inline table.
as_table_like(&self) -> Option<&dyn TableLike>248     pub fn as_table_like(&self) -> Option<&dyn TableLike> {
249         self.as_table()
250             .map(|t| t as &dyn TableLike)
251             .or_else(|| self.as_inline_table().map(|t| t as &dyn TableLike))
252     }
253 
254     /// Casts `self` to either a table or an inline table.
as_table_like_mut(&mut self) -> Option<&mut dyn TableLike>255     pub fn as_table_like_mut(&mut self) -> Option<&mut dyn TableLike> {
256         match self {
257             Item::Table(t) => Some(t as &mut dyn TableLike),
258             Item::Value(Value::InlineTable(t)) => Some(t as &mut dyn TableLike),
259             _ => None,
260         }
261     }
262 
263     /// Returns true iff `self` is either a table, or an inline table.
is_table_like(&self) -> bool264     pub fn is_table_like(&self) -> bool {
265         self.as_table_like().is_some()
266     }
267 }
268 
269 impl Default for Item {
default() -> Self270     fn default() -> Self {
271         Item::None
272     }
273 }
274 
275 impl FromStr for Item {
276     type Err = crate::TomlError;
277 
278     /// Parses a value from a &str
from_str(s: &str) -> Result<Self, Self::Err>279     fn from_str(s: &str) -> Result<Self, Self::Err> {
280         let value = s.parse::<Value>()?;
281         Ok(Item::Value(value))
282     }
283 }
284 
285 impl std::fmt::Display for Item {
fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result286     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
287         match &self {
288             Item::None => Ok(()),
289             Item::Value(v) => v.fmt(f),
290             Item::Table(v) => v.fmt(f),
291             Item::ArrayOfTables(v) => v.fmt(f),
292         }
293     }
294 }
295 
296 /// Returns a formatted value.
297 ///
298 /// Since formatting is part of a `Value`, the right hand side of the
299 /// assignment needs to be decorated with a space before the value.
300 /// The `value` function does just that.
301 ///
302 /// # Examples
303 /// ```rust
304 /// # use pretty_assertions::assert_eq;
305 /// # use toml_edit::*;
306 /// let mut table = Table::default();
307 /// let mut array = Array::default();
308 /// array.push("hello");
309 /// array.push("\\, world"); // \ is only allowed in a literal string
310 /// table["key1"] = value("value1");
311 /// table["key2"] = value(42);
312 /// table["key3"] = value(array);
313 /// assert_eq!(table.to_string(),
314 /// r#"key1 = "value1"
315 /// key2 = 42
316 /// key3 = ["hello", '\, world']
317 /// "#);
318 /// ```
value<V: Into<Value>>(v: V) -> Item319 pub fn value<V: Into<Value>>(v: V) -> Item {
320     Item::Value(v.into().decorated(" ", ""))
321 }
322 
323 /// Returns an empty table.
table() -> Item324 pub fn table() -> Item {
325     Item::Table(Table::new())
326 }
327 
328 /// Returns an empty array of tables.
array() -> Item329 pub fn array() -> Item {
330     Item::ArrayOfTables(ArrayOfTables::new())
331 }
332