Module: SolidRedis::Cluster::KeySlot

Defined in:
lib/solid_redis/cluster/key_slot.rb

Overview

Maps a Redis key to one of the 16384 cluster hash slots using CRC16 (XMODEM) and the {hash tag} rule from the Redis Cluster specification.

Constant Summary collapse

SLOTS =
16_384
TABLE =

CRC16 XMODEM lookup table (polynomial 0x1021).

Ractor.make_shareable(
  Array.new(256) do |byte|
    crc = byte << 8
    8.times { crc = (crc & 0x8000).zero? ? (crc << 1) & 0xFFFF : ((crc << 1) ^ 0x1021) & 0xFFFF }
    crc
  end,
)

Class Method Summary collapse

Class Method Details

.crc16(string) ⇒ Object



35
36
37
38
39
# File 'lib/solid_redis/cluster/key_slot.rb', line 35

def crc16(string)
  string.each_byte.reduce(0) do |crc, byte|
    ((crc << 8) & 0xFFFF) ^ TABLE[((crc >> 8) ^ byte) & 0xFF]
  end
end

.for(key) ⇒ Object



21
22
23
# File 'lib/solid_redis/cluster/key_slot.rb', line 21

def for(key)
  crc16(hash_tag(key.to_s)) % SLOTS
end

.hash_tag(key) ⇒ Object



25
26
27
28
29
30
31
32
33
# File 'lib/solid_redis/cluster/key_slot.rb', line 25

def hash_tag(key)
  open = key.index("{")
  return key unless open

  close = key.index("}", open + 1)
  return key unless close && close > open + 1

  key[(open + 1)...close]
end