Skip to content

Commit

Permalink
runtime: rewrite 'appendCap' function and use old cap instead of len
Browse files Browse the repository at this point in the history
This change implements the commit golang/go@2333c62
in Scriggo.

For #385
  • Loading branch information
gazerro committed Jun 26, 2021
1 parent f198ac8 commit 362a1d4
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 10 deletions.
23 changes: 13 additions & 10 deletions runtime/registers.go
Original file line number Diff line number Diff line change
Expand Up @@ -317,15 +317,18 @@ func (vm *VM) setFromReflectValue(r int8, v reflect.Value) registerType {
}
}

func appendCap(c, ol, nl int) int {
if c == 0 {
func appendCap(oc, nl int) int {
if oc == 0 || nl > oc*2 {
return nl
}
if oc < 1024 {
return oc * 2
}
c := oc
for c < nl {
if ol < 1024 {
c += c
} else {
c += c / 4
c += c / 4
if c <= 0 {
c = nl
}
}
return c
Expand All @@ -343,7 +346,7 @@ func (vm *VM) appendSlice(first int8, length int, slice reflect.Value) reflect.V
s = s[:nl]
} else {
old := s
c = appendCap(c, ol, nl)
c = appendCap(c, nl)
s = make([]int, nl, c)
copy(s, old)
}
Expand All @@ -363,7 +366,7 @@ func (vm *VM) appendSlice(first int8, length int, slice reflect.Value) reflect.V
s = s[:nl]
} else {
old := s
c = appendCap(c, ol, nl)
c = appendCap(c, nl)
s = make([]byte, nl, c)
copy(s, old)
}
Expand All @@ -383,7 +386,7 @@ func (vm *VM) appendSlice(first int8, length int, slice reflect.Value) reflect.V
s = s[:nl]
} else {
old := s
c = appendCap(c, ol, nl)
c = appendCap(c, nl)
s = make([]rune, nl, c)
copy(s, old)
}
Expand All @@ -409,7 +412,7 @@ func (vm *VM) appendSlice(first int8, length int, slice reflect.Value) reflect.V
slice = slice.Slice(0, nl)
} else {
old := slice
c = appendCap(c, ol, nl)
c = appendCap(c, nl)
slice = reflect.MakeSlice(slice.Type(), nl, c)
if ol > 0 {
reflect.Copy(slice, old)
Expand Down
19 changes: 19 additions & 0 deletions test/compare/testdata/github.com-golang-go/fixedbugs/issue41239.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// run

// Copyright 2020 The Go Authors. All rights reserved. Use of this
// source code is governed by a BSD-style license that can be found in
// the LICENSE file.

package main

import "fmt"

func main() {
const N = 1024
var a [N]int
x := cap(append(a[:N-1:N], 9, 9))
y := cap(append(a[:N:N], 9))
if x != y {
panic(fmt.Sprintf("different capacity on append: %d vs %d", x, y))
}
}

0 comments on commit 362a1d4

Please sign in to comment.