github.com/fiatjaf/generic-ristretto@v0.0.1/contrib/memtest/nojemalloc.go (about)

     1  //+build !jemalloc
     2  
     3  package main
     4  
     5  // #include <stdlib.h>
     6  import "C"
     7  import (
     8  	"reflect"
     9  	"sync/atomic"
    10  	"unsafe"
    11  
    12  	"github.com/golang/glog"
    13  )
    14  
    15  func Calloc(size int) []byte {
    16  	if size == 0 {
    17  		return make([]byte, 0)
    18  	}
    19  	ptr := C.calloc(C.size_t(size), 1)
    20  	if ptr == nil {
    21  		panic("OOM")
    22  	}
    23  	hdr := reflect.SliceHeader{Data: uintptr(ptr), Len: size, Cap: size}
    24  	atomic.AddInt64(&numbytes, int64(size))
    25  	return *(*[]byte)(unsafe.Pointer(&hdr))
    26  }
    27  
    28  func Free(bs []byte) {
    29  	if len(bs) == 0 {
    30  		return
    31  	}
    32  
    33  	if sz := cap(bs); sz != 0 {
    34  		bs = bs[:cap(bs)]
    35  		C.free(unsafe.Pointer(&bs[0]))
    36  		atomic.AddInt64(&numbytes, -int64(sz))
    37  	}
    38  }
    39  
    40  func NumAllocBytes() int64 { return atomic.LoadInt64(&numbytes) }
    41  
    42  func check() {}
    43  
    44  func init() {
    45  	glog.Infof("USING CALLOC")
    46  }