1 package bbolt 2 3 import ( 4 "reflect" 5 "unsafe" 6 ) 7 8 func unsafeAdd(base unsafe.Pointer, offset uintptr) unsafe.Pointer { 9 return unsafe.Pointer(uintptr(base) + offset) 10 } 11 12 func unsafeIndex(base unsafe.Pointer, offset uintptr, elemsz uintptr, n int) unsafe.Pointer { 13 return unsafe.Pointer(uintptr(base) + offset + uintptr(n)*elemsz) 14 } 15 16 func unsafeByteSlice(base unsafe.Pointer, offset uintptr, i, j int) []byte { 17 // See: https://github.com/golang/go/wiki/cgo#turning-c-arrays-into-go-slices 18 // 19 // This memory is not allocated from C, but it is unmanaged by Go's 20 // garbage collector and should behave similarly, and the compiler 21 // should produce similar code. Note that this conversion allows a 22 // subslice to begin after the base address, with an optional offset, 23 // while the URL above does not cover this case and only slices from 24 // index 0. However, the wiki never says that the address must be to 25 // the beginning of a C allocation (or even that malloc was used at 26 // all), so this is believed to be correct. 27 return (*[maxAllocSize]byte)(unsafeAdd(base, offset))[i:j:j] 28 } 29 30 // unsafeSlice modifies the data, len, and cap of a slice variable pointed to by 31 // the slice parameter. This helper should be used over other direct 32 // manipulation of reflect.SliceHeader to prevent misuse, namely, converting 33 // from reflect.SliceHeader to a Go slice type. 34 func unsafeSlice(slice, data unsafe.Pointer, len int) { 35 s := (*reflect.SliceHeader)(slice) 36 s.Data = uintptr(data) 37 s.Cap = len 38 s.Len = len 39 } 40