github.com/pharosnet/flyline@v1.0.2/array.go (about) 1 package flyline 2 3 import ( 4 "math" 5 "unsafe" 6 ) 7 8 type entry struct { 9 value interface{} 10 } 11 12 func newArray(capacity int64) (a *array) { 13 if capacity > 0 && (capacity&(capacity-1)) != 0 { 14 panic("The array capacity must be a power of two, e.g. 2, 4, 8, 16, 32, 64, etc.") 15 return 16 } 17 var items []*entry = nil 18 align := int64(unsafe.Alignof(items)) 19 mask := capacity - 1 20 shift := int64(math.Log2(float64(capacity))) 21 size := capacity * align 22 items = make([]*entry, size) 23 itemBasePtr := uintptr(unsafe.Pointer(&items[0])) 24 itemMSize := unsafe.Sizeof(items[0]) 25 for i := int64(0); i < size; i++ { 26 items[i&mask*align] = &entry{} 27 } 28 return &array{ 29 capacity: capacity, 30 size: size, 31 shift: shift, 32 align: align, 33 mask: mask, 34 items: items, 35 itemBasePtr: itemBasePtr, 36 itemMSize: itemMSize, 37 } 38 } 39 40 // shared array 41 type array struct { 42 capacity int64 43 size int64 44 shift int64 45 align int64 46 mask int64 47 items []*entry 48 itemBasePtr uintptr 49 itemMSize uintptr 50 } 51 52 func (a *array) elementAt(seq int64) (e *entry) { 53 mask := a.mask 54 align := a.align 55 basePtr := a.itemBasePtr 56 mSize := a.itemMSize 57 entryPtr := basePtr + uintptr(seq&mask*align)*mSize 58 e = *((*(*entry))(unsafe.Pointer(entryPtr))) 59 return 60 } 61 62 func (a *array) set(seq int64, v interface{}) { 63 a.elementAt(seq).value = v 64 } 65 66 func (a *array) get(seq int64) (v interface{}) { 67 v = a.elementAt(seq).value 68 return 69 }