blob: 740ffc707678ae46119dc0c46feeeb467489c5bb [file] [log] [blame]
Abhay Kumara2ae5992025-11-10 14:02:24 +00001package common
2
3import (
4 "unsafe"
5)
6
7func UnsafeAdd(base unsafe.Pointer, offset uintptr) unsafe.Pointer {
8 return unsafe.Pointer(uintptr(base) + offset)
9}
10
11func UnsafeIndex(base unsafe.Pointer, offset uintptr, elemsz uintptr, n int) unsafe.Pointer {
12 return unsafe.Pointer(uintptr(base) + offset + uintptr(n)*elemsz)
13}
14
15func UnsafeByteSlice(base unsafe.Pointer, offset uintptr, i, j int) []byte {
16 // See: https://github.com/golang/go/wiki/cgo#turning-c-arrays-into-go-slices
17 //
18 // This memory is not allocated from C, but it is unmanaged by Go's
19 // garbage collector and should behave similarly, and the compiler
20 // should produce similar code. Note that this conversion allows a
21 // subslice to begin after the base address, with an optional offset,
22 // while the URL above does not cover this case and only slices from
23 // index 0. However, the wiki never says that the address must be to
24 // the beginning of a C allocation (or even that malloc was used at
25 // all), so this is believed to be correct.
26 return (*[MaxAllocSize]byte)(UnsafeAdd(base, offset))[i:j:j]
27}