-
Notifications
You must be signed in to change notification settings - Fork 0
/
vector.go
134 lines (112 loc) · 2.48 KB
/
vector.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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
package negentropy
import (
"errors"
"sort"
)
type Vector struct {
items []Item
sealed bool
}
func NewVector() *Vector {
return &Vector{
items: make([]Item, 0),
sealed: false,
}
}
func (v *Vector) Insert(createdAt uint64, id []byte) error {
//fmt.Fprintln(os.Stderr, "Insert", createdAt, id)
if v.sealed {
return errors.New("already sealed")
}
if len(id) != IDSize {
return errors.New("bad id size for added item")
}
item := NewItemWithID(createdAt, id)
v.items = append(v.items, *item)
return nil
}
func (v *Vector) InsertItem(item Item) error {
return v.Insert(item.Timestamp, item.ID[:])
}
func (v *Vector) Seal() error {
if v.sealed {
return errors.New("already sealed")
}
v.sealed = true
sort.Slice(v.items, func(i, j int) bool {
return v.items[i].LessThan(v.items[j])
})
for i := 1; i < len(v.items); i++ {
if v.items[i-1].Equals(v.items[i]) {
return errors.New("duplicate item inserted")
}
}
return nil
}
func (v *Vector) Unseal() {
v.sealed = false
}
func (v *Vector) Size() int {
if err := v.checkSealed(); err != nil {
return 0
}
return len(v.items)
}
func (v *Vector) GetItem(i uint64) (Item, error) {
if err := v.checkSealed(); err != nil {
return Item{}, err
}
if i >= uint64(len(v.items)) {
return Item{}, errors.New("index out of bounds")
}
return v.items[i], nil
}
func (v *Vector) Iterate(begin, end int, cb func(Item, int) bool) error {
if err := v.checkSealed(); err != nil {
return err
}
if err := v.checkBounds(begin, end); err != nil {
return err
}
for i := begin; i < end; i++ {
if !cb(v.items[i], i) {
break
}
}
return nil
}
func (v *Vector) FindLowerBound(begin, end int, bound Bound) (int, error) {
if err := v.checkSealed(); err != nil {
return 0, err
}
if err := v.checkBounds(begin, end); err != nil {
return 0, err
}
i := sort.Search(len(v.items[begin:end]), func(i int) bool {
return !v.items[begin+i].LessThan(bound.Item)
})
return begin + i, nil
}
func (v *Vector) Fingerprint(begin, end int) (Fingerprint, error) {
var out Accumulator
out.SetToZero()
if err := v.Iterate(begin, end, func(item Item, _ int) bool {
out.AddItem(item)
return true
}); err != nil {
return Fingerprint{}, err
}
return out.GetFingerprint(end - begin), nil
}
func (v *Vector) checkSealed() error {
if !v.sealed {
return errors.New("not sealed")
}
return nil
}
func (v *Vector) checkBounds(begin, end int) error {
if begin > end || end > len(v.items) {
return errors.New("bad range")
}
return nil
}