Skip to content

Commit

Permalink
add mutable accessors to Array
Browse files Browse the repository at this point in the history
These accessors make it convenient to do in-place mutation.
  • Loading branch information
sunshowers committed Jun 18, 2020
1 parent 85372f7 commit 296e1cd
Showing 1 changed file with 20 additions and 1 deletion.
21 changes: 20 additions & 1 deletion src/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,9 @@ pub(crate) enum ValueType {
/// An iterator type over `Array`'s values.
pub type ArrayIter<'a> = Box<dyn Iterator<Item = &'a Value> + 'a>;

/// A mutable iterator over `Array` values.
pub type ArrayIterMut<'a> = Box<dyn Iterator<Item = &'a mut Value> + 'a>;

impl Array {
/// Returns the length of the underlying Vec.
/// To get the actual number of items use `a.iter().count()`.
Expand All @@ -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<V: Into<Value>>(&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);
Expand Down

0 comments on commit 296e1cd

Please sign in to comment.