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
+1 -12
View File
@@ -1712,18 +1712,7 @@ func extendSlice(v Value, n int) sliceHeader {
old = *(*sliceHeader)(v.value)
}
var nbuf unsafe.Pointer
var nlen, ncap uintptr
if old.len+uintptr(n) > old.cap {
// we need to grow the slice
nbuf, nlen, ncap = sliceGrow(old.data, old.len, old.cap, old.cap+uintptr(n), v.typecode.elem().Size())
} else {
// we can reuse the slice we have
nbuf = old.data
nlen = old.len
ncap = old.cap
}
nbuf, nlen, ncap := sliceGrow(old.data, old.len, old.cap, old.len+uintptr(n), v.typecode.elem().Size())
return sliceHeader{
data: nbuf,