github.com/etecs-ru/ristretto@v0.9.1/contrib/memtest/nojemalloc.go (about)

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