]> Cypherpunks repositories - gostls13.git/commitdiff
bytes: make Join return a new buffer on len(a) == 1
authorGustavo Niemeyer <gustavo@niemeyer.net>
Fri, 20 Jul 2012 19:04:22 +0000 (16:04 -0300)
committerGustavo Niemeyer <gustavo@niemeyer.net>
Fri, 20 Jul 2012 19:04:22 +0000 (16:04 -0300)
Fixes #3844.

R=golang-dev, r
CC=golang-dev
https://golang.org/cl/6432054

src/pkg/bytes/bytes.go
src/pkg/bytes/bytes_test.go

index 09b3c1a2705500d79d8096fc41fd4156a33116e6..c3980bb2ab56a3308fa94b7a1baba67058231c3e 100644 (file)
@@ -333,14 +333,15 @@ func FieldsFunc(s []byte, f func(rune) bool) [][]byte {
        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.
 func Join(a [][]byte, sep []byte) []byte {
        if len(a) == 0 {
                return []byte{}
        }
        if len(a) == 1 {
-               return a[0]
+               // Just return a copy.
+               return append([]byte(nil), a[0]...)
        }
        n := len(sep) * (len(a) - 1)
        for i := 0; i < len(a); i++ {
@@ -619,10 +620,8 @@ func Replace(s, old, new []byte, n int) []byte {
                m = Count(s, old)
        }
        if m == 0 {
-               // Nothing to do. Just copy.
-               t := make([]byte, len(s))
-               copy(t, s)
-               return t
+               // Just return a copy.
+               return append([]byte(nil), s...)
        }
        if n < 0 || m < n {
                n = m
index 000f235176df8d7a01f42dba4f095dd6cfa9ff4e..0e2ef504cfc599a3d0767d7d64bc3715049d14f7 100644 (file)
@@ -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)
                        }
                }
+               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)
+                       }
+               }
        }
 }