Expand description
Document tree traversal to mutate an exclusive borrow of a document tree in place.
Each method of the VisitMut
trait is a hook that can be overridden
to customize the behavior when mutating the corresponding type of node.
By default, every method recursively visits the substructure of the
input by invoking the right visitor method of each of its fields.
pub trait VisitMut {
/* ... */
fn visit_item_mut(&mut self, i: &mut Item) {
visit_item_mut(self, i);
}
/* ... */
}
pub fn visit_item_mut<V>(v: &mut V, node: &mut Item)
where
V: VisitMut + ?Sized,
{
match node {
Item::None => {}
Item::Value(value) => v.visit_value_mut(value),
Item::Table(table) => v.visit_table_mut(table),
Item::ArrayOfTables(array) => v.visit_array_of_tables_mut(array),
}
}
The API is modeled after syn::visit_mut
.
§Examples
This visitor replaces every floating point value with its decimal string representation, to 2 decimal points.
use toml_edit::visit_mut::*;
struct FloatToString;
impl VisitMut for FloatToString {
fn visit_value_mut(&mut self, node: &mut Value) {
if let Value::Float(f) = node {
// Convert the float to a string.
let mut s = Formatted::new(format!("{:.2}", f.value()));
// Copy over the formatting.
std::mem::swap(s.decor_mut(), f.decor_mut());
*node = Value::String(s);
}
// Most of the time, you will also need to call the default implementation to recurse
// further down the document tree.
visit_value_mut(self, node);
}
}
let input = r#"
banana = 3.26
table = { apple = 4.5 }
"#;
let mut document: DocumentMut = input.parse().unwrap();
let mut visitor = FloatToString;
visitor.visit_document_mut(&mut document);
let output = r#"
banana = "3.26"
table = { apple = "4.50" }
"#;
assert_eq!(format!("{}", document), output);
For a more complex example where the visitor has internal state, see examples/visit.rs
on GitHub.
Traits§
- Document tree traversal to mutate an exclusive borrow of a document tree in-place.