helper_unsafe.go 972 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. "runtime"
  7. "unsafe"
  8. )
  9. // This file has unsafe variants of some helper methods.
  10. // NOTE: See helper_not_unsafe.go for the usage information.
  11. type unsafeString struct {
  12. Data uintptr
  13. Len int
  14. }
  15. type unsafeSlice struct {
  16. Data uintptr
  17. Len int
  18. Cap int
  19. }
  20. func stringView(v []byte) string {
  21. if len(v) == 0 {
  22. return ""
  23. }
  24. bx := (*unsafeSlice)(unsafe.Pointer(&v))
  25. sx := unsafeString{bx.Data, bx.Len}
  26. return *(*string)(unsafe.Pointer(&sx))
  27. }
  28. func bytesView(v string) []byte {
  29. if len(v) == 0 {
  30. return zeroByteSlice
  31. }
  32. sx := (*unsafeString)(unsafe.Pointer(&v))
  33. bx := unsafeSlice{sx.Data, sx.Len, sx.Len}
  34. return *(*[]byte)(unsafe.Pointer(&bx))
  35. }
  36. func keepAlive4BytesView(v string) {
  37. runtime.KeepAlive(v)
  38. }
  39. func keepAlive4StringView(v []byte) {
  40. runtime.KeepAlive(v)
  41. }