Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 10 additions & 6 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -494,20 +494,24 @@ where
.as_array()
.ok_or_else(|| err_json(value, "array"))
.and_then(|curr| {
// Verify legal index in bounds
let len = curr.len() as i64;

if !(-len..len).contains(&index) {
let index = if index < 0 { len + index } else { index };
if !(0..=len).contains(&index) {
return Err("ERR index out of bounds".into());
}
let index = index as usize;

let index = index.normalize(len);

let items: Vec<Value> = args
let mut items = args
.map(|json| serde_json::from_str(&json))
.collect::<Result<_, _>>()?;

let mut new_value = curr.to_owned();
new_value.splice(index..index, items.into_iter());
if new_value.len() == index {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The value of index after calling normalize in line 503, is between 0 and curr.len() - 1 (inclusive),
so we can detect before calling normailze, whether to append at the end, or to insert,
For example:

let should_append = index >= len;
let index = index.normalize(len);
...
if should_append {
    new_value.append(...);

So for doc test:
json.set test $ '["a", "b", "c"]'
We can insert before "c"
by
JSON.ARRINSERT test $ 2 '"d"'
and get ["a", "b", "d", "c"]
Or we can append after "c"
by
JSON.ARRINSERT test $ 3 '"d"'
and get ["a", "b", "c", "d"]

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems we should also adjust the documentation accordingly.
Currently it says:
The index must be in the array's range.

new_value.append(&mut items);
} else {
new_value.splice(index..index, items.into_iter());
}

Ok(Value::Array(new_value))
})
Expand Down