2 Copyright 2013 Google Inc.
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
8 http://www.apache.org/licenses/LICENSE-2.0
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
17 // Package consistenthash provides an implementation of a ring hash.
18 package consistenthash
26 type Hash func(data []byte) uint32
32 hashMap map[int]string
35 func New(replicas int, fn Hash) *Map {
39 hashMap: make(map[int]string),
42 m.hash = crc32.ChecksumIEEE
47 // Returns true if there are no items available.
48 func (m *Map) IsEmpty() bool {
49 return len(m.keys) == 0
52 // Adds some keys to the hash.
53 func (m *Map) Add(keys ...string) {
54 for _, key := range keys {
55 for i := 0; i < m.replicas; i++ {
56 hash := int(m.hash([]byte(strconv.Itoa(i) + key)))
57 m.keys = append(m.keys, hash)
64 // Gets the closest item in the hash to the provided key.
65 func (m *Map) Get(key string) string {
70 hash := int(m.hash([]byte(key)))
72 // Binary search for appropriate replica.
73 idx := sort.Search(len(m.keys), func(i int) bool { return m.keys[i] >= hash })
75 // Means we have cycled back to the first replica.
76 if idx == len(m.keys) {
80 return m.hashMap[m.keys[idx]]