Skip to content

Commit 3aa96f5

Browse files
authored
Merge pull request #98 from konstin/master
Add `array_remove` to `JsonValue`
2 parents 298e09a + 4500089 commit 3aa96f5

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

src/value/mod.rs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -476,6 +476,22 @@ impl JsonValue {
476476
}
477477
}
478478

479+
/// Works on `JsonValue::Array` - remove an entry and return the value it held.
480+
/// If the method is called on anything but an object or if the index is out of bounds, it
481+
/// will return `JsonValue::Null`.
482+
pub fn array_remove(&mut self, index: usize) -> JsonValue {
483+
match *self {
484+
JsonValue::Array(ref mut vec) => {
485+
if index < vec.len() {
486+
vec.remove(index)
487+
} else {
488+
JsonValue::Null
489+
}
490+
},
491+
_ => JsonValue::Null
492+
}
493+
}
494+
479495
/// When called on an array or an object, will wipe them clean. When called
480496
/// on a string will clear the string. Numbers and booleans become null.
481497
pub fn clear(&mut self) {

tests/value.rs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,16 @@ fn array_pop() {
157157
assert_eq!(data, array![1, 2]);
158158
}
159159

160+
#[test]
161+
fn array_remove() {
162+
let mut data = array![1, 2, 3];
163+
164+
assert_eq!(data.array_remove(1), 2);
165+
assert_eq!(data, array![1, 3]);
166+
// Test with index out of bounds
167+
assert_eq!(data.array_remove(2), JsonValue::Null);
168+
}
169+
160170
#[test]
161171
fn array_members() {
162172
let data = array![1, "foo"];

0 commit comments

Comments
 (0)