From 296e1cd8f9c3a62c7df7c3b4123d3ef81424fcd9 Mon Sep 17 00:00:00 2001 From: Rain Date: Wed, 17 Jun 2020 20:03:46 -0700 Subject: [PATCH] add mutable accessors to Array These accessors make it convenient to do in-place mutation. --- src/value.rs | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/src/value.rs b/src/value.rs index d2b257e5..00809577 100644 --- a/src/value.rs +++ b/src/value.rs @@ -82,6 +82,9 @@ pub(crate) enum ValueType { /// An iterator type over `Array`'s values. pub type ArrayIter<'a> = Box + 'a>; +/// A mutable iterator over `Array` values. +pub type ArrayIterMut<'a> = Box + 'a>; + impl Array { /// Returns the length of the underlying Vec. /// To get the actual number of items use `a.iter().count()`. @@ -99,17 +102,33 @@ impl Array { Box::new(self.values.iter().filter_map(Item::as_value)) } - /// Appends a new value. + /// Returns a mutable iterator over all values. + pub fn iter_mut(&mut self) -> ArrayIterMut<'_> { + Box::new(self.values.iter_mut().filter_map(Item::as_value_mut)) + } + + /// Appends a new value, applying default formatting to it. pub fn push>(&mut self, v: V) -> bool { self.push_value(v.into(), true) } + /// Appends a new, already formatted value. + pub fn push_formatted(&mut self, value: Value) -> bool { + self.push_value(value, false) + } + /// Returns a reference to the value at the given index, or `None` if the index is out of /// bounds. pub fn get(&self, index: usize) -> Option<&Value> { self.values.get(index).and_then(Item::as_value) } + /// Returns a mutable reference to the value at the given index, or `None` if the index is out + /// of bounds. + pub fn get_mut(&mut self, index: usize) -> Option<&mut Value> { + self.values.get_mut(index).and_then(Item::as_value_mut) + } + /// Removes the value at the given index. pub fn remove(&mut self, index: usize) -> Value { let removed = self.values.remove(index);