Class: NATS::NUID

Inherits:
Object
  • Object
show all
Defined in:
lib/nats/nuid.rb

Constant Summary collapse

DIGITS =
[*'0'..'9', *'A'..'Z', *'a'..'z']
BASE =
62
PREFIX_LENGTH =
12
SEQ_LENGTH =
10
TOTAL_LENGTH =
PREFIX_LENGTH + SEQ_LENGTH
MAX_SEQ =
BASE**10
MIN_INC =
33
MAX_INC =
333
INC =
MAX_INC - MIN_INC

Instance Method Summary collapse

Constructor Details

#initializeNUID

Returns a new instance of NUID.



28
29
30
31
32
33
34
# File 'lib/nats/nuid.rb', line 28

def initialize
  @prand    = Random.new
  @seq      = @prand.rand(MAX_SEQ)
  @inc      = MIN_INC + @prand.rand(INC)
  @prefix   = ''
  randomize_prefix!
end

Instance Method Details

#nextObject



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/nats/nuid.rb', line 36

def next
  @seq += @inc
  if @seq >= MAX_SEQ
    randomize_prefix!
    reset_sequential!
  end
  l = @seq

  # Do this inline 10 times to avoid even more extra allocs,
  # then use string interpolation of everything which works
  # faster for doing concat.
  s_10 = DIGITS[l % BASE];

  # Ugly, but parallel assignment is slightly faster here...
  s_09, s_08, s_07, s_06, s_05, s_04, s_03, s_02, s_01 = \
  (l /= BASE; DIGITS[l % BASE]), (l /= BASE; DIGITS[l % BASE]), (l /= BASE; DIGITS[l % BASE]),\
  (l /= BASE; DIGITS[l % BASE]), (l /= BASE; DIGITS[l % BASE]), (l /= BASE; DIGITS[l % BASE]),\
  (l /= BASE; DIGITS[l % BASE]), (l /= BASE; DIGITS[l % BASE]), (l /= BASE; DIGITS[l % BASE])
  "#{@prefix}#{s_01}#{s_02}#{s_03}#{s_04}#{s_05}#{s_06}#{s_07}#{s_08}#{s_09}#{s_10}"
end

#randomize_prefix!Object



57
58
59
60
61
62
63
# File 'lib/nats/nuid.rb', line 57

def randomize_prefix!
  @prefix = \
  SecureRandom.random_bytes(PREFIX_LENGTH).each_byte
    .reduce('') do |prefix, n|
    prefix << DIGITS[n % BASE]
  end
end