mirror of
https://github.com/golang/go.git
synced 2025-12-08 06:10:04 +00:00
bytes: make Join return a new buffer on len(a) == 1
Fixes #3844. R=golang-dev, r CC=golang-dev https://golang.org/cl/6432054
This commit is contained in:
parent
7bf8355dc7
commit
c0efcac6a9
2 changed files with 11 additions and 6 deletions
|
|
@ -333,14 +333,15 @@ func FieldsFunc(s []byte, f func(rune) bool) [][]byte {
|
||||||
return a[0:na]
|
return a[0:na]
|
||||||
}
|
}
|
||||||
|
|
||||||
// Join concatenates the elements of a to create a single byte array. The separator
|
// Join concatenates the elements of a to create a new byte array. The separator
|
||||||
// sep is placed between elements in the resulting array.
|
// sep is placed between elements in the resulting array.
|
||||||
func Join(a [][]byte, sep []byte) []byte {
|
func Join(a [][]byte, sep []byte) []byte {
|
||||||
if len(a) == 0 {
|
if len(a) == 0 {
|
||||||
return []byte{}
|
return []byte{}
|
||||||
}
|
}
|
||||||
if len(a) == 1 {
|
if len(a) == 1 {
|
||||||
return a[0]
|
// Just return a copy.
|
||||||
|
return append([]byte(nil), a[0]...)
|
||||||
}
|
}
|
||||||
n := len(sep) * (len(a) - 1)
|
n := len(sep) * (len(a) - 1)
|
||||||
for i := 0; i < len(a); i++ {
|
for i := 0; i < len(a); i++ {
|
||||||
|
|
@ -619,10 +620,8 @@ func Replace(s, old, new []byte, n int) []byte {
|
||||||
m = Count(s, old)
|
m = Count(s, old)
|
||||||
}
|
}
|
||||||
if m == 0 {
|
if m == 0 {
|
||||||
// Nothing to do. Just copy.
|
// Just return a copy.
|
||||||
t := make([]byte, len(s))
|
return append([]byte(nil), s...)
|
||||||
copy(t, s)
|
|
||||||
return t
|
|
||||||
}
|
}
|
||||||
if n < 0 || m < n {
|
if n < 0 || m < n {
|
||||||
n = m
|
n = m
|
||||||
|
|
|
||||||
|
|
@ -490,6 +490,12 @@ func TestSplit(t *testing.T) {
|
||||||
t.Errorf("Split disagrees withSplitN(%q, %q, %d) = %v; want %v", tt.s, tt.sep, tt.n, b, a)
|
t.Errorf("Split disagrees withSplitN(%q, %q, %d) = %v; want %v", tt.s, tt.sep, tt.n, b, a)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if len(a) > 0 {
|
||||||
|
in, out := a[0], s
|
||||||
|
if cap(in) == cap(out) && &in[:1][0] == &out[:1][0] {
|
||||||
|
t.Errorf("Join(%#v, %q) didn't copy", a, tt.sep)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue