You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

39 lines
1.5 KiB

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