-
Notifications
You must be signed in to change notification settings - Fork 649
/
iterator.go
76 lines (64 loc) · 1.75 KB
/
iterator.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// Copyright (C) 2019-2023, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package linkedhashmap
import (
"container/list"
"github.com/ava-labs/avalanchego/utils"
)
var _ Iter[int, struct{}] = (*iterator[int, struct{}])(nil)
// Iterates over the keys and values in a LinkedHashmap
// from oldest to newest elements.
// Assumes the underlying LinkedHashmap is not modified while
// the iterator is in use, except to delete elements that
// have already been iterated over.
type Iter[K, V any] interface {
Next() bool
Key() K
Value() V
}
type iterator[K comparable, V any] struct {
lh *linkedHashmap[K, V]
key K
value V
next *list.Element
initialized, exhausted bool
}
func (it *iterator[K, V]) Next() bool {
// If the iterator has been exhausted, there is no next value.
if it.exhausted {
it.key = utils.Zero[K]()
it.value = utils.Zero[V]()
it.next = nil
return false
}
it.lh.lock.RLock()
defer it.lh.lock.RUnlock()
// If the iterator was not yet initialized, do it now.
if !it.initialized {
it.initialized = true
oldest := it.lh.entryList.Front()
if oldest == nil {
it.exhausted = true
it.key = utils.Zero[K]()
it.value = utils.Zero[V]()
it.next = nil
return false
}
it.next = oldest
}
// It's important to ensure that [it.next] is not nil
// by not deleting elements that have not yet been iterated
// over from [it.lh]
kv := it.next.Value.(keyValue[K, V])
it.key = kv.key
it.value = kv.value
it.next = it.next.Next() // Next time, return next element
it.exhausted = it.next == nil
return true
}
func (it *iterator[K, V]) Key() K {
return it.key
}
func (it *iterator[K, V]) Value() V {
return it.value
}