Enum toml_edit::Value

source ·
pub enum Value {
    String(Formatted<String>),
    Integer(Formatted<i64>),
    Float(Formatted<f64>),
    Boolean(Formatted<bool>),
    Datetime(Formatted<Datetime>),
    Array(Array),
    InlineTable(InlineTable),
}
Expand description

Representation of a TOML Value (as part of a Key/Value Pair).

Variants§

§

String(Formatted<String>)

A string value.

§

Integer(Formatted<i64>)

A 64-bit integer value.

§

Float(Formatted<f64>)

A 64-bit float value.

§

Boolean(Formatted<bool>)

A boolean value.

§

Datetime(Formatted<Datetime>)

An RFC 3339 formatted date-time with offset.

§

Array(Array)

An inline array of values.

§

InlineTable(InlineTable)

An inline table of key/value pairs.

Implementations§

Downcasting

Text description of value type

Examples found in repository?
src/item.rs (line 40)
37
38
39
40
41
42
43
44
    pub fn type_name(&self) -> &'static str {
        match self {
            Item::None => "none",
            Item::Value(v) => v.type_name(),
            Item::Table(..) => "table",
            Item::ArrayOfTables(..) => "array of tables",
        }
    }
More examples
Hide additional examples
src/parser/inline_table.rs (line 74)
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
fn descend_path<'a>(
    mut table: &'a mut InlineTable,
    path: &'a [Key],
) -> Result<&'a mut InlineTable, CustomError> {
    for (i, key) in path.iter().enumerate() {
        let entry = table.entry_format(key).or_insert_with(|| {
            let mut new_table = InlineTable::new();
            new_table.set_dotted(true);

            Value::InlineTable(new_table)
        });
        match *entry {
            Value::InlineTable(ref mut sweet_child_of_mine) => {
                table = sweet_child_of_mine;
            }
            ref v => {
                return Err(CustomError::extend_wrong_type(path, i, v.type_name()));
            }
        }
    }
    Ok(table)
}
src/parser/state.rs (line 194)
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
    pub(crate) fn descend_path<'t, 'k>(
        mut table: &'t mut Table,
        path: &'k [Key],
        dotted: bool,
    ) -> Result<&'t mut Table, CustomError> {
        for (i, key) in path.iter().enumerate() {
            let entry = table.entry_format(key).or_insert_with(|| {
                let mut new_table = Table::new();
                new_table.set_implicit(true);
                new_table.set_dotted(dotted);

                Item::Table(new_table)
            });
            match *entry {
                Item::Value(ref v) => {
                    return Err(CustomError::extend_wrong_type(path, i, v.type_name()));
                }
                Item::ArrayOfTables(ref mut array) => {
                    debug_assert!(!array.is_empty());

                    let index = array.len() - 1;
                    let last_child = array.get_mut(index).unwrap();

                    table = last_child;
                }
                Item::Table(ref mut sweet_child_of_mine) => {
                    table = sweet_child_of_mine;
                }
                _ => unreachable!(),
            }
        }
        Ok(table)
    }

Casts self to str.

Examples found in repository?
src/value.rs (line 55)
54
55
56
    pub fn is_str(&self) -> bool {
        self.as_str().is_some()
    }

Returns true iff self is a string.

Casts self to integer.

Examples found in repository?
src/value.rs (line 68)
67
68
69
    pub fn is_integer(&self) -> bool {
        self.as_integer().is_some()
    }

Returns true iff self is an integer.

Casts self to float.

Examples found in repository?
src/value.rs (line 81)
80
81
82
    pub fn is_float(&self) -> bool {
        self.as_float().is_some()
    }

Returns true iff self is a float.

Casts self to boolean.

Examples found in repository?
src/value.rs (line 94)
93
94
95
    pub fn is_bool(&self) -> bool {
        self.as_bool().is_some()
    }

Returns true iff self is a boolean.

Casts self to date-time.

Examples found in repository?
src/value.rs (line 107)
106
107
108
    pub fn is_datetime(&self) -> bool {
        self.as_datetime().is_some()
    }

Returns true iff self is a date-time.

Casts self to array.

Examples found in repository?
src/value.rs (line 128)
127
128
129
    pub fn is_array(&self) -> bool {
        self.as_array().is_some()
    }
More examples
Hide additional examples
src/index.rs (line 22)
19
20
21
22
23
24
25
    fn index<'v>(&self, v: &'v Item) -> Option<&'v Item> {
        match *v {
            Item::ArrayOfTables(ref aot) => aot.values.get(*self),
            Item::Value(ref a) if a.is_array() => a.as_array().and_then(|a| a.values.get(*self)),
            _ => None,
        }
    }

Casts self to mutable array.

Examples found in repository?
src/index.rs (line 29)
26
27
28
29
30
31
32
    fn index_mut<'v>(&self, v: &'v mut Item) -> Option<&'v mut Item> {
        match *v {
            Item::ArrayOfTables(ref mut vec) => vec.values.get_mut(*self),
            Item::Value(ref mut a) => a.as_array_mut().and_then(|a| a.values.get_mut(*self)),
            _ => None,
        }
    }

Returns true iff self is an array.

Examples found in repository?
src/index.rs (line 22)
19
20
21
22
23
24
25
    fn index<'v>(&self, v: &'v Item) -> Option<&'v Item> {
        match *v {
            Item::ArrayOfTables(ref aot) => aot.values.get(*self),
            Item::Value(ref a) if a.is_array() => a.as_array().and_then(|a| a.values.get(*self)),
            _ => None,
        }
    }

Casts self to inline table.

Examples found in repository?
src/value.rs (line 149)
148
149
150
    pub fn is_inline_table(&self) -> bool {
        self.as_inline_table().is_some()
    }
More examples
Hide additional examples
src/index.rs (line 40)
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
    fn index<'v>(&self, v: &'v Item) -> Option<&'v Item> {
        match *v {
            Item::Table(ref t) => t.get(self),
            Item::Value(ref v) => v
                .as_inline_table()
                .and_then(|t| t.items.get(self))
                .and_then(|kv| {
                    if !kv.value.is_none() {
                        Some(&kv.value)
                    } else {
                        None
                    }
                }),
            _ => None,
        }
    }
src/table.rs (line 85)
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
    fn append_values<'s, 'c>(
        &'s self,
        parent: &[&'s Key],
        values: &'c mut Vec<(Vec<&'s Key>, &'s Value)>,
    ) {
        for value in self.items.values() {
            let mut path = parent.to_vec();
            path.push(&value.key);
            match &value.value {
                Item::Table(table) if table.is_dotted() => {
                    table.append_values(&path, values);
                }
                Item::Value(value) => {
                    if let Some(table) = value.as_inline_table() {
                        if table.is_dotted() {
                            table.append_values(&path, values);
                        } else {
                            values.push((path, value));
                        }
                    } else {
                        values.push((path, value));
                    }
                }
                _ => {}
            }
        }
    }

Casts self to mutable inline table.

Examples found in repository?
src/index.rs (line 63)
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
    fn index_mut<'v>(&self, v: &'v mut Item) -> Option<&'v mut Item> {
        if let Item::None = *v {
            let mut t = InlineTable::default();
            t.items.insert(
                InternalString::from(self),
                TableKeyValue::new(Key::new(self), Item::None),
            );
            *v = value(Value::InlineTable(t));
        }
        match *v {
            Item::Table(ref mut t) => Some(t.entry(self).or_insert(Item::None)),
            Item::Value(ref mut v) => v.as_inline_table_mut().map(|t| {
                &mut t
                    .items
                    .entry(InternalString::from(self))
                    .or_insert_with(|| TableKeyValue::new(Key::new(self), Item::None))
                    .value
            }),
            _ => None,
        }
    }

Returns true iff self is an inline table.

Examples found in repository?
src/item.rs (line 152)
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
    pub fn into_array_of_tables(self) -> Result<ArrayOfTables, Self> {
        match self {
            Item::ArrayOfTables(a) => Ok(a),
            Item::Value(Value::Array(a)) => {
                if a.is_empty() {
                    Err(Item::Value(Value::Array(a)))
                } else if a.iter().all(|v| v.is_inline_table()) {
                    let mut aot = ArrayOfTables::new();
                    aot.values = a.values;
                    for value in aot.values.iter_mut() {
                        value.make_item();
                    }
                    Ok(aot)
                } else {
                    Err(Item::Value(Value::Array(a)))
                }
            }
            _ => Err(self),
        }
    }

Get the decoration of the value.

Example
let v = toml_edit::Value::from(true);
assert_eq!(v.decor().suffix(), None);
Examples found in repository?
src/ser/pretty.rs (line 26)
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
    fn visit_value_mut(&mut self, node: &mut crate::Value) {
        node.decor_mut().clear();

        crate::visit_mut::visit_value_mut(self, node);
    }

    fn visit_array_mut(&mut self, node: &mut crate::Array) {
        crate::visit_mut::visit_array_mut(self, node);

        if (0..=1).contains(&node.len()) {
            node.set_trailing("");
            node.set_trailing_comma(false);
        } else {
            for item in node.iter_mut() {
                item.decor_mut().set_prefix("\n    ");
            }
            node.set_trailing("\n");
            node.set_trailing_comma(true);
        }
    }
More examples
Hide additional examples
src/value.rs (line 204)
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
    pub(crate) fn decorate(&mut self, prefix: &str, suffix: &str) {
        let decor = self.decor_mut();
        *decor = Decor::new(prefix, suffix);
    }
}

impl FromStr for Value {
    type Err = parser::TomlError;

    /// Parses a value from a &str
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        use nom8::prelude::*;

        let b = s.as_bytes();
        let parsed = parser::value::value.parse(b).finish();
        match parsed {
            Ok(mut value) => {
                // Only take the repr and not decor, as its probably not intended
                value.decor_mut().clear();
                Ok(value)
            }
            Err(e) => Err(Self::Err::new(e, b)),
        }
    }
src/table.rs (line 452)
444
445
446
447
448
449
450
451
452
453
454
fn decorate_table(table: &mut Table) {
    for (key_decor, value) in table
        .items
        .iter_mut()
        .filter(|&(_, ref kv)| kv.value.is_value())
        .map(|(_, kv)| (&mut kv.key.decor, kv.value.as_value_mut().unwrap()))
    {
        key_decor.clear();
        value.decor_mut().clear();
    }
}
src/inline_table.rs (line 398)
390
391
392
393
394
395
396
397
398
399
400
fn decorate_inline_table(table: &mut InlineTable) {
    for (key_decor, value) in table
        .items
        .iter_mut()
        .filter(|&(_, ref kv)| kv.value.is_value())
        .map(|(_, kv)| (&mut kv.key.decor, kv.value.as_value_mut().unwrap()))
    {
        key_decor.clear();
        value.decor_mut().clear();
    }
}
src/array.rs (line 244)
237
238
239
240
241
242
243
244
245
246
    pub fn replace<V: Into<Value>>(&mut self, index: usize, v: V) -> Value {
        // Read the existing value's decor and preserve it.
        let existing_decor = self
            .get(index)
            .unwrap_or_else(|| panic!("index {} out of bounds (len = {})", index, self.len()))
            .decor();
        let mut value = v.into();
        *value.decor_mut() = existing_decor.clone();
        self.replace_formatted(index, value)
    }

Get the decoration of the value.

Example
let v = toml_edit::Value::from(true);
assert_eq!(v.decor().suffix(), None);
Examples found in repository?
src/array.rs (line 242)
237
238
239
240
241
242
243
244
245
246
    pub fn replace<V: Into<Value>>(&mut self, index: usize, v: V) -> Value {
        // Read the existing value's decor and preserve it.
        let existing_decor = self
            .get(index)
            .unwrap_or_else(|| panic!("index {} out of bounds (len = {})", index, self.len()))
            .decor();
        let mut value = v.into();
        *value.decor_mut() = existing_decor.clone();
        self.replace_formatted(index, value)
    }

Sets the prefix and the suffix for value.

Example
let mut v = toml_edit::Value::from(42);
assert_eq!(&v.to_string(), "42");
let d = v.decorated(" ", " ");
assert_eq!(&d.to_string(), " 42 ");
Examples found in repository?
src/parser/array.rs (line 64)
61
62
63
64
65
66
67
68
pub(crate) fn array_value(input: Input<'_>) -> IResult<Input<'_>, Value, ParserError<'_>> {
    (ws_comment_newline, value, ws_comment_newline)
        .map_res::<_, _, std::str::Utf8Error>(|(ws1, v, ws2)| {
            let v = v.decorated(std::str::from_utf8(ws1)?, std::str::from_utf8(ws2)?);
            Ok(v)
        })
        .parse(input)
}
More examples
Hide additional examples
src/parser/inline_table.rs (line 116)
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
fn keyval(input: Input<'_>) -> IResult<Input<'_>, (Vec<Key>, TableKeyValue), ParserError<'_>> {
    (
        key,
        cut((
            one_of(KEYVAL_SEP)
                .context(Context::Expected(ParserValue::CharLiteral('.')))
                .context(Context::Expected(ParserValue::CharLiteral('='))),
            (ws, value, ws),
        )),
    )
        .map(|(key, (_, v))| {
            let mut path = key;
            let key = path.pop().expect("grammar ensures at least 1");

            let (pre, v, suf) = v;
            let v = v.decorated(pre, suf);
            (
                path,
                TableKeyValue {
                    key,
                    value: Item::Value(v),
                },
            )
        })
        .parse(input)
}
src/parser/document.rs (line 127)
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
pub(crate) fn parse_keyval(
    input: Input<'_>,
) -> IResult<Input<'_>, (Vec<Key>, TableKeyValue), ParserError<'_>> {
    (
        key,
        cut((
            one_of(KEYVAL_SEP)
                .context(Context::Expected(ParserValue::CharLiteral('.')))
                .context(Context::Expected(ParserValue::CharLiteral('='))),
            (
                ws,
                value,
                line_trailing
                    .context(Context::Expected(ParserValue::CharLiteral('\n')))
                    .context(Context::Expected(ParserValue::CharLiteral('#'))),
            ),
        )),
    )
        .map_res::<_, _, std::str::Utf8Error>(|(key, (_, v))| {
            let mut path = key;
            let key = path.pop().expect("grammar ensures at least 1");

            let (pre, v, suf) = v;
            let suf = std::str::from_utf8(suf)?;
            let v = v.decorated(pre, suf);
            Ok((
                path,
                TableKeyValue {
                    key,
                    value: Item::Value(v),
                },
            ))
        })
        .parse(input)
}

Trait Implementations§

Returns a copy of the value. Read more
Performs copy-assignment from source. Read more
Formats the value using the given formatter. Read more
The error type that can be returned if some error occurs during deserialization.
Require the Deserializer to figure out how to drive the visitor based on what data type is in the input. Read more
Hint that the Deserialize type is expecting a struct with a particular name and fields.
Hint that the Deserialize type is expecting an optional value. Read more
Hint that the Deserialize type is expecting an enum value with a particular name and possible variants.
Hint that the Deserialize type is expecting a bool value.
Hint that the Deserialize type is expecting a u8 value.
Hint that the Deserialize type is expecting a u16 value.
Hint that the Deserialize type is expecting a u32 value.
Hint that the Deserialize type is expecting a u64 value.
Hint that the Deserialize type is expecting an i8 value.
Hint that the Deserialize type is expecting an i16 value.
Hint that the Deserialize type is expecting an i32 value.
Hint that the Deserialize type is expecting an i64 value.
Hint that the Deserialize type is expecting a f32 value.
Hint that the Deserialize type is expecting a f64 value.
Hint that the Deserialize type is expecting a char value.
Hint that the Deserialize type is expecting a string value and does not benefit from taking ownership of buffered data owned by the Deserializer. Read more
Hint that the Deserialize type is expecting a string value and would benefit from taking ownership of buffered data owned by the Deserializer. Read more
Hint that the Deserialize type is expecting a sequence of values.
Hint that the Deserialize type is expecting a byte array and does not benefit from taking ownership of buffered data owned by the Deserializer. Read more
Hint that the Deserialize type is expecting a byte array and would benefit from taking ownership of buffered data owned by the Deserializer. Read more
Hint that the Deserialize type is expecting a map of key-value pairs.
Hint that the Deserialize type is expecting a unit value.
Hint that the Deserialize type is expecting a newtype struct with a particular name.
Hint that the Deserialize type needs to deserialize a value whose type doesn’t matter because it is ignored. Read more
Hint that the Deserialize type is expecting a unit struct with a particular name.
Hint that the Deserialize type is expecting a tuple struct with a particular name and number of fields.
Hint that the Deserialize type is expecting a sequence of values and knows how many values there are without looking at the serialized data.
Hint that the Deserialize type is expecting the name of a struct field or the discriminant of an enum variant.
Hint that the Deserialize type is expecting an i128 value. Read more
Hint that the Deserialize type is expecting an u128 value. Read more
Determine whether Deserialize implementations should expect to deserialize their human-readable form. Read more
Formats the value using the given formatter. Read more
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Converts to this type from the input type.
Creates a value from an iterator. Read more
Creates a value from an iterator. Read more

Parses a value from a &str

The associated error which can be returned from parsing.
The type of the deserializer being converted into.
Convert this value into a deserializer.

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
Converts the given value to a String. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.