helper_unsafe.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. //+build unsafe
  2. // Copyright (c) 2012-2015 Ugorji Nwoke. All rights reserved.
  3. // Use of this source code is governed by a MIT license found in the LICENSE file.
  4. package codec
  5. import (
  6. "unsafe"
  7. )
  8. // This file has unsafe variants of some helper methods.
  9. type unsafeString struct {
  10. Data uintptr
  11. Len int
  12. }
  13. type unsafeBytes struct {
  14. Data uintptr
  15. Len int
  16. Cap int
  17. }
  18. // stringView returns a view of the []byte as a string.
  19. // In unsafe mode, it doesn't incur allocation and copying caused by conversion.
  20. // In regular safe mode, it is an allocation and copy.
  21. func stringView(v []byte) string {
  22. if len(v) == 0 {
  23. return ""
  24. }
  25. x := unsafeString{uintptr(unsafe.Pointer(&v[0])), len(v)}
  26. return *(*string)(unsafe.Pointer(&x))
  27. }
  28. // bytesView returns a view of the string as a []byte.
  29. // In unsafe mode, it doesn't incur allocation and copying caused by conversion.
  30. // In regular safe mode, it is an allocation and copy.
  31. func bytesView(v string) []byte {
  32. if len(v) == 0 {
  33. return zeroByteSlice
  34. }
  35. x := unsafeBytes{uintptr(unsafe.Pointer(&v)), len(v), len(v)}
  36. return *(*[]byte)(unsafe.Pointer(&x))
  37. }