本站源代码
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

82 lines
1.8KB

  1. /*
  2. Copyright 2013 Google Inc.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. // Package consistenthash provides an implementation of a ring hash.
  14. package consistenthash
  15. import (
  16. "hash/crc32"
  17. "sort"
  18. "strconv"
  19. )
  20. type Hash func(data []byte) uint32
  21. type Map struct {
  22. hash Hash
  23. replicas int
  24. keys []int // Sorted
  25. hashMap map[int]string
  26. }
  27. func New(replicas int, fn Hash) *Map {
  28. m := &Map{
  29. replicas: replicas,
  30. hash: fn,
  31. hashMap: make(map[int]string),
  32. }
  33. if m.hash == nil {
  34. m.hash = crc32.ChecksumIEEE
  35. }
  36. return m
  37. }
  38. // Returns true if there are no items available.
  39. func (m *Map) IsEmpty() bool {
  40. return len(m.keys) == 0
  41. }
  42. // Adds some keys to the hash.
  43. func (m *Map) Add(keys ...string) {
  44. for _, key := range keys {
  45. for i := 0; i < m.replicas; i++ {
  46. hash := int(m.hash([]byte(strconv.Itoa(i) + key)))
  47. m.keys = append(m.keys, hash)
  48. m.hashMap[hash] = key
  49. }
  50. }
  51. sort.Ints(m.keys)
  52. }
  53. // Gets the closest item in the hash to the provided key.
  54. func (m *Map) Get(key string) string {
  55. if m.IsEmpty() {
  56. return ""
  57. }
  58. hash := int(m.hash([]byte(key)))
  59. // Binary search for appropriate replica.
  60. idx := sort.Search(len(m.keys), func(i int) bool { return m.keys[i] >= hash })
  61. // Means we have cycled back to the first replica.
  62. if idx == len(m.keys) {
  63. idx = 0
  64. }
  65. return m.hashMap[m.keys[idx]]
  66. }
上海开阖软件有限公司 沪ICP备12045867号-1