listelement.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package hashmap
  2. import (
  3. "sync/atomic"
  4. "unsafe"
  5. )
  6. // ListElement is an element of a list.
  7. type ListElement struct {
  8. keyHash uintptr
  9. previousElement unsafe.Pointer // is nil for the first item in list
  10. nextElement unsafe.Pointer // is nil for the last item in list
  11. key interface{}
  12. value unsafe.Pointer
  13. deleted uintptr // marks the item as deleting or deleted
  14. }
  15. // Value returns the value of the list item.
  16. func (e *ListElement) Value() (value interface{}) {
  17. return *(*interface{})(atomic.LoadPointer(&e.value))
  18. }
  19. // Next returns the item on the right.
  20. func (e *ListElement) Next() *ListElement {
  21. return (*ListElement)(atomic.LoadPointer(&e.nextElement))
  22. }
  23. // Previous returns the item on the left.
  24. func (e *ListElement) Previous() *ListElement {
  25. return (*ListElement)(atomic.LoadPointer(&e.previousElement))
  26. }
  27. // setValue sets the value of the item.
  28. // The value needs to be wrapped in unsafe.Pointer already.
  29. func (e *ListElement) setValue(value unsafe.Pointer) {
  30. atomic.StorePointer(&e.value, value)
  31. }
  32. // casValue compares and swaps the values of the item.
  33. // The to value needs to be wrapped in unsafe.Pointer already.
  34. func (e *ListElement) casValue(from interface{}, to unsafe.Pointer) bool {
  35. old := atomic.LoadPointer(&e.value)
  36. if *(*interface{})(old) != from {
  37. return false
  38. }
  39. return atomic.CompareAndSwapPointer(&e.value, old, to)
  40. }