From ba2e5d1ed6c143ef127c48059029302ae91368d6 Mon Sep 17 00:00:00 2001 From: hyung-hwan Date: Sat, 24 Feb 2024 22:53:34 +0900 Subject: [PATCH] updated the go wrapper code to save one memory allocation --- go/cb.go | 14 +++++++++++--- go/hcl.go | 4 ++-- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/go/cb.go b/go/cb.go index 30545d9..d385d14 100644 --- a/go/cb.go +++ b/go/cb.go @@ -13,6 +13,7 @@ import ( "os" "path" "path/filepath" + "reflect" "sync" "unsafe" ) @@ -137,9 +138,16 @@ func hcl_go_cci_handler(c *C.hcl_t, cmd C.hcl_io_cmd_t, arg unsafe.Pointer) C.in } // | fd | length | name bytes of the length | - C.memcpy(tptr, unsafe.Pointer(&fd), C.size_t(unsafe.Sizeof(fd))) - C.memcpy(unsafe.Pointer(uintptr(tptr)+unsafe.Sizeof(fd)), unsafe.Pointer(&tlen), C.size_t(unsafe.Sizeof(tlen))) - C.memcpy(unsafe.Pointer(uintptr(tptr)+unsafe.Sizeof(fd)+unsafe.Sizeof(tlen)), unsafe.Pointer(C.CString(name)), tlen) + *(*int)(tptr) = fd; + *(*C.size_t)(unsafe.Pointer(uintptr(tptr)+unsafe.Sizeof(fd))) = tlen; + + // C.CString() allocates a memory block. Use a SliceHeader to avoid extra memory allocation + // for the string conversion. Create a fake slice header that can be used with copy() instead. + var dsthdr reflect.SliceHeader + dsthdr.Data = uintptr(tptr)+unsafe.Sizeof(fd)+unsafe.Sizeof(tlen) + dsthdr.Len = int(tlen) + dsthdr.Cap = int(tlen) + copy(*(*[]byte)(unsafe.Pointer(&dsthdr)), name); ioarg.handle = tptr return 0 diff --git a/go/hcl.go b/go/hcl.go index 56072a1..7e570f1 100644 --- a/go/hcl.go +++ b/go/hcl.go @@ -175,12 +175,12 @@ func (hcl *HCL) SetLogTarget(target string) { var x C.int var tgt *C.char - tgt = C.CString(target) + tgt = C.CString(target) // TODO: need error check? defer C.free(unsafe.Pointer(tgt)) x = C.hcl_setoption(hcl.c, C.HCL_LOG_TARGET_BCSTR, unsafe.Pointer(tgt)) if x <= -1 { - // thist must not happen + // this must not happen panic(fmt.Errorf("unable to set log target - %s", hcl.get_errmsg())) } }