<commit_before>require 'digest/md5'

class Ketama
  def initialize(servers)
    @continuum = []
    servers.each do |s|
      0.upto(39) do |i|
        digest = Digest::MD5.hexdigest([s, i] * '-')
        0.upto(3) do |j|
          @continuum[digest.slice(-4 * j - 4, 4).hex] = s
        end
      end
    end
  end

  def get_server(key)
    i = Digest::MD5.hexdigest(key).hex % 0x10000
    @continuum.size.times do |j|
      s = @continuum[(i + j) % @continuum.size]
      return s unless s.nil?
    end
    nil
  end
end

if $0 == __FILE__
  servers = %w(10.0.0.1 10.0.0.2 10.0.0.3 10.0.0.4 10.0.0.5 10.0.0.6)
  ketama = Ketama.new(servers)
  %w(foo bar baz test key widget).each do |w|
    puts [w, ketama.get_server(w)] * ': '
  end
end<commit_msg>use values from the beginning of the digest not the end<commit_after>require 'digest/md5'

class Ketama
  def initialize(servers)
    @continuum = []
    servers.each do |s|
      0.upto(39) do |i|
        digest = Digest::MD5.hexdigest([s, i] * '-')
        0.upto(3) do |j|
          @continuum[digest.slice(4 * j, 4).hex] = s
        end
      end
    end
  end

  def get_server(key)
    i = Digest::MD5.hexdigest(key).slice(0, 4).hex
    @continuum.size.times do |j|
      s = @continuum[(i + j) % @continuum.size]
      return s unless s.nil?
    end
    nil
  end
end

if $0 == __FILE__
  servers = %w(10.0.0.1 10.0.0.2 10.0.0.3 10.0.0.4 10.0.0.5 10.0.0.6)
  ketama = Ketama.new(servers)
  %w(foo bar baz test key widget).each do |w|
    puts [w, ketama.get_server(w)] * ': '
  end
end
{'fraction_non_alphanumeric': 0.15857605177993528, 'fraction_numerical': 0.05889967637540453, 'mean_word_length': 2.214137214137214, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 12, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4767097', 'n_tokens_mistral': 696, 'n_tokens_neox': 652, 'n_words': 154}