clone_test.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. // Copyright 2021 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.ß
  4. package strings_test
  5. import (
  6. "reflect"
  7. "strings"
  8. "testing"
  9. "unsafe"
  10. )
  11. var emptyString string
  12. func TestClone(t *testing.T) {
  13. var cloneTests = []string{
  14. "",
  15. strings.Clone(""),
  16. strings.Repeat("a", 42)[:0],
  17. "short",
  18. strings.Repeat("a", 42),
  19. }
  20. for _, input := range cloneTests {
  21. clone := strings.Clone(input)
  22. if clone != input {
  23. t.Errorf("Clone(%q) = %q; want %q", input, clone, input)
  24. }
  25. inputHeader := (*reflect.StringHeader)(unsafe.Pointer(&input))
  26. cloneHeader := (*reflect.StringHeader)(unsafe.Pointer(&clone))
  27. if len(input) != 0 && cloneHeader.Data == inputHeader.Data {
  28. t.Errorf("Clone(%q) return value should not reference inputs backing memory.", input)
  29. }
  30. emptyHeader := (*reflect.StringHeader)(unsafe.Pointer(&emptyString))
  31. if len(input) == 0 && cloneHeader.Data != emptyHeader.Data {
  32. t.Errorf("Clone(%#v) return value should be equal to empty string.", inputHeader)
  33. }
  34. }
  35. }
  36. func BenchmarkClone(b *testing.B) {
  37. var str = strings.Repeat("a", 42)
  38. b.ReportAllocs()
  39. for i := 0; i < b.N; i++ {
  40. stringSink = strings.Clone(str)
  41. }
  42. }