forked from Workiva/go-datastructures
/
key.go
96 lines (76 loc) · 2.05 KB
/
key.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
/*
Copyright 2014 Workiva, LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package link
import "sort"
func (keys Keys) search(key Key) int {
return sort.Search(len(keys), func(i int) bool {
return keys[i].Compare(key) >= 0
})
}
func (keys *Keys) insert(key Key) Key {
i := keys.search(key)
return keys.insertAt(key, i)
}
func (keys *Keys) insertAt(key Key, i int) Key {
if i == len(*keys) {
*keys = append(*keys, key)
return nil
}
if (*keys)[i].Compare(key) == 0 { //overwrite case
oldKey := (*keys)[i]
(*keys)[i] = key
return oldKey
}
*keys = append(*keys, nil)
copy((*keys)[i+1:], (*keys)[i:])
(*keys)[i] = key
return nil
}
func (keys *Keys) split() (Key, Keys, Keys) {
i := (len(*keys) / 2) - 1
middle := (*keys)[i]
left, right := keys.splitAt(i)
return middle, left, right
}
func (keys *Keys) splitAt(i int) (Keys, Keys) {
right := make(Keys, len(*keys)-i-1, cap(*keys))
copy(right, (*keys)[i+1:])
for j := i + 1; j < len(*keys); j++ {
(*keys)[j] = nil
}
*keys = (*keys)[:i+1]
return *keys, right
}
func (keys Keys) last() Key {
return keys[len(keys)-1]
}
func (keys Keys) first() Key {
return keys[0]
}
func (keys Keys) needsSplit() bool {
return cap(keys) == len(keys)
}
func (keys Keys) reverse() Keys {
reversed := make(Keys, len(keys))
for i := len(keys) - 1; i >= 0; i-- {
reversed[len(keys)-1-i] = keys[i]
}
return reversed
}
func chunkKeys(keys Keys, numParts int64) []Keys {
parts := make([]Keys, numParts)
for i := int64(0); i < numParts; i++ {
parts[i] = keys[i*int64(len(keys))/numParts : (i+1)*int64(len(keys))/numParts]
}
return parts
}