fastmem.go raw

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