| Abhay Kumar | a2ae599 | 2025-11-10 14:02:24 +0000 | [diff] [blame^] | 1 | package common |
| 2 | |
| 3 | import ( |
| 4 | "unsafe" |
| 5 | ) |
| 6 | |
| 7 | func UnsafeAdd(base unsafe.Pointer, offset uintptr) unsafe.Pointer { |
| 8 | return unsafe.Pointer(uintptr(base) + offset) |
| 9 | } |
| 10 | |
| 11 | func UnsafeIndex(base unsafe.Pointer, offset uintptr, elemsz uintptr, n int) unsafe.Pointer { |
| 12 | return unsafe.Pointer(uintptr(base) + offset + uintptr(n)*elemsz) |
| 13 | } |
| 14 | |
| 15 | func 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 | } |