github.com/GoWebProd/gip@v0.0.0-20230623090727-b60d41d5d320/allocator/alloc.go (about)

     1  package allocator
     2  
     3  /*
     4  #cgo LDFLAGS: -ljemalloc -lm -lstdc++ -pthread -ldl
     5  #include <stdlib.h>
     6  #include <jemalloc/jemalloc.h>
     7  */
     8  import "C"
     9  
    10  import (
    11  	"reflect"
    12  	"unsafe"
    13  
    14  	"github.com/GoWebProd/gip/rtime"
    15  )
    16  
    17  //go:linkname throw runtime.throw
    18  func throw(s string)
    19  
    20  func Alloc(size int) []byte {
    21  	ptr := C.mallocx(C.size_t(size), 0x40)
    22  	if ptr == nil {
    23  		throw("out of memory")
    24  	}
    25  
    26  	var data []byte
    27  
    28  	h := (*reflect.SliceHeader)(unsafe.Pointer(&data))
    29  	h.Len = size
    30  	h.Cap = size
    31  	h.Data = uintptr(ptr)
    32  
    33  	return data
    34  }
    35  
    36  func Realloc(data *[]byte, size int) {
    37  	h := (*reflect.SliceHeader)(unsafe.Pointer(data))
    38  	if h.Cap == 0 {
    39  		*data = Alloc(size)[:0]
    40  
    41  		return
    42  	}
    43  
    44  	ptr := C.rallocx(unsafe.Pointer(h.Data), C.size_t(size), 0x40)
    45  	if ptr == nil {
    46  		throw("out of memory")
    47  	}
    48  
    49  	h.Data = uintptr(ptr)
    50  	h.Cap = size
    51  }
    52  
    53  func AllocObject[T any]() *T {
    54  	var obj T
    55  
    56  	size := unsafe.Sizeof(obj)
    57  
    58  	ptr := C.mallocx(C.size_t(size), 0x40)
    59  	if ptr == nil {
    60  		throw("out of memory")
    61  	}
    62  
    63  	return (*T)(ptr)
    64  }
    65  
    66  func Free(data []byte) {
    67  	C.free(rtime.Noescape(&data[0]))
    68  }
    69  
    70  func FreeObject[T any](o *T) {
    71  	C.free(rtime.Noescape(o))
    72  }