helper_unsafe.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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 unsafeSlice 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. bx := (*unsafeSlice)(unsafe.Pointer(&v))
  26. sx := unsafeString{bx.Data, bx.Len}
  27. return *(*string)(unsafe.Pointer(&sx))
  28. }
  29. // bytesView returns a view of the string as a []byte.
  30. // In unsafe mode, it doesn't incur allocation and copying caused by conversion.
  31. // In regular safe mode, it is an allocation and copy.
  32. func bytesView(v string) []byte {
  33. if len(v) == 0 {
  34. return zeroByteSlice
  35. }
  36. sx := (*unsafeString)(unsafe.Pointer(&v))
  37. bx := unsafeSlice{sx.Data, sx.Len, sx.Len}
  38. return *(*[]byte)(unsafe.Pointer(&bx))
  39. }