strings_unsafe_go121.go 2.2 KB

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