| 1 |
// Copyright 2015 Randall Farmer. All rights reserved. |
| 2 |
|
| 3 |
// Use of this source code is governed by a BSD-style license that can be |
| 4 |
// found in the LICENSE file. |
| 5 |
|
| 6 |
// Package index uses sorted arrays of integers to assist sorting and |
| 7 |
// searching, particularly of collections of strings. |
| 8 |
package index |
| 9 |
|
| 10 |
import ( |
| 11 |
"bytes" |
| 12 |
"sort" |
| 13 |
"strings" |
| 14 |
|
| 15 |
"github.com/twotwotwo/sorts" |
| 16 |
) |
| 17 |
|
| 18 |
type Index struct { |
| 19 |
Keys []uint64 |
| 20 |
Summary []uint64 // implicit B-tree, if Summarize() was called |
| 21 |
Data sort.Interface |
| 22 |
} |
| 23 |
|
| 24 |
// Len returns the length of the data underlying an Index |
| 25 |
func (idx *Index) Len() int { return idx.Data.Len() } |
| 26 |
|
| 27 |
// Less compares Index elements by their Keys, falling back to Data.Less for |
| 28 |
// equal-keyed items. |
| 29 |
func (idx *Index) Less(i, j int) bool { |
| 30 |
return idx.Keys[i] < idx.Keys[j] || (idx.Keys[i] == idx.Keys[j] && idx.Data.Less(i, j)) |
| 31 |
} |
| 32 |
|
| 33 |
// Swap swaps both the Keys and the inderlying data items at indices i and |
| 34 |
// j. |
| 35 |
func (idx *Index) Swap(i, j int) { |
| 36 |
idx.Keys[i], idx.Keys[j] = idx.Keys[j], idx.Keys[i] |
| 37 |
idx.Data.Swap(i, j) |
| 38 |
} |
| 39 |
|
| 40 |
// Key returns the uint64 key at index i. |
| 41 |
func (idx *Index) Key(i int) uint64 { return idx.Keys[i] } |
| 42 |
|
| 43 |
// levelBits and pageSize control the fan-out of Summary, the implicit |
| 44 |
// B-tree. 6 won a very informal bake-off. (Would have guessed 3, matching |
| 45 |
// 8-word amd64 cache lines.) More would work better if this were ever on |
| 46 |
// block storage, e.g. levelBits of 9 corresponds to a page size of 4KiB. |
| 47 |
const levelBits = 6 |
| 48 |
const pageSize = 1 << levelBits |
| 49 |
|
| 50 |
// Summarize makes an implicit B-tree to speed lookups, using a few percent |
| 51 |
// overhead on top of what's already used for Indices. |
| 52 |
func (idx *Index) Summarize() { |
| 53 |
l := idx.Len() |
| 54 |
sl := l>>levelBits + l>>levelBits*2 + l>>levelBits*3 + l>>((levelBits*4)-1) |
| 55 |
summary := make([]uint64, 0, sl) |
| 56 |
summarizing := idx.Keys |
| 57 |
levelNum := 1 |
| 58 |
for len(summarizing) > pageSize { |
| 59 |
start := len(summary) |
| 60 |
for i := 0; i < len(summarizing); i += pageSize { |
| 61 |
summary = append(summary, summarizing[i]) |
| 62 |
} |
| 63 |
summarizing = summary[start:] |
| 64 |
levelNum++ |
| 65 |
} |
| 66 |
idx.Summary = summary |
| 67 |
} |
| 68 |
|
| 69 |
// FindUint64 finds the position of the first item >= key in Keys, returning |
| 70 |
// one after the end if there is none. When different values map to the same key, |
| 71 |
// you might want to sort.Search within the returned range to narrow your result |
| 72 |
// down to the desired values. |
| 73 |
func (idx *Index) FindUint64(key uint64) int { |
| 74 |
if idx.Summary != nil { |
| 75 |
return idx.findUint64Summary(key) |
| 76 |
} |
| 77 |
return sort.Search(idx.Len(), func(i int) bool { return idx.Keys[i] >= key }) |
| 78 |
} |
| 79 |
|
| 80 |
// Compares string a to []byte b, returning -1 if a<b, 0 if a==b, and 1 if a>b. |
| 81 |
func CompareStringToBytes(a string, b []byte) int { |
| 82 |
for i := range b { |
| 83 |
if i > len(a) { |
| 84 |
return -1 |
| 85 |
} |
| 86 |
if b[i] > a[i] { |
| 87 |
return -1 |
| 88 |
} |
| 89 |
if a[i] > b[i] { |
| 90 |
return 1 |
| 91 |
} |
| 92 |
} |
| 93 |
if len(a) > len(b) { |
| 94 |
return 1 |
| 95 |
} |
| 96 |
return 0 |
| 97 |
} |
| 98 |
|
| 99 |
// CompareBytesToString is a convenience wrapper for CompareStringToBytes. |
| 100 |
func CompareBytesToString(a []byte, b string) int { |
| 101 |
return -CompareStringToBytes(b, a) |
| 102 |
} |
| 103 |
|
| 104 |
// FindString finds the first item >= key, returning one after the end if there |
| 105 |
// is none. The collection type must implement Key(i) returning string or []byte. |
| 106 |
func (idx *Index) FindString(key string) int { |
| 107 |
k := StringKey(key) |
| 108 |
a, b := idx.FindUint64Range(k) |
| 109 |
switch data := idx.Data.(type) { |
| 110 |
case sorts.StringInterface: |
| 111 |
return a + sort.Search(b-a, func(i int) bool { |
| 112 |
return strings.Compare(key, data.Key(a+i)) >= 0 |
| 113 |
}) |
| 114 |
case sorts.BytesInterface: |
| 115 |
return a + sort.Search(b-a, func(i int) bool { |
| 116 |
return CompareStringToBytes(key, data.Key(a+i)) >= 0 |
| 117 |
}) |
| 118 |
default: |
| 119 |
panic("to use FindStringKey, Data.Key(i) must return string or []byte") |
| 120 |
} |
| 121 |
} |
| 122 |
|
| 123 |
// FindBytes finds the first item >= key, returning one after the end if there |
| 124 |
// is none. The collection type must implement Key(i) returning string or []byte. |
| 125 |
func (idx *Index) FindBytes(key []byte) int { |
| 126 |
k := BytesKey(key) |
| 127 |
a, b := idx.FindUint64Range(k) |
| 128 |
switch data := idx.Data.(type) { |
| 129 |
case sorts.StringInterface: |
| 130 |
return a + sort.Search(b-a, func(i int) bool { |
| 131 |
return CompareBytesToString(key, data.Key(a+i)) >= 0 |
| 132 |
}) |
| 133 |
case sorts.BytesInterface: |
| 134 |
offset := sort.Search(b-a, func(i int) bool { |
| 135 |
return bytes.Compare(key, data.Key(a+i)) >= 0 |
| 136 |
}) |
| 137 |
return a + offset |
| 138 |
default: |
| 139 |
panic("to use FindBytesKey, Data.Key(i) must return string or []byte") |
| 140 |
} |
| 141 |
} |
| 142 |
|
| 143 |
// FindUint64Range looks for a range of keys such that all items in idx.Keys[a:b] |
| 144 |
// equal key. |
| 145 |
// It can return an empty range if the item isn't found; in that case, a and b are both where the item would be inserted (and can be one past the end). |
| 146 |
// To find a single key, use FindUint64. |
| 147 |
func (idx *Index) FindUint64Range(key uint64) (a, b int) { |
| 148 |
a = idx.FindUint64(key) |
| 149 |
if a == len(idx.Keys) || idx.Keys[a] != key { |
| 150 |
// key not found, needn't search again |
| 151 |
return a, a |
| 152 |
} |
| 153 |
if key == ^uint64(0) { // would overflow |
| 154 |
b = len(idx.Keys) |
| 155 |
} else { |
| 156 |
b = idx.FindUint64(key + 1) |
| 157 |
} |
| 158 |
return |
| 159 |
} |
| 160 |
|
| 161 |
// FindStringRange(key) finds the range (a,b] such that Key() returns key for all items in idx.Data[a:b]. |
| 162 |
// It can return an empty range if the item isn't found; in that case, a and b are both where the item would be inserted (and can be one past the end). |
| 163 |
// Data must implement Key(i) returning string or []byte. |
| 164 |
// To find a single item, use FindString. |
| 165 |
func (idx *Index) FindStringRange(key string) (int, int) { |
| 166 |
k := StringKey(key) |
| 167 |
a, b := idx.FindUint64Range(k) |
| 168 |
switch data := idx.Data.(type) { |
| 169 |
case sorts.StringInterface: |
| 170 |
aa := a + sort.Search(b-a, func(i int) bool { |
| 171 |
return strings.Compare(key, data.Key(a+i)) >= 0 |
| 172 |
}) |
| 173 |
bb := aa + sort.Search(b-aa, func(i int) bool { |
| 174 |
return strings.Compare(key, data.Key(aa+i)) > 0 |
| 175 |
}) |
| 176 |
return aa, bb |
| 177 |
case sorts.BytesInterface: |
| 178 |
aa := a + sort.Search(b-a, func(i int) bool { |
| 179 |
return CompareStringToBytes(key, data.Key(a+i)) >= 0 |
| 180 |
}) |
| 181 |
bb := aa + sort.Search(b-aa, func(i int) bool { |
| 182 |
return CompareStringToBytes(key, data.Key(aa+i)) > 0 |
| 183 |
}) |
| 184 |
return aa, bb |
| 185 |
default: |
| 186 |
panic("to use FindStringRange, Data.Key(i) must return string or []byte") |
| 187 |
} |
| 188 |
} |
| 189 |
|
| 190 |
// FindBytesRange(key) finds the range (a,b] such that Key() returns key for all items in idx.Data[a:b]. |
| 191 |
// It can return an empty range if the item isn't found; in that case, a is where the item would be inserted (and can be one past the end). |
| 192 |
// Data must implement Key(i) returning string or []byte. |
| 193 |
// To find a single item, use FindBytes. |
| 194 |
func (idx *Index) FindBytesRange(key []byte) (int, int) { |
| 195 |
k := BytesKey(key) |
| 196 |
a, b := idx.FindUint64Range(k) |
| 197 |
switch data := idx.Data.(type) { |
| 198 |
case sorts.StringInterface: |
| 199 |
aa := a + sort.Search(b-a, func(i int) bool { |
| 200 |
return CompareBytesToString(key, data.Key(a+i)) >= 0 |
| 201 |
}) |
| 202 |
bb := aa + sort.Search(b-aa, func(i int) bool { |
| 203 |
return CompareBytesToString(key, data.Key(aa+i)) > 0 |
| 204 |
}) |
| 205 |
return aa, bb |
| 206 |
case sorts.BytesInterface: |
| 207 |
aa := a + sort.Search(b-a, func(i int) bool { |
| 208 |
return bytes.Compare(key, data.Key(a+i)) >= 0 |
| 209 |
}) |
| 210 |
bb := aa + sort.Search(b-aa, func(i int) bool { |
| 211 |
return bytes.Compare(key, data.Key(aa+i)) > 0 |
| 212 |
}) |
| 213 |
return aa, bb |
| 214 |
default: |
| 215 |
panic("to use FindStringRangeExact, Data.Key(i) must return string or []byte") |
| 216 |
} |
| 217 |
} |
| 218 |
|
| 219 |
func (idx *Index) findUint64Summary(key uint64) int { |
| 220 |
summary := idx.Summary |
| 221 |
keys := idx.Keys |
| 222 |
|
| 223 |
// count how many layers to expect in the "btree" |
| 224 |
levels, l := 0, len(keys) |
| 225 |
for l > 0 { |
| 226 |
levels++ |
| 227 |
l >>= levelBits |
| 228 |
} |
| 229 |
levels-- // went one too far |
| 230 |
|
| 231 |
// keep following largest-strictly-less down the chain |
| 232 |
levelNum := levels |
| 233 |
levelEnd := len(summary) |
| 234 |
offset := 0 |
| 235 |
for levelNum > 0 { |
| 236 |
// extract the "level" |
| 237 |
thisLevelBits := uint(levelBits * levelNum) |
| 238 |
levelLen := len(keys) >> thisLevelBits |
| 239 |
if len(keys) > levelLen<<thisLevelBits { |
| 240 |
// an entry for the remainder |
| 241 |
levelLen++ |
| 242 |
} |
| 243 |
level := summary[levelEnd-levelLen : levelEnd] |
| 244 |
|
| 245 |
// extract the page at the given offset |
| 246 |
pageEnd := offset + pageSize |
| 247 |
if pageEnd > len(level) { |
| 248 |
pageEnd = len(level) |
| 249 |
} |
| 250 |
page := level[offset:pageEnd] |
| 251 |
|
| 252 |
// scan page for an entry >= key |
| 253 |
// binsearch would be fewer operations but less predictable ones |
| 254 |
i := 0 |
| 255 |
for i < len(page) && page[i] < key { |
| 256 |
i++ |
| 257 |
} |
| 258 |
if i > 0 { |
| 259 |
// i is first one that goes too far |
| 260 |
i-- |
| 261 |
} |
| 262 |
|
| 263 |
// use that to walk down the tree |
| 264 |
// in particular, get next offset and level location |
| 265 |
offset += i |
| 266 |
offset <<= levelBits |
| 267 |
levelEnd -= levelLen |
| 268 |
levelNum-- |
| 269 |
} |
| 270 |
|
| 271 |
// level==0 is the original array |
| 272 |
pageEnd := offset + pageSize |
| 273 |
if pageEnd > len(keys) { |
| 274 |
pageEnd = len(keys) |
| 275 |
} |
| 276 |
page := keys[offset:pageEnd] |
| 277 |
i := 0 |
| 278 |
for i < len(page) && page[i] < key { |
| 279 |
i++ |
| 280 |
} |
| 281 |
return offset + i |
| 282 |
} |
| 283 |
|
| 284 |
// StringKey generates a uint64 key from the first bytes of key. |
| 285 |
func StringKey(key string) uint64 { |
| 286 |
k := uint64(0) |
| 287 |
for j := 0; j < 8 && j < len(key); j++ { |
| 288 |
k ^= uint64(key[j]) << uint(56-8*j) |
| 289 |
} |
| 290 |
return k |
| 291 |
} |
| 292 |
|
| 293 |
// BytesKey generates a uint64 key from the first bytes of key. |
| 294 |
func BytesKey(key []byte) uint64 { |
| 295 |
k := uint64(0) |
| 296 |
for j := 0; j < 8 && j < len(key); j++ { |
| 297 |
k ^= uint64(key[j]) << uint(56-8*j) |
| 298 |
} |
| 299 |
return k |
| 300 |
} |
| 301 |
|
| 302 |
// SortWithIndex allocates an Index with space for a uint64 key for each |
| 303 |
// item in data, then sorts items by their uint64 keys, using data.Less as a |
| 304 |
// tie-breaker for equal-keyed items. data may implement index.KeySetter or |
| 305 |
// any of sorts.StringInterface, BytesInterface, or Uint64Interface. |
| 306 |
func SortWithIndex(data sort.Interface) *Index { |
| 307 |
l := data.Len() |
| 308 |
indices := make([]uint64, l) |
| 309 |
idx := &Index{ |
| 310 |
Keys: indices, |
| 311 |
Data: data, |
| 312 |
} |
| 313 |
switch data := data.(type) { |
| 314 |
case sorts.StringInterface: |
| 315 |
for i := 0; i < l; i++ { |
| 316 |
key := data.Key(i) |
| 317 |
k := uint64(0) |
| 318 |
for j := 0; j < 8 && j < len(key); j++ { |
| 319 |
k ^= uint64(key[j]) << uint(56-8*j) |
| 320 |
} |
| 321 |
indices[i] = k |
| 322 |
} |
| 323 |
case sorts.BytesInterface: |
| 324 |
for i := 0; i < l; i++ { |
| 325 |
key := data.Key(i) |
| 326 |
k := uint64(0) |
| 327 |
for j := 0; j < 8 && j < len(key); j++ { |
| 328 |
k ^= uint64(key[j]) << uint(56-8*j) |
| 329 |
} |
| 330 |
indices[i] = k |
| 331 |
} |
| 332 |
case sorts.Uint64Interface: |
| 333 |
for i := 0; i < l; i++ { |
| 334 |
indices[i] = data.Key(i) |
| 335 |
} |
| 336 |
default: |
| 337 |
panic("don't know how to extract int keys for data") |
| 338 |
} |
| 339 |
sorts.ByUint64(idx) |
| 340 |
return idx |
| 341 |
} |