-
Notifications
You must be signed in to change notification settings - Fork 0
/
list.go
84 lines (68 loc) · 1.51 KB
/
list.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
77
78
79
80
81
82
83
84
package fifomu
import (
"sync"
)
var elementPool = sync.Pool{New: func() any { return new(element[waiter]) }}
// list is a doubly-linked list of type T.
type list[T any] struct {
root element[T]
len uint
}
func (l *list[T]) lazyInit() {
if l.root.next == nil {
l.root.next = &l.root
l.root.prev = &l.root
l.len = 0
}
}
// front returns the first element of list l or nil.
func (l *list[T]) front() *element[T] {
if l.len == 0 {
return nil
}
return l.root.next
}
// pushBackElem inserts a new element e with value v at
// the back of list l and returns e.
func (l *list[T]) pushBackElem(v T) *element[T] {
l.lazyInit()
e := elementPool.Get().(*element[T]) //nolint:errcheck
e.Value = v
l.insert(e, l.root.prev)
return e
}
// pushBack inserts a new element e with value v at
// the back of list l.
func (l *list[T]) pushBack(v T) {
l.lazyInit()
e := elementPool.Get().(*element[T]) //nolint:errcheck
e.Value = v
l.insert(e, l.root.prev)
}
// remove removes e from l if e is an element of list l.
func (l *list[T]) remove(e *element[T]) {
if e.list == l {
e.prev.next = e.next
e.next.prev = e.prev
e.next = nil // avoid memory leaks
e.prev = nil // avoid memory leaks
e.list = nil
l.len--
}
elementPool.Put(e)
}
// insert inserts e after at.
func (l *list[T]) insert(e, at *element[T]) {
e.prev = at
e.next = at.next
e.prev.next = e
e.next.prev = e
e.list = l
l.len++
}
// element is a node of a linked list.
type element[T any] struct {
next, prev *element[T]
list *list[T]
Value T
}