fastmem.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /*
  2. * Copyright 2021 ByteDance Inc.
  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 rt
  17. import (
  18. `unsafe`
  19. `reflect`
  20. )
  21. //go:nosplit
  22. func Mem2Str(v []byte) (s string) {
  23. (*GoString)(unsafe.Pointer(&s)).Len = (*GoSlice)(unsafe.Pointer(&v)).Len
  24. (*GoString)(unsafe.Pointer(&s)).Ptr = (*GoSlice)(unsafe.Pointer(&v)).Ptr
  25. return
  26. }
  27. //go:nosplit
  28. func Str2Mem(s string) (v []byte) {
  29. (*GoSlice)(unsafe.Pointer(&v)).Cap = (*GoString)(unsafe.Pointer(&s)).Len
  30. (*GoSlice)(unsafe.Pointer(&v)).Len = (*GoString)(unsafe.Pointer(&s)).Len
  31. (*GoSlice)(unsafe.Pointer(&v)).Ptr = (*GoString)(unsafe.Pointer(&s)).Ptr
  32. return
  33. }
  34. func BytesFrom(p unsafe.Pointer, n int, c int) (r []byte) {
  35. (*GoSlice)(unsafe.Pointer(&r)).Ptr = p
  36. (*GoSlice)(unsafe.Pointer(&r)).Len = n
  37. (*GoSlice)(unsafe.Pointer(&r)).Cap = c
  38. return
  39. }
  40. func FuncAddr(f interface{}) unsafe.Pointer {
  41. if vv := UnpackEface(f); vv.Type.Kind() != reflect.Func {
  42. panic("f is not a function")
  43. } else {
  44. return *(*unsafe.Pointer)(vv.Value)
  45. }
  46. }
  47. //go:nocheckptr
  48. func IndexChar(src string, index int) unsafe.Pointer {
  49. return unsafe.Pointer(uintptr((*GoString)(unsafe.Pointer(&src)).Ptr) + uintptr(index))
  50. }
  51. //go:nocheckptr
  52. func IndexByte(ptr []byte, index int) unsafe.Pointer {
  53. return unsafe.Pointer(uintptr((*GoSlice)(unsafe.Pointer(&ptr)).Ptr) + uintptr(index))
  54. }