package gg // The structure to store objects // with O(1) add, remove and search operations. type Objects struct { // The place to store all the objects. store []Object // Find index by Object. searchMap map[Object] int // Available nil values in the store. freeIndexes []int } func NewObjects() *Objects { ret := &Objects{} ret.searchMap = map[Object] int {} return ret } func (objects *Objects) has(object Object) bool { _, ok := objects.searchMap[object] return ok } func (objects *Objects) add(object Object) bool { if objects.has(object) { return false } if len(objects.freeIndexes) > 0 { freeIndex := objects.freeIndexes[0] objects.freeIndexes = objects.freeIndexes[1:] objects.store[freeIndex] = object objects.searchMap[object] = freeIndex } else { objects.store = append(objects.store, object) objects.searchMap[object] = len(objects.store)-1 } return true } func (objects *Objects) remove(object Object) bool { objectIndex, ok := objects.searchMap[object] if !ok { return false } objects.store[objectIndex] = nil objects.freeIndexes = append( objects.freeIndexes, objectIndex, ) return true }