Skip to content

Commit

Permalink
Remove size in OrderedSet (#2319)
Browse files Browse the repository at this point in the history
  • Loading branch information
weiihann authored Dec 12, 2024
1 parent 65b7507 commit 7687360
Showing 1 changed file with 22 additions and 24 deletions.
46 changes: 22 additions & 24 deletions utils/orderedset.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,8 @@ import (
// - Uses a slice to maintain insertion order and enable ordered iteration
// The data structure is safe for concurrent access through the use of a read-write mutex.
type OrderedSet[K comparable, V any] struct {
itemPos map[K]int // position of the node in the list
itemPos map[K]int // position of the item in the list
items []V
size int
lock sync.RWMutex
}

Expand All @@ -22,46 +21,45 @@ func NewOrderedSet[K comparable, V any]() *OrderedSet[K, V] {
}
}

func (ps *OrderedSet[K, V]) Put(key K, value V) {
ps.lock.Lock()
defer ps.lock.Unlock()
func (o *OrderedSet[K, V]) Put(key K, value V) {
o.lock.Lock()
defer o.lock.Unlock()

// Update existing entry
if pos, exists := ps.itemPos[key]; exists {
ps.items[pos] = value
if pos, exists := o.itemPos[key]; exists {
o.items[pos] = value
return
}

// Insert new entry
ps.itemPos[key] = len(ps.items)
ps.items = append(ps.items, value)
ps.size++
o.itemPos[key] = len(o.items)
o.items = append(o.items, value)
}

func (ps *OrderedSet[K, V]) Get(key K) (V, bool) {
ps.lock.RLock()
defer ps.lock.RUnlock()
func (o *OrderedSet[K, V]) Get(key K) (V, bool) {
o.lock.RLock()
defer o.lock.RUnlock()

if pos, ok := ps.itemPos[key]; ok {
return ps.items[pos], true
if pos, ok := o.itemPos[key]; ok {
return o.items[pos], true
}
var zero V
return zero, false
}

func (ps *OrderedSet[K, V]) Size() int {
ps.lock.RLock()
defer ps.lock.RUnlock()
func (o *OrderedSet[K, V]) Size() int {
o.lock.RLock()
defer o.lock.RUnlock()

return ps.size
return len(o.items)
}

// List returns a shallow copy of the proof set's value list.
func (ps *OrderedSet[K, V]) List() []V {
ps.lock.RLock()
defer ps.lock.RUnlock()
func (o *OrderedSet[K, V]) List() []V {
o.lock.RLock()
defer o.lock.RUnlock()

values := make([]V, len(ps.items))
copy(values, ps.items)
values := make([]V, len(o.items))
copy(values, o.items)
return values
}

0 comments on commit 7687360

Please sign in to comment.