Skip to content

Commit

Permalink
add methods to insert and replace values in an array
Browse files Browse the repository at this point in the history
Add both formatted and regular versions of these
methods. The regular replace method preserves
existing formatting.
  • Loading branch information
sunshowers committed Jun 18, 2020
1 parent 29eab2c commit 5dcbd28
Show file tree
Hide file tree
Showing 3 changed files with 77 additions and 10 deletions.
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,8 @@ mod table;
mod value;

pub use crate::array_of_tables::ArrayOfTables;
pub use crate::document::Document;
pub use crate::decor::Decor;
pub use crate::document::Document;
pub use crate::key::Key;
pub use crate::parser::TomlError;
pub use crate::table::{array, table, value, Item, Iter, Table, TableLike};
Expand Down
71 changes: 65 additions & 6 deletions src/value.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use crate::decor::{Decor, Formatted, InternalString};
use crate::formatted;
use crate::key::Key;
use crate::parser;
use crate::table::{Item, Iter, KeyValuePairs, TableKeyValue, TableLike};
use crate::{decorated, formatted};
use chrono::{self, FixedOffset};
use combine::stream::state::State;
use linked_hash_map::LinkedHashMap;
Expand Down Expand Up @@ -103,14 +103,69 @@ impl Array {
///
/// Returns an error if the value was of a different type than the values in the array.
pub fn push<V: Into<Value>>(&mut self, v: V) -> Result<(), Value> {
self.push_value(v.into(), true)
self.value_op(v.into(), true, |items, value| {
items.push(Item::Value(value))
})
}

/// Appends a new, already formatted value to the end of the array.
///
/// Returns an error if the value was of a different type than the array.
pub fn push_formatted(&mut self, v: Value) -> Result<(), Value> {
self.push_value(v, false)
self.value_op(v, false, |items, value| items.push(Item::Value(value)))
}

/// Inserts an element at the given position within the array, applying default formatting to
/// it and shifting all values after it to the right.
///
/// Returns an error if the value was of a different type than the values in the array.
///
/// Panics if `index > len`.
pub fn insert<V: Into<Value>>(&mut self, index: usize, v: V) -> Result<(), Value> {
self.value_op(v.into(), true, |items, value| {
items.insert(index, Item::Value(value))
})
}

/// Inserts an already formatted value at the given position within the array, shifting all
/// values after it to the right.
///
/// Returns an error if the value was of a different type than the values in the array.
///
/// Panics if `index > len`.
pub fn insert_formatted(&mut self, index: usize, v: Value) -> Result<(), Value> {
self.value_op(v, false, |items, value| {
items.insert(index, Item::Value(value))
})
}

/// Replaces the element at the given position within the array, preserving existing formatting.
///
/// Returns an error if the replacement was of a different type than the values in the array.
///
/// Panics if `index >= len`.
pub fn replace<V: Into<Value>>(&mut self, index: usize, v: V) -> Result<Value, 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 value = decorated(v.into(), existing_decor.prefix(), existing_decor.suffix());
self.replace_formatted(index, value)
}

/// Replaces the element at the given position within the array with an already formatted value.
///
/// Returns an error if the replacement was of a different type than the values in the array.
///
/// Panics if `index >= len`.
pub fn replace_formatted(&mut self, index: usize, v: Value) -> Result<Value, Value> {
self.value_op(v, false, |items, value| {
match mem::replace(&mut items[index], Item::Value(value)) {
Item::Value(old_value) => old_value,
x => panic!("non-value item {:?} in an array", x),
}
})
}

/// Returns a reference to the value at the given index, or `None` if the index is out of
Expand All @@ -136,16 +191,20 @@ impl Array {
formatted::decorate_array(self);
}

pub(crate) fn push_value(&mut self, v: Value, decorate: bool) -> Result<(), Value> {
fn value_op<T>(
&mut self,
v: Value,
decorate: bool,
op: impl FnOnce(&mut Vec<Item>, Value) -> T,
) -> Result<T, Value> {
let mut value = v;
if !self.is_empty() && decorate {
formatted::decorate(&mut value, " ", "");
} else if decorate {
formatted::decorate(&mut value, "", "");
}
if self.is_empty() || value.get_type() == self.value_type() {
self.values.push(Item::Value(value));
Ok(())
Ok(op(&mut self.values, value))
} else {
Err(value)
}
Expand Down
14 changes: 11 additions & 3 deletions tests/test_edit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -462,7 +462,7 @@ macro_rules! as_array {
}

#[test]
fn test_insert_into_array() {
fn test_insert_replace_into_array() {
given(r#"
a = [1,2,3]
b = []"#
Expand All @@ -485,14 +485,22 @@ fn test_insert_into_array() {
assert!(b.push_formatted(decorated("world".into(), "\n", "\n")).is_ok());
assert!(b.push_formatted(decorated("test".into(), "", "")).is_ok());

assert!(b.insert(1, "beep").is_ok());
assert!(b.insert_formatted(2, decorated("boop".into(), " ", " ")).is_ok());

// This should preserve formatting.
assert_eq!(b.replace(2, "zoink").unwrap().as_str(), Some("boop"));
// This should replace formatting.
assert_eq!(b.replace_formatted(4, decorated("yikes".into(), " ", "")).unwrap().as_str(), Some("test"));

// Check that pushing a different type into an array fails.
assert!(b.push(42).is_err());

}).produces(r#"
a = [1, 2, 3, 4]
b = ["hello",
b = ["hello", "beep", "zoink" ,
"world"
,"test"]
, "yikes"]
"#
);
}
Expand Down

0 comments on commit 5dcbd28

Please sign in to comment.