Skip to content

Commit 7b45edb

Browse files
author
Martin Möhrmann
committed
bytes: add Clone function
The new Clone function returns a copy of b[:len(b)] for the input byte slice b. The result may have additional unused capacity. Clone(nil) returns nil. Fixes #45038 Change-Id: I0469a202d77a7b491f1341c08915d07ddd1f0300 Reviewed-on: https://go-review.googlesource.com/c/go/+/359675 Run-TryBot: Martin Möhrmann <[email protected]> TryBot-Result: Gopher Robot <[email protected]> Reviewed-by: Joseph Tsai <[email protected]> Reviewed-by: Martin Möhrmann <[email protected]> Reviewed-by: Ian Lance Taylor <[email protected]>
1 parent 69a8954 commit 7b45edb

File tree

3 files changed

+44
-0
lines changed

3 files changed

+44
-0
lines changed

api/next/45038.txt

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
pkg bytes, func Clone([]uint8) []uint8 #45038

src/bytes/bytes.go

+10
Original file line numberDiff line numberDiff line change
@@ -1299,3 +1299,13 @@ func Cut(s, sep []byte) (before, after []byte, found bool) {
12991299
}
13001300
return s, nil, false
13011301
}
1302+
1303+
// Clone returns a copy of b[:len(b)].
1304+
// The result may have additional unused capacity.
1305+
// Clone(nil) returns nil.
1306+
func Clone(b []byte) []byte {
1307+
if b == nil {
1308+
return nil
1309+
}
1310+
return append([]byte{}, b...)
1311+
}

src/bytes/bytes_test.go

+33
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import (
1515
"testing"
1616
"unicode"
1717
"unicode/utf8"
18+
"unsafe"
1819
)
1920

2021
func eq(a, b []string) bool {
@@ -2118,3 +2119,35 @@ func BenchmarkIndexPeriodic(b *testing.B) {
21182119
})
21192120
}
21202121
}
2122+
2123+
func TestClone(t *testing.T) {
2124+
var cloneTests = [][]byte{
2125+
[]byte(nil),
2126+
[]byte{},
2127+
Clone([]byte{}),
2128+
[]byte(strings.Repeat("a", 42))[:0],
2129+
[]byte(strings.Repeat("a", 42))[:0:0],
2130+
[]byte("short"),
2131+
[]byte(strings.Repeat("a", 42)),
2132+
}
2133+
for _, input := range cloneTests {
2134+
clone := Clone(input)
2135+
if !Equal(clone, input) {
2136+
t.Errorf("Clone(%q) = %q; want %q", input, clone, input)
2137+
}
2138+
2139+
if input == nil && clone != nil {
2140+
t.Errorf("Clone(%#v) return value should be equal to nil slice.", input)
2141+
}
2142+
2143+
if input != nil && clone == nil {
2144+
t.Errorf("Clone(%#v) return value should not be equal to nil slice.", input)
2145+
}
2146+
2147+
inputHeader := (*reflect.SliceHeader)(unsafe.Pointer(&input))
2148+
cloneHeader := (*reflect.SliceHeader)(unsafe.Pointer(&clone))
2149+
if cap(input) != 0 && cloneHeader.Data == inputHeader.Data {
2150+
t.Errorf("Clone(%q) return value should not reference inputs backing memory.", input)
2151+
}
2152+
}
2153+
}

0 commit comments

Comments
 (0)