mirror of
https://github.com/json-c/json-c.git
synced 2026-03-23 15:09:07 +08:00
json_object: introduce json_object_array_insert_idx() API function
The behavior of the json_object_array_put_idx() is that, if a user wants to insert an element inside a JSON array, the element will be replaced. For some cases, a user would want to insert an element into the JSON array and shift the elements to the right. For indexes that are outside the length of the current array this behaves like json_object_array_put_idx(). If a user wants to enforce that the JSON array is not expanded, then the json_object_array_length() function can be used to guard against that. The main driver for this change is JSON patch, where the 'add' operation in an array means inserting a value at a certain index and shifting everything by one. Signed-off-by: Alexandru Ardelean <ardeleanalex@gmail.com>
This commit is contained in:
committed by
Eric Hawicz
parent
5568916eb1
commit
a86d7a8f5a
21
arraylist.c
21
arraylist.c
@@ -125,6 +125,27 @@ int array_list_shrink(struct array_list *arr, size_t empty_slots)
|
||||
return 0;
|
||||
}
|
||||
|
||||
int array_list_insert_idx(struct array_list *arr, size_t idx, void *data)
|
||||
{
|
||||
size_t move_amount;
|
||||
|
||||
if (idx >= arr->length)
|
||||
return array_list_put_idx(arr, idx, data);
|
||||
|
||||
/* we're at full size, what size_t can support */
|
||||
if (arr->length == SIZE_T_MAX)
|
||||
return -1;
|
||||
|
||||
if (array_list_expand_internal(arr, arr->length + 1))
|
||||
return -1;
|
||||
|
||||
move_amount = (arr->length - idx) * sizeof(void *);
|
||||
memmove(arr->array + idx + 1, arr->array + idx, move_amount);
|
||||
arr->array[idx] = data;
|
||||
arr->length++;
|
||||
return 0;
|
||||
}
|
||||
|
||||
//static inline int _array_list_put_idx(struct array_list *arr, size_t idx, void *data)
|
||||
int array_list_put_idx(struct array_list *arr, size_t idx, void *data)
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user