forked from abhi-bit/gouch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sorted_list.go
111 lines (94 loc) · 2.05 KB
/
sorted_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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package gouch
import (
"container/list"
"encoding/binary"
"fmt"
)
//Item within SortedList
type Item struct {
Data []byte
}
//CompareFunc comparator for given sorted list
type CompareFunc func(i1, i2 *Item) int
//SortedList data struct
type SortedList struct {
List *list.List
Compare CompareFunc
}
//SortedListCreate creates a sortedList
func SortedListCreate(Compare CompareFunc) *SortedList {
return &SortedList{
List: list.New(),
Compare: Compare,
}
}
//SortedListAdd adds an item to existing sorted list
func (s *SortedList) SortedListAdd(item *Item) {
node := s.List.Front()
var prev *list.Element
// Initializing to a non-zero value
cmp := -2
for node != nil {
if val, ok := node.Value.(*Item); ok {
cmp = s.Compare(val, item)
if cmp >= 0 {
break
}
prev = node
node = node.Next()
}
}
if prev != nil {
s.List.InsertAfter(item, prev)
} else if prev == nil && node == nil {
s.List.PushBack(item)
}
if cmp == 0 {
s.List.InsertAfter(item, node)
}
}
//SortedListGet grabs an item from SortedList
func (s *SortedList) SortedListGet(item *Item) *Item {
node := s.List.Front()
// Initializing to a non-zero value
cmp := -2
for node != nil {
cmp = s.Compare(node.Value.(*Item), item)
if cmp == 0 {
return node.Value.(*Item)
} else if cmp > 0 {
return nil
} else {
node = node.Next()
}
}
return nil
}
//SortedListRemove removes an item from SortedList
func (s *SortedList) SortedListRemove(item *Item) {
node := s.List.Front()
// Initializing to a non-zero value
cmp := -2
for node != nil {
cmp = s.Compare(node.Value.(*Item), item)
if cmp == 0 {
s.List.Remove(node)
return
} else if cmp >= 0 {
return
} else {
node = node.Next()
}
}
return
}
//SortedListDump dumps the SortedList data struct
func (s *SortedList) SortedListDump() {
for e := s.List.Front(); e != nil; e = e.Next() {
fmt.Println(binary.BigEndian.Uint32(e.Value.(*Item).Data))
}
}
//SortedListSize dumps the len of SortedList data struct
func (s *SortedList) SortedListSize() int {
return s.List.Len()
}