diff --git a/common/bytes.go b/common/bytes.go index 4fb016a976..0fd5fa6255 100644 --- a/common/bytes.go +++ b/common/bytes.go @@ -107,14 +107,9 @@ func ReadVarInt(buff []byte) (ret uint64) { return } -// Copy bytes -// // Returns an exact copy of the provided bytes func CopyBytes(b []byte) (copiedBytes []byte) { - copiedBytes = make([]byte, len(b)) - copy(copiedBytes, b) - - return + return append([]byte{}, b...) } func HasHexPrefix(str string) bool { diff --git a/common/bytes_test.go b/common/bytes_test.go index 2e52084777..6b739ee622 100644 --- a/common/bytes_test.go +++ b/common/bytes_test.go @@ -76,10 +76,21 @@ func (s *BytesSuite) TestReadVarInt(c *checker.C) { } func (s *BytesSuite) TestCopyBytes(c *checker.C) { - data1 := []byte{1, 2, 3, 4} - exp1 := []byte{1, 2, 3, 4} - res1 := CopyBytes(data1) - c.Assert(res1, checker.DeepEquals, exp1) + data := [][]byte{ + []byte{0x00, 0x7f, 0x80, 0xff}, // interesting bytes + []byte{}, // empty case + } + + // test + for i := 0; i < len(data); i++ { + have := CopyBytes(data[i]) + if data[i] != nil { + // make sure we're not just returning the input arg + c.Assert(&have, checker.Not(checker.Equals), &data[i]) + } + // verify deep copy + c.Assert(have, checker.DeepEquals, data[i]) + } } func (s *BytesSuite) TestIsHex(c *checker.C) {