strings_unsafe.go 2.1 KB

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