runtime: Simplify slice growing/appending code (#4287)

* reflect: rawFieldByNameFunc: copy index slice to avoid later overwrites

* runtime: Simplify slice growing/appending code

Refactor the slice appending function to rely on the slice growing
function, and remove branches/loops to use a branchfree variant.

Signed-off-by: L. Pereira <l.pereira@fastly.com>

* runtime: Remove one branch in sliceAppend()

Both branches were equivalent, so guard the overall logic in
sliceAppend() with the more general condition.

Signed-off-by: L. Pereira <l.pereira@fastly.com>

* runtime: Simplify slice growing calculation

Use `bits.Len()` rather than `32 - bits.LeadingZeros32()`.  They're
equivalent, but the Len version is a bit easier to read.

Signed-off-by: L. Pereira <l.pereira@fastly.com>

* reflect: Always call sliceGrow() in extendSlice()

sliceGrow() will return the old slice if its capacity is large enough.

Signed-off-by: L. Pereira <l.pereira@fastly.com>

---------

Signed-off-by: L. Pereira <l.pereira@fastly.com>
Co-authored-by: Damian Gryski <damian@gryski.com>
This commit is contained in:
L. Pereira
2024-07-31 13:20:12 -07:00
committed by GitHub
parent 88f9fc3ce2
commit 417a26d20c
4 changed files with 23 additions and 59 deletions
+2 -2
View File
@@ -7,12 +7,12 @@ copy foo -> bar: 3
bar: len=3 cap=5 data: 1 2 4
slice is nil? true true
grow: len=0 cap=0 data:
grow: len=1 cap=1 data: 42
grow: len=1 cap=2 data: 42
grow: len=3 cap=4 data: 42 -1 -2
grow: len=7 cap=8 data: 42 -1 -2 1 2 4 5
grow: len=7 cap=8 data: 42 -1 -2 1 2 4 5
grow: len=14 cap=16 data: 42 -1 -2 1 2 4 5 42 -1 -2 1 2 4 5
bytes: len=6 cap=6 data: 1 2 3 102 111 111
bytes: len=6 cap=8 data: 1 2 3 102 111 111
slice to array pointer: 1 -2 20 4
unsafe.Add array: 1 5 8 4
unsafe.Slice array: 3 3 9 15 4