Class: NATS::NUID

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

Constant Summary collapse

DIGITS =
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".chars
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
@@nuid =
NUID.new.extend(MonitorMixin)

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeNUID

Returns a new instance of NUID.



32
33
34
35
36
37
38
# File 'lib/nats/nuid.rb', line 32

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

Class Method Details

.nextObject



87
88
89
90
91
# File 'lib/nats/nuid.rb', line 87

def next
  @@nuid.synchronize do
    @@nuid.next
  end
end

Instance Method Details

#nextObject



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/nats/nuid.rb', line 40

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



70
71
72
73
74
75
76
# File 'lib/nats/nuid.rb', line 70

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