diff options
| author | Bruce Hill <bruce@bruce-hill.com> | 2024-03-08 13:00:29 -0500 |
|---|---|---|
| committer | Bruce Hill <bruce@bruce-hill.com> | 2024-03-08 13:00:29 -0500 |
| commit | 1677d7a1b901f9bf86b566de64339cefddf3c2bd (patch) | |
| tree | 508244819b1f20c3bf9254e8b8c3ff2fdfe2acfb /builtins/array.c | |
| parent | 06549741aa5139ba9f85c33a21f2ed672e1e094f (diff) | |
Fix negative index issue and add array:random()
Diffstat (limited to 'builtins/array.c')
| -rw-r--r-- | builtins/array.c | 14 |
1 files changed, 11 insertions, 3 deletions
diff --git a/builtins/array.c b/builtins/array.c index ee583b5b..93c20bab 100644 --- a/builtins/array.c +++ b/builtins/array.c @@ -44,7 +44,7 @@ public void Array__compact(array_t *arr, const TypeInfo *type) public void Array__insert(array_t *arr, const void *item, int64_t index, const TypeInfo *type) { - if (index < 1) index = arr->length - index + 1; + if (index < 1) index = arr->length + index; if (index < 1) index = 1; else if (index > (int64_t)arr->length + 1) index = (int64_t)arr->length + 1; @@ -79,7 +79,7 @@ public void Array__insert(array_t *arr, const void *item, int64_t index, const T public void Array__insert_all(array_t *arr, array_t to_insert, int64_t index, const TypeInfo *type) { - if (index < 1) index = arr->length - index + 1; + if (index < 1) index = arr->length + index; if (index < 1) index = 1; else if (index > (int64_t)arr->length + 1) index = (int64_t)arr->length + 1; @@ -112,7 +112,7 @@ public void Array__insert_all(array_t *arr, array_t to_insert, int64_t index, co public void Array__remove(array_t *arr, int64_t index, int64_t count, const TypeInfo *type) { - if (index < 1) index = arr->length - index + 1; + if (index < 1) index = arr->length + index; if (index < 1 || index > (int64_t)arr->length || count < 1) return; @@ -171,6 +171,14 @@ public void Array__shuffle(array_t *arr, const TypeInfo *type) } } +public void *Array_random(array_t arr) +{ + if (arr.length == 0) + return NULL; // fail("Cannot get a random item from an empty array!"); + uint32_t index = arc4random_uniform(arr.length); + return arr.data + arr.stride*index; +} + public array_t Array__slice(array_t *array, int64_t first, int64_t stride, int64_t length, const TypeInfo *type) { if (stride > MAX_STRIDE || stride < MIN_STRIDE) |
