You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

43 lines
1.2 KiB

  1. // Copyright 2015 PingCAP, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // See the License for the specific language governing permissions and
  12. // limitations under the License.
  13. package hack
  14. import (
  15. "reflect"
  16. "unsafe"
  17. )
  18. // String converts slice to string without copy.
  19. // Use at your own risk.
  20. func String(b []byte) (s string) {
  21. if len(b) == 0 {
  22. return ""
  23. }
  24. pbytes := (*reflect.SliceHeader)(unsafe.Pointer(&b))
  25. pstring := (*reflect.StringHeader)(unsafe.Pointer(&s))
  26. pstring.Data = pbytes.Data
  27. pstring.Len = pbytes.Len
  28. return
  29. }
  30. // Slice converts string to slice without copy.
  31. // Use at your own risk.
  32. func Slice(s string) (b []byte) {
  33. pbytes := (*reflect.SliceHeader)(unsafe.Pointer(&b))
  34. pstring := (*reflect.StringHeader)(unsafe.Pointer(&s))
  35. pbytes.Data = pstring.Data
  36. pbytes.Len = pstring.Len
  37. pbytes.Cap = pstring.Len
  38. return
  39. }