string_unsafe.go 709 B

123456789101112131415161718192021
  1. package utils
  2. import "unsafe"
  3. // ImmutableBytesFromString is equivalent to []byte(s), except that it uses the
  4. // same memory backing s instead of making a heap-allocated copy. This is only
  5. // valid if the returned slice is never mutated.
  6. func ImmutableBytesFromString(s string) []byte {
  7. b := unsafe.StringData(s)
  8. return unsafe.Slice(b, len(s))
  9. }
  10. // StringFromImmutableBytes is equivalent to string(bs), except that it uses
  11. // the same memory backing bs instead of making a heap-allocated copy. This is
  12. // only valid if bs is never mutated after StringFromImmutableBytes returns.
  13. func StringFromImmutableBytes(bs []byte) string {
  14. if len(bs) == 0 {
  15. return ""
  16. }
  17. return unsafe.String(&bs[0], len(bs))
  18. }