avm1: Fix Array.splice

Clamp the index parameters to the length of the array. This fixes
`[].splice(1, 0, 'obj');` to add the object at the proper
position (0, because the start index 1 is larger than the length).
This commit is contained in:
Mike Welsh 2021-04-30 09:47:55 -07:00
parent c465e268bf
commit 2a46c72bb2
4 changed files with 32 additions and 7 deletions

View File

@ -285,14 +285,14 @@ pub fn join<'gc>(
.into()) .into())
} }
fn make_index_absolute(mut index: i32, length: usize) -> usize { /// Handles an index parameter that may be positive (starting from beginning) or negaitve (starting from end).
/// The returned index will be positive and clamped from [0, length].
fn make_index_absolute(index: i32, length: usize) -> usize {
if index < 0 { if index < 0 {
index += length as i32; let offset = index as isize;
} length.saturating_sub((-offset) as usize)
if index < 0 {
0
} else { } else {
index as usize (index as usize).min(length)
} }
} }
@ -365,7 +365,6 @@ pub fn splice<'gc>(
let to_add = if args.len() > 2 { &args[2..] } else { &[] }; let to_add = if args.len() > 2 { &args[2..] } else { &[] };
let offset = to_remove as i32 - to_add.len() as i32; let offset = to_remove as i32 - to_add.len() as i32;
let new_length = old_length + to_add.len() - to_remove; let new_length = old_length + to_add.len() - to_remove;
for i in start..start + to_remove { for i in start..start + to_remove {
removed.set_array_element( removed.set_array_element(
i - start, i - start,

View File

@ -124,4 +124,30 @@ undefined
// splice.length // splice.length
undefined undefined
// splice = original.splice(1, 0, 'a')
// original
a
// original.length
1
// splice
// splice.length
0
// splice = original.splice(-9, 0, 'c')
// original
c,a,b
// original.length
3
// splice
// splice.length
0