[Libguestfs] [libnbd PATCH 4/7] Revert "generator/Go.ml: Simplify copy_uint32_array"

Eric Blake
Wed, 26 Jul 2023 17:50:02 -0000

This reverts commit 6725fa0e129f9a60d7b89707ef8604e0aeeeaf43, although
with a more modern style.

Casting a C array to a Go slice just to benefit from potential
optimizations in Go's copy(), is rather complex to understand,
especially when we are still copying things (the main reason to treat
a C array as a Go slice is when avoiding a copy has a benefit).
Without a benchmark showing measurable difference in runtime speed,
and considering that network transit time probably dominates the time
spent on block status and its callback, it is not worth the
complexity.  Furthermore, an upcoming patch wants to add a similar
helper function for converting between a list of C and Go structs,
where the copy() trick will not work; and having the two helpers look
alike is beneficial.

Suggested-by: Laszlo Ersek <lersek at redhat.com>
CC: Nir Soffer <nsoffer at redhat.com>
Signed-off-by: Eric Blake <eblake at redhat.com>
---
 generator/GoLang.ml | 14 ++++++++------
 1 file changed, 8 insertions(+), 6 deletions(-)

diff --git a/generator/GoLang.ml b/generator/GoLang.ml
index 0aa83bdc..77dacadb 100644
--- a/generator/GoLang.ml
+++ b/generator/GoLang.ml
@@ -509,12 +509,14 @@ let

 /* Closures. */

-func copy_uint32_array (entries *C.uint32_t, count C.size_t) []uint32 {
-    ret := make([]uint32, int (count))
-    // See
https://github.com/golang/go/wiki/cgo#turning-c-arrays-into-go-slices
-    // TODO: Use unsafe.Slice() when we require Go 1.17.
-    s := (*[1<<30]uint32)(unsafe.Pointer(entries))[:count:count]
-    copy(ret, s)
+func copy_uint32_array(entries *C.uint32_t, count C.size_t) []uint32 {
+    ret := make([]uint32, int(count))
+    addr := uintptr(unsafe.Pointer(entries))
+    for i := 0; i < int(count); i++ {
+        ptr := (*C.uint32_t)(unsafe.Pointer(addr))
+        ret[i] = uint32(*ptr)
+        addr += unsafe.Sizeof(*ptr)
+    }
     return ret
 }
 ";

base-commit: 5c2fc3cc7e14146d000b65b191e70d9a0585a395
prerequisite-patch-id: 4db98f7b211c0de9a4095b300970e1973cf0716c
prerequisite-patch-id: 0bb320af5109c1c21e5b76d44e6ec1e7e685fd9f
prerequisite-patch-id: 205525d8ea09e77ea13f43d0720153ed5904dbcd
--
2.41.0