faststr.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /*
  2. * Copyright 2024 CloudWeGo Authors
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package base64x
  17. import (
  18. `reflect`
  19. `unsafe`
  20. )
  21. func mem2str(v []byte) (s string) {
  22. (*reflect.StringHeader)(unsafe.Pointer(&s)).Len = (*reflect.SliceHeader)(unsafe.Pointer(&v)).Len
  23. (*reflect.StringHeader)(unsafe.Pointer(&s)).Data = (*reflect.SliceHeader)(unsafe.Pointer(&v)).Data
  24. return
  25. }
  26. func str2mem(s string) (v []byte) {
  27. (*reflect.SliceHeader)(unsafe.Pointer(&v)).Cap = (*reflect.StringHeader)(unsafe.Pointer(&s)).Len
  28. (*reflect.SliceHeader)(unsafe.Pointer(&v)).Len = (*reflect.StringHeader)(unsafe.Pointer(&s)).Len
  29. (*reflect.SliceHeader)(unsafe.Pointer(&v)).Data = (*reflect.StringHeader)(unsafe.Pointer(&s)).Data
  30. return
  31. }
  32. func mem2addr(v []byte) unsafe.Pointer {
  33. return *(*unsafe.Pointer)(unsafe.Pointer(&v))
  34. }
  35. // NoEscape hides a pointer from escape analysis. NoEscape is
  36. // the identity function but escape analysis doesn't think the
  37. // output depends on the input. NoEscape is inlined and currently
  38. // compiles down to zero instructions.
  39. // USE CAREFULLY!
  40. //go:nosplit
  41. //goland:noinspection GoVetUnsafePointer
  42. func noEscape(p unsafe.Pointer) unsafe.Pointer {
  43. x := uintptr(p)
  44. return unsafe.Pointer(x ^ 0)
  45. }