strings_unsafe_go121.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Copyright 2018 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. //go:build go1.21
  5. package strs
  6. import (
  7. "unsafe"
  8. "google.golang.org/protobuf/reflect/protoreflect"
  9. )
  10. // UnsafeString returns an unsafe string reference of b.
  11. // The caller must treat the input slice as immutable.
  12. //
  13. // WARNING: Use carefully. The returned result must not leak to the end user
  14. // unless the input slice is provably immutable.
  15. func UnsafeString(b []byte) string {
  16. return unsafe.String(unsafe.SliceData(b), len(b))
  17. }
  18. // UnsafeBytes returns an unsafe bytes slice reference of s.
  19. // The caller must treat returned slice as immutable.
  20. //
  21. // WARNING: Use carefully. The returned result must not leak to the end user.
  22. func UnsafeBytes(s string) []byte {
  23. return unsafe.Slice(unsafe.StringData(s), len(s))
  24. }
  25. // Builder builds a set of strings with shared lifetime.
  26. // This differs from strings.Builder, which is for building a single string.
  27. type Builder struct {
  28. buf []byte
  29. }
  30. // AppendFullName is equivalent to protoreflect.FullName.Append,
  31. // but optimized for large batches where each name has a shared lifetime.
  32. func (sb *Builder) AppendFullName(prefix protoreflect.FullName, name protoreflect.Name) protoreflect.FullName {
  33. n := len(prefix) + len(".") + len(name)
  34. if len(prefix) == 0 {
  35. n -= len(".")
  36. }
  37. sb.grow(n)
  38. sb.buf = append(sb.buf, prefix...)
  39. sb.buf = append(sb.buf, '.')
  40. sb.buf = append(sb.buf, name...)
  41. return protoreflect.FullName(sb.last(n))
  42. }
  43. // MakeString is equivalent to string(b), but optimized for large batches
  44. // with a shared lifetime.
  45. func (sb *Builder) MakeString(b []byte) string {
  46. sb.grow(len(b))
  47. sb.buf = append(sb.buf, b...)
  48. return sb.last(len(b))
  49. }
  50. func (sb *Builder) grow(n int) {
  51. if cap(sb.buf)-len(sb.buf) >= n {
  52. return
  53. }
  54. // Unlike strings.Builder, we do not need to copy over the contents
  55. // of the old buffer since our builder provides no API for
  56. // retrieving previously created strings.
  57. sb.buf = make([]byte, 0, 2*(cap(sb.buf)+n))
  58. }
  59. func (sb *Builder) last(n int) string {
  60. return UnsafeString(sb.buf[len(sb.buf)-n:])
  61. }