File: hash.go

package info (click to toggle)
golang-github-mna-redisc 1.1.7-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, sid
  • size: 308 kB
  • sloc: ruby: 1,261; sh: 101; makefile: 5
file content (45 lines) | stat: -rw-r--r-- 1,028 bytes parent folder | download
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
package redisc

import (
	"sort"
	"strings"
)

// Slot returns the hash slot for the key.
func Slot(key string) int {
	if start := strings.Index(key, "{"); start >= 0 {
		if end := strings.Index(key[start+1:], "}"); end > 0 { // if end == 0, then it's {}, so we ignore it
			end += start + 1
			key = key[start+1 : end]
		}
	}
	return int(crc16(key) % hashSlots)
}

// SplitBySlot takes a list of keys and returns a list of list of keys,
// grouped by identical cluster slot. For example:
//
//     bySlot := SplitBySlot("k1", "k2", "k3")
//     for _, keys := range bySlot {
//       // keys is a list of keys that belong to the same slot
//     }
func SplitBySlot(keys ...string) [][]string {
	var slots []int
	m := make(map[int][]string)
	for _, k := range keys {
		slot := Slot(k)
		_, ok := m[slot]
		m[slot] = append(m[slot], k)

		if !ok {
			slots = append(slots, slot)
		}
	}

	sort.Ints(slots)
	bySlot := make([][]string, 0, len(m))
	for _, slot := range slots {
		bySlot = append(bySlot, m[slot])
	}
	return bySlot
}