Class: ULID

Inherits:
Object
  • Object
show all
Includes:
Comparable
Defined in:
lib/ulid.rb,
lib/ulid/uuid.rb,
lib/ulid/utils.rb,
lib/ulid/errors.rb,
lib/ulid/version.rb,
lib/ulid/crockford_base32.rb,
lib/ulid/monotonic_generator.rb

Overview

shareable_constant_value: literal

Defined Under Namespace

Classes: Error, IrreversibleUUIDError, MonotonicGenerator, OverflowError, ParserError, UnexpectedError

Constant Summary collapse

TIMESTAMP_ENCODED_LENGTH =
10
RANDOMNESS_ENCODED_LENGTH =
16
ENCODED_LENGTH =
26
MAX_MILLISECONDS =
281474976710655
MAX_ENTROPY =
1208925819614629174706175
MAX_INTEGER =
340282366920938463463374607431768211455
VERSION =
'0.8.0'

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(milliseconds:, entropy:, integer:, encoded:) ⇒ void

Parameters:

  • milliseconds (Integer)
  • entropy (Integer)
  • integer (Integer)
  • encoded (String)


366
367
368
369
370
371
372
373
# File 'lib/ulid.rb', line 366

def initialize(milliseconds:, entropy:, integer:, encoded:)
  # All arguments check should be done with each constructors, not here
  @integer = integer
  @encoded = encoded
  @milliseconds = milliseconds
  @entropy = entropy
  freeze
end

Instance Attribute Details

#entropyInteger (readonly)

Returns:

  • (Integer)


20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
# File 'lib/ulid.rb', line 20

class ULID
  include(Comparable)

  TIMESTAMP_ENCODED_LENGTH = 10
  RANDOMNESS_ENCODED_LENGTH = 16
  ENCODED_LENGTH = 26

  OCTETS_LENGTH = 16

  MAX_MILLISECONDS = 281474976710655
  MAX_ENTROPY = 1208925819614629174706175
  MAX_INTEGER = 340282366920938463463374607431768211455

  # @see https://github.com/ulid/spec/pull/57
  # Currently not used as a constant, but kept as a reference for now.
  PATTERN_WITH_CROCKFORD_BASE32_SUBSET = /(?<timestamp>[0-7][#{CrockfordBase32::ENCODING_STRING}]{#{TIMESTAMP_ENCODED_LENGTH - 1}})(?<randomness>[#{CrockfordBase32::ENCODING_STRING}]{#{RANDOMNESS_ENCODED_LENGTH}})/i

  STRICT_PATTERN_WITH_CROCKFORD_BASE32_SUBSET = /\A#{PATTERN_WITH_CROCKFORD_BASE32_SUBSET.source}\z/i

  # Optimized for `ULID.scan`, might be changed the definition with gathered `ULID.scan` spec changed.
  SCANNING_PATTERN = /\b[0-7][#{CrockfordBase32::ENCODING_STRING}]{#{TIMESTAMP_ENCODED_LENGTH - 1}}[#{CrockfordBase32::ENCODING_STRING}]{#{RANDOMNESS_ENCODED_LENGTH}}\b/i

  # Similar as Time#inspect since Ruby 2.7, however it is NOT same.
  # Time#inspect trancates needless digits. Keeping full milliseconds with "%3N" will fit for ULID.
  # @see https://bugs.ruby-lang.org/issues/15958
  # @see https://github.com/ruby/ruby/blob/744d17ff6c33b09334508e8110007ea2a82252f5/time.c#L4026-L4078
  TIME_FORMAT_IN_INSPECT = '%Y-%m-%d %H:%M:%S.%3N %Z'

  RANDOM_INTEGER_GENERATOR = -> {
    SecureRandom.random_number(MAX_INTEGER)
  }.freeze

  Utils.make_sharable_constants(self)

  private_constant(
    :PATTERN_WITH_CROCKFORD_BASE32_SUBSET,
    :STRICT_PATTERN_WITH_CROCKFORD_BASE32_SUBSET,
    :SCANNING_PATTERN,
    :TIME_FORMAT_IN_INSPECT,
    :RANDOM_INTEGER_GENERATOR,
    :OCTETS_LENGTH,
    :UUID
  )

  private_class_method(:new, :allocate)

  # @param [Integer, Time] moment
  # @param [Integer] entropy
  # @return [ULID]
  # @raise [OverflowError] if the given value is larger than the ULID limit
  # @raise [ArgumentError] if the given milliseconds and/or entropy is negative number
  def self.generate(moment: Utils.current_milliseconds, entropy: Utils.reasonable_entropy)
    milliseconds = Utils.milliseconds_from_moment(moment)
    base32hex = Utils.encode_base32hex(milliseconds:, entropy:)
    new(
      milliseconds:,
      entropy:,
      integer: Integer(base32hex, 32, exception: true),
      encoded: CrockfordBase32.from_base32hex(base32hex).freeze
    )
  end

  # Almost same as [.generate] except directly returning String without needless object creation
  #
  # @param [Integer, Time] moment
  # @param [Integer] entropy
  # @return [String]
  def self.encode(moment: Utils.current_milliseconds, entropy: Utils.reasonable_entropy)
    base32hex = Utils.encode_base32hex(milliseconds: Utils.milliseconds_from_moment(moment), entropy:)
    CrockfordBase32.from_base32hex(base32hex)
  end

  # Short hand of `ULID.generate(moment: time)`
  # @param [Time] time
  # @return [ULID]
  def self.at(time)
    raise(ArgumentError, 'ULID.at takes only `Time` instance') unless Time === time

    generate(moment: time)
  end

  # @param [Time, Integer] moment
  # @return [ULID]
  def self.min(moment=0)
    0.equal?(moment) ? MIN : generate(moment:, entropy: 0)
  end

  # @param [Time, Integer] moment
  # @return [ULID]
  def self.max(moment=MAX_MILLISECONDS)
    MAX_MILLISECONDS.equal?(moment) ? MAX : generate(moment:, entropy: MAX_ENTROPY)
  end

  # @param [Range<Time>, Range<nil>, Range[ULID], nil] period
  # @overload sample(number, period: nil)
  #   @param [Integer] number
  #   @return [Array<ULID>]
  #   @raise [ArgumentError] if the given number is lager than `ULID spec limits` or `Possibilities of given period`, or given negative number
  # @overload sample(period: nil)
  #   @return [ULID]
  # @note Major difference of `Array#sample` interface is below
  #   * Do not ensure the uniqueness
  #   * Do not take random generator for the arguments
  #   * Raising error instead of truncating elements for the given number
  def self.sample(number=nil, period: nil)
    int_generator = (
      if period
        ulid_range = range(period)
        min, max, exclude_end = ulid_range.begin.to_i, ulid_range.end.to_i, ulid_range.exclude_end?

        possibilities = (max - min) + (exclude_end ? 0 : 1)
        raise(ArgumentError, "given range `#{ulid_range.inspect}` does not have possibilities") unless possibilities.positive?

        -> {
          SecureRandom.random_number(possibilities) + min
        }
      else
        RANDOM_INTEGER_GENERATOR
      end
    )

    case number
    when nil
      from_integer(int_generator.call)
    when Integer
      if number > MAX_INTEGER || number.negative?
        raise(ArgumentError, "given number `#{number}` is larger than ULID limit `#{MAX_INTEGER}` or negative")
      end

      if period && possibilities && (number > possibilities)
        raise(ArgumentError, "given number `#{number}` is larger than given possibilities `#{possibilities}`")
      end

      Array.new(number) { from_integer(int_generator.call) }
    else
      raise(ArgumentError, 'accepts no argument or integer only')
    end
  end

  # @param [String, #to_str] string
  # @return [Enumerator]
  # @yieldparam [ULID] ulid
  # @yieldreturn [self]
  def self.scan(string)
    string = String.try_convert(string)
    raise(ArgumentError, 'ULID.scan takes only strings') unless string
    return to_enum(:scan, string) unless block_given?

    string.scan(SCANNING_PATTERN) do |matched|
      if String === matched
        yield(parse(matched))
      end
    end
    self
  end

  # @param [Integer] integer
  # @return [ULID]
  # @raise [OverflowError] if the given integer is larger than the ULID limit
  # @raise [ArgumentError] if the given integer is negative number
  def self.from_integer(integer)
    raise(ArgumentError, 'ULID.from_integer takes only `Integer`') unless Integer === integer
    raise(OverflowError, "integer overflow: given #{integer}, max: #{MAX_INTEGER}") unless integer <= MAX_INTEGER
    raise(ArgumentError, "integer should not be negative: given: #{integer}") if integer.negative?

    base32hex = integer.to_s(32).rjust(ENCODED_LENGTH, '0')
    base32hex_timestamp = base32hex.slice(0, TIMESTAMP_ENCODED_LENGTH)
    base32hex_randomness = base32hex.slice(TIMESTAMP_ENCODED_LENGTH, RANDOMNESS_ENCODED_LENGTH)

    raise(UnexpectedError) unless base32hex_timestamp && base32hex_randomness

    milliseconds = Integer(base32hex_timestamp, 32, exception: true)
    entropy = Integer(base32hex_randomness, 32, exception: true)

    new(
      milliseconds:,
      entropy:,
      integer:,
      encoded: CrockfordBase32.from_base32hex(base32hex).freeze
    )
  end

  # @param [Range<Time>, Range<nil>, Range[ULID]] period
  # @return [Range<ULID>]
  # @raise [ArgumentError] if the given period is not a `Range[Time]`, `Range[nil]` or `Range[ULID]`
  def self.range(period)
    raise(ArgumentError, 'ULID.range takes only `Range[Time]`, `Range[nil]` or `Range[ULID]`') unless Range === period

    begin_element, end_element, exclude_end = period.begin, period.end, period.exclude_end?

    begin_ulid = (
      case begin_element
      when Time
        min(begin_element)
      when nil
        MIN
      when self
        begin_element
      else
        raise(ArgumentError, "ULID.range takes only `Range[Time]`, `Range[nil]` or `Range[ULID]`, given: #{period.inspect}")
      end
    )

    end_ulid = (
      case end_element
      when Time
        exclude_end ? min(end_element) : max(end_element)
      when nil
        exclude_end = false
        # The end should be max and include end, because nil end means to cover endless ULIDs until the limit
        MAX
      when self
        end_element
      else
        raise(ArgumentError, "ULID.range takes only `Range[Time]`, `Range[nil]` or `Range[ULID]`, given: #{period.inspect}")
      end
    )

    Range.new(begin_ulid, end_ulid, exclude_end)
  end

  # @param [Time] time
  # @return [Time]
  def self.floor(time)
    raise(ArgumentError, 'ULID.floor takes only `Time` instance') unless Time === time

    time.floor(3)
  end

  # @param [String, #to_str] string
  # @return [ULID]
  # @raise [ParserError] if the given format is not correct for ULID specs
  def self.parse(string)
    string = String.try_convert(string)
    raise(ArgumentError, 'ULID.parse takes only strings') unless string

    unless STRICT_PATTERN_WITH_CROCKFORD_BASE32_SUBSET.match?(string)
      raise(ParserError, "given `#{string}` does not match to `#{STRICT_PATTERN_WITH_CROCKFORD_BASE32_SUBSET.inspect}`")
    end

    from_integer(CrockfordBase32.decode(string))
  end

  # @param [String, #to_str] string
  # @return [ULID]
  # @raise [ParserError] if the given format is not correct for ULID specs
  def self.parse_variant_format(string)
    string = String.try_convert(string)
    raise(ArgumentError, 'ULID.parse_variant_format takes only strings') unless string

    normalized_in_crockford = CrockfordBase32.normalize(string)
    parse(normalized_in_crockford)
  end

  # Almost same as `ULID.parse(string).to_time` except directly returning Time instance without needless object creation
  #
  # @param [String, #to_str] string
  # @param [String, Integer, nil] in
  # @return [Time]
  # @raise [ParserError] if the given format is not correct for ULID specs
  def self.decode_time(string, in: 'UTC')
    in_for_time_at = { in: }.fetch(:in)
    string = String.try_convert(string)
    raise(ArgumentError, 'ULID.decode_time takes only strings') unless string

    unless STRICT_PATTERN_WITH_CROCKFORD_BASE32_SUBSET.match?(string)
      raise(ParserError, "given `#{string}` does not match to `#{STRICT_PATTERN_WITH_CROCKFORD_BASE32_SUBSET.inspect}`")
    end

    timestamp = string.slice(0, TIMESTAMP_ENCODED_LENGTH).freeze || raise(UnexpectedError)

    Time.at(0, CrockfordBase32.decode(timestamp), :millisecond, in: in_for_time_at)
  end

  # @param [String, #to_str] string
  # @return [String]
  # @raise [ParserError] if the given format is not correct for ULID specs, even if ignored `orthographical variants of the format`
  def self.normalize(string)
    string = String.try_convert(string)
    raise(ArgumentError, 'ULID.normalize takes only strings') unless string

    # Ensure the ULID correctness, because CrockfordBase32 does not always mean to satisfy ULID format
    parse_variant_format(string).encode
  end

  # @param [String, #to_str] string
  # @return [Boolean]
  def self.normalized?(string)
    normalized = normalize(string)
  rescue Exception
    false
  else
    normalized == string
  end

  # @param [String, #to_str] string
  # @return [Boolean]
  def self.valid_as_variant_format?(string)
    parse_variant_format(string)
  rescue Exception
    false
  else
    true
  end

  # @param [ULID, #to_ulid] object
  # @return [ULID, nil]
  # @raise [TypeError] if `object.to_ulid` did not return ULID instance
  def self.try_convert(object)
    begin
      converted = object.to_ulid
    rescue NoMethodError
      nil
    else
      if ULID === converted
        converted
      else
        object_class_name = Utils.safe_get_class_name(object)
        converted_class_name = Utils.safe_get_class_name(converted)
        raise(TypeError, "can't convert #{object_class_name} to ULID (#{object_class_name}#to_ulid gives #{converted_class_name})")
      end
    end
  end

  # @param [String, #to_str] uuidish
  # @return [ULID]
  # @raise [ParserError] if the given format is not correct for UUID`ish` format
  def self.from_uuidish(uuidish)
    from_integer(UUID.parse_any_to_int(uuidish))
  end

  # @param [String, #to_str] uuid
  # @return [ULID]
  # @raise [ParserError] if the given format is not correct for UUIDv4 specs
  def self.from_uuidv4(uuid)
    from_integer(UUID.parse_v4_to_int(uuid))
  end

  attr_reader(:milliseconds, :entropy, :encoded)
  protected(:encoded)

  # @param [Integer] milliseconds
  # @param [Integer] entropy
  # @param [Integer] integer
  # @param [String] encoded
  # @return [void]
  def initialize(milliseconds:, entropy:, integer:, encoded:)
    # All arguments check should be done with each constructors, not here
    @integer = integer
    @encoded = encoded
    @milliseconds = milliseconds
    @entropy = entropy
    freeze
  end

  # @return [String]
  def encode
    @encoded
  end
  alias_method(:to_s, :encode)

  # @return [Integer]
  def to_i
    @integer
  end

  # @return [Integer]
  def hash
    [ULID, @integer].hash
  end

  # @return [-1, 0, 1, nil]
  def <=>(other)
    (ULID === other) ? (@integer <=> other.to_i) : nil
  end

  # @return [String]
  def inspect
    "ULID(#{to_time.strftime(TIME_FORMAT_IN_INSPECT)}: #{@encoded})"
  end

  # @return [Boolean]
  def eql?(other)
    equal?(other) || (ULID === other && @integer == other.to_i)
  end
  alias_method(:==, :eql?)

  # Return `true` for same value of ULID, variant formats of strings, same Time in ULID precision(msec).
  # Do not consider integer, octets and partial strings, then returns `false`.
  #
  # @return [Boolean]
  # @see .normalize
  # @see .floor
  def ===(other)
    case other
    when ULID
      @integer == other.to_i
    when String
      begin
        to_i == ULID.parse_variant_format(other).to_i
      rescue Exception
        false
      end
    when Time
      to_time == ULID.floor(other)
    else
      false
    end
  end

  # @return [Time]
  # @param [String, Integer, nil] in
  def to_time(in: 'UTC')
    Time.at(0, @milliseconds, :millisecond, in: { in: }.fetch(:in))
  end

  # @return [Array(Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)]
  def octets
    digits = @integer.digits(256)
    digits.fill(0, digits.size, OCTETS_LENGTH - digits.size).reverse
  end

  # @return [String]
  def timestamp
    @encoded.slice(0, TIMESTAMP_ENCODED_LENGTH) || raise(UnexpectedError)
  end

  # @return [String]
  def randomness
    @encoded.slice(TIMESTAMP_ENCODED_LENGTH, RANDOMNESS_ENCODED_LENGTH) || raise(UnexpectedError)
  end

  # @return [ULID, nil] when called on ULID as `7ZZZZZZZZZZZZZZZZZZZZZZZZZ`, returns `nil` instead of ULID
  def succ
    succ_int = @integer.succ
    if succ_int >= MAX_INTEGER
      if succ_int == MAX_INTEGER
        MAX
      else
        nil
      end
    else
      ULID.from_integer(succ_int)
    end
  end
  alias_method(:next, :succ)

  # @return [ULID, nil] when called on ULID as `00000000000000000000000000`, returns `nil` instead of ULID
  def pred
    pred_int = @integer.pred
    if pred_int <= 0
      if pred_int == 0
        MIN
      else
        nil
      end
    else
      ULID.from_integer(pred_int)
    end
  end

  # @return [Integer]
  def marshal_dump
    @integer
  end

  # @param [Integer] integer
  # @return [void]
  def marshal_load(integer)
    unmarshaled = ULID.from_integer(integer)
    initialize(
      integer: unmarshaled.to_i,
      milliseconds: unmarshaled.milliseconds,
      entropy: unmarshaled.entropy,
      encoded: unmarshaled.encoded
    )
  end

  # @return [self]
  def to_ulid
    self
  end

  # Generate a UUID-like string that does not set the version and variants field.
  # It means wrong in UUIDv4 spec, but reversible
  #
  # @return [String]
  def to_uuidish
    UUID::Fields.raw_from_octets(octets).to_s.freeze
  end

  # Generate a UUIDv4-like string that sets the version and variants field.
  # It may conform to the UUID specification, but it is irreversible with the source ULID and may conflict with some other ULIDs.
  # You can specify `force` keyword argument to turn off the irreversible check
  #
  # @raise [IrreversibleUUIDError] if the converted UUID cannot be reversible with the replacing above 2 fields
  # @see https://github.com/kachick/ruby-ulid/issues/76
  # @param [bool] force
  # @return [String]
  def to_uuidv4(force: false)
    v4 = UUID::Fields.forced_v4_from_octets(octets)
    unless force
      uuidish = UUID::Fields.raw_from_octets(octets)
      raise(IrreversibleUUIDError) unless uuidish == v4
    end

    v4.to_s.freeze
  end

  # @return [ULID]
  def dup
    super.freeze
  end

  # @return [ULID]
  def clone(freeze: true)
    raise(ArgumentError, 'unfreezing ULID is an unexpected operation') unless freeze == true

    super
  end

  MIN = parse('00000000000000000000000000')
  MAX = parse('7ZZZZZZZZZZZZZZZZZZZZZZZZZ')

  Ractor.make_shareable(MIN)
  Ractor.make_shareable(MAX)

  private_constant(:MIN, :MAX)
end

#millisecondsInteger (readonly)

Returns:

  • (Integer)


20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
# File 'lib/ulid.rb', line 20

class ULID
  include(Comparable)

  TIMESTAMP_ENCODED_LENGTH = 10
  RANDOMNESS_ENCODED_LENGTH = 16
  ENCODED_LENGTH = 26

  OCTETS_LENGTH = 16

  MAX_MILLISECONDS = 281474976710655
  MAX_ENTROPY = 1208925819614629174706175
  MAX_INTEGER = 340282366920938463463374607431768211455

  # @see https://github.com/ulid/spec/pull/57
  # Currently not used as a constant, but kept as a reference for now.
  PATTERN_WITH_CROCKFORD_BASE32_SUBSET = /(?<timestamp>[0-7][#{CrockfordBase32::ENCODING_STRING}]{#{TIMESTAMP_ENCODED_LENGTH - 1}})(?<randomness>[#{CrockfordBase32::ENCODING_STRING}]{#{RANDOMNESS_ENCODED_LENGTH}})/i

  STRICT_PATTERN_WITH_CROCKFORD_BASE32_SUBSET = /\A#{PATTERN_WITH_CROCKFORD_BASE32_SUBSET.source}\z/i

  # Optimized for `ULID.scan`, might be changed the definition with gathered `ULID.scan` spec changed.
  SCANNING_PATTERN = /\b[0-7][#{CrockfordBase32::ENCODING_STRING}]{#{TIMESTAMP_ENCODED_LENGTH - 1}}[#{CrockfordBase32::ENCODING_STRING}]{#{RANDOMNESS_ENCODED_LENGTH}}\b/i

  # Similar as Time#inspect since Ruby 2.7, however it is NOT same.
  # Time#inspect trancates needless digits. Keeping full milliseconds with "%3N" will fit for ULID.
  # @see https://bugs.ruby-lang.org/issues/15958
  # @see https://github.com/ruby/ruby/blob/744d17ff6c33b09334508e8110007ea2a82252f5/time.c#L4026-L4078
  TIME_FORMAT_IN_INSPECT = '%Y-%m-%d %H:%M:%S.%3N %Z'

  RANDOM_INTEGER_GENERATOR = -> {
    SecureRandom.random_number(MAX_INTEGER)
  }.freeze

  Utils.make_sharable_constants(self)

  private_constant(
    :PATTERN_WITH_CROCKFORD_BASE32_SUBSET,
    :STRICT_PATTERN_WITH_CROCKFORD_BASE32_SUBSET,
    :SCANNING_PATTERN,
    :TIME_FORMAT_IN_INSPECT,
    :RANDOM_INTEGER_GENERATOR,
    :OCTETS_LENGTH,
    :UUID
  )

  private_class_method(:new, :allocate)

  # @param [Integer, Time] moment
  # @param [Integer] entropy
  # @return [ULID]
  # @raise [OverflowError] if the given value is larger than the ULID limit
  # @raise [ArgumentError] if the given milliseconds and/or entropy is negative number
  def self.generate(moment: Utils.current_milliseconds, entropy: Utils.reasonable_entropy)
    milliseconds = Utils.milliseconds_from_moment(moment)
    base32hex = Utils.encode_base32hex(milliseconds:, entropy:)
    new(
      milliseconds:,
      entropy:,
      integer: Integer(base32hex, 32, exception: true),
      encoded: CrockfordBase32.from_base32hex(base32hex).freeze
    )
  end

  # Almost same as [.generate] except directly returning String without needless object creation
  #
  # @param [Integer, Time] moment
  # @param [Integer] entropy
  # @return [String]
  def self.encode(moment: Utils.current_milliseconds, entropy: Utils.reasonable_entropy)
    base32hex = Utils.encode_base32hex(milliseconds: Utils.milliseconds_from_moment(moment), entropy:)
    CrockfordBase32.from_base32hex(base32hex)
  end

  # Short hand of `ULID.generate(moment: time)`
  # @param [Time] time
  # @return [ULID]
  def self.at(time)
    raise(ArgumentError, 'ULID.at takes only `Time` instance') unless Time === time

    generate(moment: time)
  end

  # @param [Time, Integer] moment
  # @return [ULID]
  def self.min(moment=0)
    0.equal?(moment) ? MIN : generate(moment:, entropy: 0)
  end

  # @param [Time, Integer] moment
  # @return [ULID]
  def self.max(moment=MAX_MILLISECONDS)
    MAX_MILLISECONDS.equal?(moment) ? MAX : generate(moment:, entropy: MAX_ENTROPY)
  end

  # @param [Range<Time>, Range<nil>, Range[ULID], nil] period
  # @overload sample(number, period: nil)
  #   @param [Integer] number
  #   @return [Array<ULID>]
  #   @raise [ArgumentError] if the given number is lager than `ULID spec limits` or `Possibilities of given period`, or given negative number
  # @overload sample(period: nil)
  #   @return [ULID]
  # @note Major difference of `Array#sample` interface is below
  #   * Do not ensure the uniqueness
  #   * Do not take random generator for the arguments
  #   * Raising error instead of truncating elements for the given number
  def self.sample(number=nil, period: nil)
    int_generator = (
      if period
        ulid_range = range(period)
        min, max, exclude_end = ulid_range.begin.to_i, ulid_range.end.to_i, ulid_range.exclude_end?

        possibilities = (max - min) + (exclude_end ? 0 : 1)
        raise(ArgumentError, "given range `#{ulid_range.inspect}` does not have possibilities") unless possibilities.positive?

        -> {
          SecureRandom.random_number(possibilities) + min
        }
      else
        RANDOM_INTEGER_GENERATOR
      end
    )

    case number
    when nil
      from_integer(int_generator.call)
    when Integer
      if number > MAX_INTEGER || number.negative?
        raise(ArgumentError, "given number `#{number}` is larger than ULID limit `#{MAX_INTEGER}` or negative")
      end

      if period && possibilities && (number > possibilities)
        raise(ArgumentError, "given number `#{number}` is larger than given possibilities `#{possibilities}`")
      end

      Array.new(number) { from_integer(int_generator.call) }
    else
      raise(ArgumentError, 'accepts no argument or integer only')
    end
  end

  # @param [String, #to_str] string
  # @return [Enumerator]
  # @yieldparam [ULID] ulid
  # @yieldreturn [self]
  def self.scan(string)
    string = String.try_convert(string)
    raise(ArgumentError, 'ULID.scan takes only strings') unless string
    return to_enum(:scan, string) unless block_given?

    string.scan(SCANNING_PATTERN) do |matched|
      if String === matched
        yield(parse(matched))
      end
    end
    self
  end

  # @param [Integer] integer
  # @return [ULID]
  # @raise [OverflowError] if the given integer is larger than the ULID limit
  # @raise [ArgumentError] if the given integer is negative number
  def self.from_integer(integer)
    raise(ArgumentError, 'ULID.from_integer takes only `Integer`') unless Integer === integer
    raise(OverflowError, "integer overflow: given #{integer}, max: #{MAX_INTEGER}") unless integer <= MAX_INTEGER
    raise(ArgumentError, "integer should not be negative: given: #{integer}") if integer.negative?

    base32hex = integer.to_s(32).rjust(ENCODED_LENGTH, '0')
    base32hex_timestamp = base32hex.slice(0, TIMESTAMP_ENCODED_LENGTH)
    base32hex_randomness = base32hex.slice(TIMESTAMP_ENCODED_LENGTH, RANDOMNESS_ENCODED_LENGTH)

    raise(UnexpectedError) unless base32hex_timestamp && base32hex_randomness

    milliseconds = Integer(base32hex_timestamp, 32, exception: true)
    entropy = Integer(base32hex_randomness, 32, exception: true)

    new(
      milliseconds:,
      entropy:,
      integer:,
      encoded: CrockfordBase32.from_base32hex(base32hex).freeze
    )
  end

  # @param [Range<Time>, Range<nil>, Range[ULID]] period
  # @return [Range<ULID>]
  # @raise [ArgumentError] if the given period is not a `Range[Time]`, `Range[nil]` or `Range[ULID]`
  def self.range(period)
    raise(ArgumentError, 'ULID.range takes only `Range[Time]`, `Range[nil]` or `Range[ULID]`') unless Range === period

    begin_element, end_element, exclude_end = period.begin, period.end, period.exclude_end?

    begin_ulid = (
      case begin_element
      when Time
        min(begin_element)
      when nil
        MIN
      when self
        begin_element
      else
        raise(ArgumentError, "ULID.range takes only `Range[Time]`, `Range[nil]` or `Range[ULID]`, given: #{period.inspect}")
      end
    )

    end_ulid = (
      case end_element
      when Time
        exclude_end ? min(end_element) : max(end_element)
      when nil
        exclude_end = false
        # The end should be max and include end, because nil end means to cover endless ULIDs until the limit
        MAX
      when self
        end_element
      else
        raise(ArgumentError, "ULID.range takes only `Range[Time]`, `Range[nil]` or `Range[ULID]`, given: #{period.inspect}")
      end
    )

    Range.new(begin_ulid, end_ulid, exclude_end)
  end

  # @param [Time] time
  # @return [Time]
  def self.floor(time)
    raise(ArgumentError, 'ULID.floor takes only `Time` instance') unless Time === time

    time.floor(3)
  end

  # @param [String, #to_str] string
  # @return [ULID]
  # @raise [ParserError] if the given format is not correct for ULID specs
  def self.parse(string)
    string = String.try_convert(string)
    raise(ArgumentError, 'ULID.parse takes only strings') unless string

    unless STRICT_PATTERN_WITH_CROCKFORD_BASE32_SUBSET.match?(string)
      raise(ParserError, "given `#{string}` does not match to `#{STRICT_PATTERN_WITH_CROCKFORD_BASE32_SUBSET.inspect}`")
    end

    from_integer(CrockfordBase32.decode(string))
  end

  # @param [String, #to_str] string
  # @return [ULID]
  # @raise [ParserError] if the given format is not correct for ULID specs
  def self.parse_variant_format(string)
    string = String.try_convert(string)
    raise(ArgumentError, 'ULID.parse_variant_format takes only strings') unless string

    normalized_in_crockford = CrockfordBase32.normalize(string)
    parse(normalized_in_crockford)
  end

  # Almost same as `ULID.parse(string).to_time` except directly returning Time instance without needless object creation
  #
  # @param [String, #to_str] string
  # @param [String, Integer, nil] in
  # @return [Time]
  # @raise [ParserError] if the given format is not correct for ULID specs
  def self.decode_time(string, in: 'UTC')
    in_for_time_at = { in: }.fetch(:in)
    string = String.try_convert(string)
    raise(ArgumentError, 'ULID.decode_time takes only strings') unless string

    unless STRICT_PATTERN_WITH_CROCKFORD_BASE32_SUBSET.match?(string)
      raise(ParserError, "given `#{string}` does not match to `#{STRICT_PATTERN_WITH_CROCKFORD_BASE32_SUBSET.inspect}`")
    end

    timestamp = string.slice(0, TIMESTAMP_ENCODED_LENGTH).freeze || raise(UnexpectedError)

    Time.at(0, CrockfordBase32.decode(timestamp), :millisecond, in: in_for_time_at)
  end

  # @param [String, #to_str] string
  # @return [String]
  # @raise [ParserError] if the given format is not correct for ULID specs, even if ignored `orthographical variants of the format`
  def self.normalize(string)
    string = String.try_convert(string)
    raise(ArgumentError, 'ULID.normalize takes only strings') unless string

    # Ensure the ULID correctness, because CrockfordBase32 does not always mean to satisfy ULID format
    parse_variant_format(string).encode
  end

  # @param [String, #to_str] string
  # @return [Boolean]
  def self.normalized?(string)
    normalized = normalize(string)
  rescue Exception
    false
  else
    normalized == string
  end

  # @param [String, #to_str] string
  # @return [Boolean]
  def self.valid_as_variant_format?(string)
    parse_variant_format(string)
  rescue Exception
    false
  else
    true
  end

  # @param [ULID, #to_ulid] object
  # @return [ULID, nil]
  # @raise [TypeError] if `object.to_ulid` did not return ULID instance
  def self.try_convert(object)
    begin
      converted = object.to_ulid
    rescue NoMethodError
      nil
    else
      if ULID === converted
        converted
      else
        object_class_name = Utils.safe_get_class_name(object)
        converted_class_name = Utils.safe_get_class_name(converted)
        raise(TypeError, "can't convert #{object_class_name} to ULID (#{object_class_name}#to_ulid gives #{converted_class_name})")
      end
    end
  end

  # @param [String, #to_str] uuidish
  # @return [ULID]
  # @raise [ParserError] if the given format is not correct for UUID`ish` format
  def self.from_uuidish(uuidish)
    from_integer(UUID.parse_any_to_int(uuidish))
  end

  # @param [String, #to_str] uuid
  # @return [ULID]
  # @raise [ParserError] if the given format is not correct for UUIDv4 specs
  def self.from_uuidv4(uuid)
    from_integer(UUID.parse_v4_to_int(uuid))
  end

  attr_reader(:milliseconds, :entropy, :encoded)
  protected(:encoded)

  # @param [Integer] milliseconds
  # @param [Integer] entropy
  # @param [Integer] integer
  # @param [String] encoded
  # @return [void]
  def initialize(milliseconds:, entropy:, integer:, encoded:)
    # All arguments check should be done with each constructors, not here
    @integer = integer
    @encoded = encoded
    @milliseconds = milliseconds
    @entropy = entropy
    freeze
  end

  # @return [String]
  def encode
    @encoded
  end
  alias_method(:to_s, :encode)

  # @return [Integer]
  def to_i
    @integer
  end

  # @return [Integer]
  def hash
    [ULID, @integer].hash
  end

  # @return [-1, 0, 1, nil]
  def <=>(other)
    (ULID === other) ? (@integer <=> other.to_i) : nil
  end

  # @return [String]
  def inspect
    "ULID(#{to_time.strftime(TIME_FORMAT_IN_INSPECT)}: #{@encoded})"
  end

  # @return [Boolean]
  def eql?(other)
    equal?(other) || (ULID === other && @integer == other.to_i)
  end
  alias_method(:==, :eql?)

  # Return `true` for same value of ULID, variant formats of strings, same Time in ULID precision(msec).
  # Do not consider integer, octets and partial strings, then returns `false`.
  #
  # @return [Boolean]
  # @see .normalize
  # @see .floor
  def ===(other)
    case other
    when ULID
      @integer == other.to_i
    when String
      begin
        to_i == ULID.parse_variant_format(other).to_i
      rescue Exception
        false
      end
    when Time
      to_time == ULID.floor(other)
    else
      false
    end
  end

  # @return [Time]
  # @param [String, Integer, nil] in
  def to_time(in: 'UTC')
    Time.at(0, @milliseconds, :millisecond, in: { in: }.fetch(:in))
  end

  # @return [Array(Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)]
  def octets
    digits = @integer.digits(256)
    digits.fill(0, digits.size, OCTETS_LENGTH - digits.size).reverse
  end

  # @return [String]
  def timestamp
    @encoded.slice(0, TIMESTAMP_ENCODED_LENGTH) || raise(UnexpectedError)
  end

  # @return [String]
  def randomness
    @encoded.slice(TIMESTAMP_ENCODED_LENGTH, RANDOMNESS_ENCODED_LENGTH) || raise(UnexpectedError)
  end

  # @return [ULID, nil] when called on ULID as `7ZZZZZZZZZZZZZZZZZZZZZZZZZ`, returns `nil` instead of ULID
  def succ
    succ_int = @integer.succ
    if succ_int >= MAX_INTEGER
      if succ_int == MAX_INTEGER
        MAX
      else
        nil
      end
    else
      ULID.from_integer(succ_int)
    end
  end
  alias_method(:next, :succ)

  # @return [ULID, nil] when called on ULID as `00000000000000000000000000`, returns `nil` instead of ULID
  def pred
    pred_int = @integer.pred
    if pred_int <= 0
      if pred_int == 0
        MIN
      else
        nil
      end
    else
      ULID.from_integer(pred_int)
    end
  end

  # @return [Integer]
  def marshal_dump
    @integer
  end

  # @param [Integer] integer
  # @return [void]
  def marshal_load(integer)
    unmarshaled = ULID.from_integer(integer)
    initialize(
      integer: unmarshaled.to_i,
      milliseconds: unmarshaled.milliseconds,
      entropy: unmarshaled.entropy,
      encoded: unmarshaled.encoded
    )
  end

  # @return [self]
  def to_ulid
    self
  end

  # Generate a UUID-like string that does not set the version and variants field.
  # It means wrong in UUIDv4 spec, but reversible
  #
  # @return [String]
  def to_uuidish
    UUID::Fields.raw_from_octets(octets).to_s.freeze
  end

  # Generate a UUIDv4-like string that sets the version and variants field.
  # It may conform to the UUID specification, but it is irreversible with the source ULID and may conflict with some other ULIDs.
  # You can specify `force` keyword argument to turn off the irreversible check
  #
  # @raise [IrreversibleUUIDError] if the converted UUID cannot be reversible with the replacing above 2 fields
  # @see https://github.com/kachick/ruby-ulid/issues/76
  # @param [bool] force
  # @return [String]
  def to_uuidv4(force: false)
    v4 = UUID::Fields.forced_v4_from_octets(octets)
    unless force
      uuidish = UUID::Fields.raw_from_octets(octets)
      raise(IrreversibleUUIDError) unless uuidish == v4
    end

    v4.to_s.freeze
  end

  # @return [ULID]
  def dup
    super.freeze
  end

  # @return [ULID]
  def clone(freeze: true)
    raise(ArgumentError, 'unfreezing ULID is an unexpected operation') unless freeze == true

    super
  end

  MIN = parse('00000000000000000000000000')
  MAX = parse('7ZZZZZZZZZZZZZZZZZZZZZZZZZ')

  Ractor.make_shareable(MIN)
  Ractor.make_shareable(MAX)

  private_constant(:MIN, :MAX)
end

Class Method Details

.at(time) ⇒ ULID

Short hand of ‘ULID.generate(moment: time)`

Parameters:

  • time (Time)

Returns:

Raises:

  • (ArgumentError)


95
96
97
98
99
# File 'lib/ulid.rb', line 95

def self.at(time)
  raise(ArgumentError, 'ULID.at takes only `Time` instance') unless Time === time

  generate(moment: time)
end

.decode_time(string, in: 'UTC') ⇒ Time

Almost same as ‘ULID.parse(string).to_time` except directly returning Time instance without needless object creation

Parameters:

  • string (String, #to_str)
  • in (String, Integer, nil) (defaults to: 'UTC')

Returns:

  • (Time)

Raises:

  • (ParserError)

    if the given format is not correct for ULID specs



280
281
282
283
284
285
286
287
288
289
290
291
292
# File 'lib/ulid.rb', line 280

def self.decode_time(string, in: 'UTC')
  in_for_time_at = { in: }.fetch(:in)
  string = String.try_convert(string)
  raise(ArgumentError, 'ULID.decode_time takes only strings') unless string

  unless STRICT_PATTERN_WITH_CROCKFORD_BASE32_SUBSET.match?(string)
    raise(ParserError, "given `#{string}` does not match to `#{STRICT_PATTERN_WITH_CROCKFORD_BASE32_SUBSET.inspect}`")
  end

  timestamp = string.slice(0, TIMESTAMP_ENCODED_LENGTH).freeze || raise(UnexpectedError)

  Time.at(0, CrockfordBase32.decode(timestamp), :millisecond, in: in_for_time_at)
end

.encode(moment: Utils.current_milliseconds, entropy: Utils.reasonable_entropy) ⇒ String

Almost same as [.generate] except directly returning String without needless object creation

Parameters:

  • moment (Integer, Time) (defaults to: Utils.current_milliseconds)
  • entropy (Integer) (defaults to: Utils.reasonable_entropy)

Returns:

  • (String)


87
88
89
90
# File 'lib/ulid.rb', line 87

def self.encode(moment: Utils.current_milliseconds, entropy: Utils.reasonable_entropy)
  base32hex = Utils.encode_base32hex(milliseconds: Utils.milliseconds_from_moment(moment), entropy:)
  CrockfordBase32.from_base32hex(base32hex)
end

.floor(time) ⇒ Time

Parameters:

  • time (Time)

Returns:

  • (Time)

Raises:

  • (ArgumentError)


243
244
245
246
247
# File 'lib/ulid.rb', line 243

def self.floor(time)
  raise(ArgumentError, 'ULID.floor takes only `Time` instance') unless Time === time

  time.floor(3)
end

.from_integer(integer) ⇒ ULID

Parameters:

  • integer (Integer)

Returns:

Raises:

  • (OverflowError)

    if the given integer is larger than the ULID limit

  • (ArgumentError)

    if the given integer is negative number



180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
# File 'lib/ulid.rb', line 180

def self.from_integer(integer)
  raise(ArgumentError, 'ULID.from_integer takes only `Integer`') unless Integer === integer
  raise(OverflowError, "integer overflow: given #{integer}, max: #{MAX_INTEGER}") unless integer <= MAX_INTEGER
  raise(ArgumentError, "integer should not be negative: given: #{integer}") if integer.negative?

  base32hex = integer.to_s(32).rjust(ENCODED_LENGTH, '0')
  base32hex_timestamp = base32hex.slice(0, TIMESTAMP_ENCODED_LENGTH)
  base32hex_randomness = base32hex.slice(TIMESTAMP_ENCODED_LENGTH, RANDOMNESS_ENCODED_LENGTH)

  raise(UnexpectedError) unless base32hex_timestamp && base32hex_randomness

  milliseconds = Integer(base32hex_timestamp, 32, exception: true)
  entropy = Integer(base32hex_randomness, 32, exception: true)

  new(
    milliseconds:,
    entropy:,
    integer:,
    encoded: CrockfordBase32.from_base32hex(base32hex).freeze
  )
end

.from_uuidish(uuidish) ⇒ ULID

Parameters:

  • uuidish (String, #to_str)

Returns:

Raises:

  • (ParserError)

    if the given format is not correct for UUID`ish` format



347
348
349
# File 'lib/ulid.rb', line 347

def self.from_uuidish(uuidish)
  from_integer(UUID.parse_any_to_int(uuidish))
end

.from_uuidv4(uuid) ⇒ ULID

Parameters:

  • uuid (String, #to_str)

Returns:

Raises:

  • (ParserError)

    if the given format is not correct for UUIDv4 specs



354
355
356
# File 'lib/ulid.rb', line 354

def self.from_uuidv4(uuid)
  from_integer(UUID.parse_v4_to_int(uuid))
end

.generate(moment: Utils.current_milliseconds, entropy: Utils.reasonable_entropy) ⇒ ULID

Parameters:

  • moment (Integer, Time) (defaults to: Utils.current_milliseconds)
  • entropy (Integer) (defaults to: Utils.reasonable_entropy)

Returns:

Raises:

  • (OverflowError)

    if the given value is larger than the ULID limit

  • (ArgumentError)

    if the given milliseconds and/or entropy is negative number



71
72
73
74
75
76
77
78
79
80
# File 'lib/ulid.rb', line 71

def self.generate(moment: Utils.current_milliseconds, entropy: Utils.reasonable_entropy)
  milliseconds = Utils.milliseconds_from_moment(moment)
  base32hex = Utils.encode_base32hex(milliseconds:, entropy:)
  new(
    milliseconds:,
    entropy:,
    integer: Integer(base32hex, 32, exception: true),
    encoded: CrockfordBase32.from_base32hex(base32hex).freeze
  )
end

.max(moment = MAX_MILLISECONDS) ⇒ ULID

Parameters:

  • moment (Time, Integer) (defaults to: MAX_MILLISECONDS)

Returns:



109
110
111
# File 'lib/ulid.rb', line 109

def self.max(moment=MAX_MILLISECONDS)
  MAX_MILLISECONDS.equal?(moment) ? MAX : generate(moment:, entropy: MAX_ENTROPY)
end

.min(moment = 0) ⇒ ULID

Parameters:

  • moment (Time, Integer) (defaults to: 0)

Returns:



103
104
105
# File 'lib/ulid.rb', line 103

def self.min(moment=0)
  0.equal?(moment) ? MIN : generate(moment:, entropy: 0)
end

.normalize(string) ⇒ String

Parameters:

  • string (String, #to_str)

Returns:

  • (String)

Raises:

  • (ParserError)

    if the given format is not correct for ULID specs, even if ignored 'orthographical variants of the format`



297
298
299
300
301
302
303
# File 'lib/ulid.rb', line 297

def self.normalize(string)
  string = String.try_convert(string)
  raise(ArgumentError, 'ULID.normalize takes only strings') unless string

  # Ensure the ULID correctness, because CrockfordBase32 does not always mean to satisfy ULID format
  parse_variant_format(string).encode
end

.normalized?(string) ⇒ Boolean

Parameters:

  • string (String, #to_str)

Returns:

  • (Boolean)


307
308
309
310
311
312
313
# File 'lib/ulid.rb', line 307

def self.normalized?(string)
  normalized = normalize(string)
rescue Exception
  false
else
  normalized == string
end

.parse(string) ⇒ ULID

Parameters:

  • string (String, #to_str)

Returns:

Raises:

  • (ParserError)

    if the given format is not correct for ULID specs



252
253
254
255
256
257
258
259
260
261
# File 'lib/ulid.rb', line 252

def self.parse(string)
  string = String.try_convert(string)
  raise(ArgumentError, 'ULID.parse takes only strings') unless string

  unless STRICT_PATTERN_WITH_CROCKFORD_BASE32_SUBSET.match?(string)
    raise(ParserError, "given `#{string}` does not match to `#{STRICT_PATTERN_WITH_CROCKFORD_BASE32_SUBSET.inspect}`")
  end

  from_integer(CrockfordBase32.decode(string))
end

.parse_variant_format(string) ⇒ ULID

Parameters:

  • string (String, #to_str)

Returns:

Raises:

  • (ParserError)

    if the given format is not correct for ULID specs



266
267
268
269
270
271
272
# File 'lib/ulid.rb', line 266

def self.parse_variant_format(string)
  string = String.try_convert(string)
  raise(ArgumentError, 'ULID.parse_variant_format takes only strings') unless string

  normalized_in_crockford = CrockfordBase32.normalize(string)
  parse(normalized_in_crockford)
end

.range(period) ⇒ Range<ULID>

Parameters:

  • period (Range<Time>, Range<nil>, Range[ULID])

Returns:

Raises:

  • (ArgumentError)

    if the given period is not a 'Range`, `Range` or `Range`



205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
# File 'lib/ulid.rb', line 205

def self.range(period)
  raise(ArgumentError, 'ULID.range takes only `Range[Time]`, `Range[nil]` or `Range[ULID]`') unless Range === period

  begin_element, end_element, exclude_end = period.begin, period.end, period.exclude_end?

  begin_ulid = (
    case begin_element
    when Time
      min(begin_element)
    when nil
      MIN
    when self
      begin_element
    else
      raise(ArgumentError, "ULID.range takes only `Range[Time]`, `Range[nil]` or `Range[ULID]`, given: #{period.inspect}")
    end
  )

  end_ulid = (
    case end_element
    when Time
      exclude_end ? min(end_element) : max(end_element)
    when nil
      exclude_end = false
      # The end should be max and include end, because nil end means to cover endless ULIDs until the limit
      MAX
    when self
      end_element
    else
      raise(ArgumentError, "ULID.range takes only `Range[Time]`, `Range[nil]` or `Range[ULID]`, given: #{period.inspect}")
    end
  )

  Range.new(begin_ulid, end_ulid, exclude_end)
end

.sample(number, period: nil) ⇒ Array<ULID> .sample(period: nil) ⇒ ULID

Note:

Major difference of 'Array#sample` interface is below

  • Do not ensure the uniqueness

  • Do not take random generator for the arguments

  • Raising error instead of truncating elements for the given number

Overloads:

  • .sample(number, period: nil) ⇒ Array<ULID>

    Parameters:

    • number (Integer)

    Returns:

    Raises:

    • (ArgumentError)

      if the given number is lager than 'ULID spec limits` or `Possibilities of given period`, or given negative number

  • .sample(period: nil) ⇒ ULID

    Returns:

Parameters:

  • period (Range<Time>, Range<nil>, Range[ULID], nil) (defaults to: nil)


124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
# File 'lib/ulid.rb', line 124

def self.sample(number=nil, period: nil)
  int_generator = (
    if period
      ulid_range = range(period)
      min, max, exclude_end = ulid_range.begin.to_i, ulid_range.end.to_i, ulid_range.exclude_end?

      possibilities = (max - min) + (exclude_end ? 0 : 1)
      raise(ArgumentError, "given range `#{ulid_range.inspect}` does not have possibilities") unless possibilities.positive?

      -> {
        SecureRandom.random_number(possibilities) + min
      }
    else
      RANDOM_INTEGER_GENERATOR
    end
  )

  case number
  when nil
    from_integer(int_generator.call)
  when Integer
    if number > MAX_INTEGER || number.negative?
      raise(ArgumentError, "given number `#{number}` is larger than ULID limit `#{MAX_INTEGER}` or negative")
    end

    if period && possibilities && (number > possibilities)
      raise(ArgumentError, "given number `#{number}` is larger than given possibilities `#{possibilities}`")
    end

    Array.new(number) { from_integer(int_generator.call) }
  else
    raise(ArgumentError, 'accepts no argument or integer only')
  end
end

.scan(string) {|ulid| ... } ⇒ Enumerator

Parameters:

  • string (String, #to_str)

Yield Parameters:

Yield Returns:

  • (self)

Returns:

  • (Enumerator)

Raises:

  • (ArgumentError)


163
164
165
166
167
168
169
170
171
172
173
174
# File 'lib/ulid.rb', line 163

def self.scan(string)
  string = String.try_convert(string)
  raise(ArgumentError, 'ULID.scan takes only strings') unless string
  return to_enum(:scan, string) unless block_given?

  string.scan(SCANNING_PATTERN) do |matched|
    if String === matched
      yield(parse(matched))
    end
  end
  self
end

.try_convert(object) ⇒ ULID?

Parameters:

Returns:

Raises:

  • (TypeError)

    if 'object.to_ulid` did not return ULID instance



328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
# File 'lib/ulid.rb', line 328

def self.try_convert(object)
  begin
    converted = object.to_ulid
  rescue NoMethodError
    nil
  else
    if ULID === converted
      converted
    else
      object_class_name = Utils.safe_get_class_name(object)
      converted_class_name = Utils.safe_get_class_name(converted)
      raise(TypeError, "can't convert #{object_class_name} to ULID (#{object_class_name}#to_ulid gives #{converted_class_name})")
    end
  end
end

.valid_as_variant_format?(string) ⇒ Boolean

Parameters:

  • string (String, #to_str)

Returns:

  • (Boolean)


317
318
319
320
321
322
323
# File 'lib/ulid.rb', line 317

def self.valid_as_variant_format?(string)
  parse_variant_format(string)
rescue Exception
  false
else
  true
end

Instance Method Details

#<=>(other) ⇒ -1, ...

Returns:

  • (-1, 0, 1, nil)


392
393
394
# File 'lib/ulid.rb', line 392

def <=>(other)
  (ULID === other) ? (@integer <=> other.to_i) : nil
end

#===(other) ⇒ Boolean

Return ‘true` for same value of ULID, variant formats of strings, same Time in ULID precision(msec). Do not consider integer, octets and partial strings, then returns `false`.

Returns:

  • (Boolean)

See Also:



413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
# File 'lib/ulid.rb', line 413

def ===(other)
  case other
  when ULID
    @integer == other.to_i
  when String
    begin
      to_i == ULID.parse_variant_format(other).to_i
    rescue Exception
      false
    end
  when Time
    to_time == ULID.floor(other)
  else
    false
  end
end

#clone(freeze: true) ⇒ ULID

Returns:

Raises:

  • (ArgumentError)


535
536
537
538
539
# File 'lib/ulid.rb', line 535

def clone(freeze: true)
  raise(ArgumentError, 'unfreezing ULID is an unexpected operation') unless freeze == true

  super
end

#dupULID

Returns:



530
531
532
# File 'lib/ulid.rb', line 530

def dup
  super.freeze
end

#encodeString Also known as: to_s

Returns:

  • (String)


376
377
378
# File 'lib/ulid.rb', line 376

def encode
  @encoded
end

#eql?(other) ⇒ Boolean Also known as: ==

Returns:

  • (Boolean)


402
403
404
# File 'lib/ulid.rb', line 402

def eql?(other)
  equal?(other) || (ULID === other && @integer == other.to_i)
end

#hashInteger

Returns:

  • (Integer)


387
388
389
# File 'lib/ulid.rb', line 387

def hash
  [ULID, @integer].hash
end

#inspectString

Returns:

  • (String)


397
398
399
# File 'lib/ulid.rb', line 397

def inspect
  "ULID(#{to_time.strftime(TIME_FORMAT_IN_INSPECT)}: #{@encoded})"
end

#marshal_dumpInteger

Returns:

  • (Integer)


482
483
484
# File 'lib/ulid.rb', line 482

def marshal_dump
  @integer
end

#marshal_load(integer) ⇒ void

This method returns an undefined value.

Parameters:

  • integer (Integer)


488
489
490
491
492
493
494
495
496
# File 'lib/ulid.rb', line 488

def marshal_load(integer)
  unmarshaled = ULID.from_integer(integer)
  initialize(
    integer: unmarshaled.to_i,
    milliseconds: unmarshaled.milliseconds,
    entropy: unmarshaled.entropy,
    encoded: unmarshaled.encoded
  )
end

#octetsArray(Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)

Returns:

  • (Array(Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer))


437
438
439
440
# File 'lib/ulid.rb', line 437

def octets
  digits = @integer.digits(256)
  digits.fill(0, digits.size, OCTETS_LENGTH - digits.size).reverse
end

#predULID?

Returns when called on ULID as ‘00000000000000000000000000`, returns `nil` instead of ULID.

Returns:

  • (ULID, nil)

    when called on ULID as '00000000000000000000000000`, returns `nil` instead of ULID



468
469
470
471
472
473
474
475
476
477
478
479
# File 'lib/ulid.rb', line 468

def pred
  pred_int = @integer.pred
  if pred_int <= 0
    if pred_int == 0
      MIN
    else
      nil
    end
  else
    ULID.from_integer(pred_int)
  end
end

#randomnessString

Returns:

  • (String)


448
449
450
# File 'lib/ulid.rb', line 448

def randomness
  @encoded.slice(TIMESTAMP_ENCODED_LENGTH, RANDOMNESS_ENCODED_LENGTH) || raise(UnexpectedError)
end

#succULID? Also known as: next

Returns when called on ULID as ‘7ZZZZZZZZZZZZZZZZZZZZZZZZZ`, returns `nil` instead of ULID.

Returns:

  • (ULID, nil)

    when called on ULID as '7ZZZZZZZZZZZZZZZZZZZZZZZZZ`, returns `nil` instead of ULID



453
454
455
456
457
458
459
460
461
462
463
464
# File 'lib/ulid.rb', line 453

def succ
  succ_int = @integer.succ
  if succ_int >= MAX_INTEGER
    if succ_int == MAX_INTEGER
      MAX
    else
      nil
    end
  else
    ULID.from_integer(succ_int)
  end
end

#timestampString

Returns:

  • (String)


443
444
445
# File 'lib/ulid.rb', line 443

def timestamp
  @encoded.slice(0, TIMESTAMP_ENCODED_LENGTH) || raise(UnexpectedError)
end

#to_iInteger

Returns:

  • (Integer)


382
383
384
# File 'lib/ulid.rb', line 382

def to_i
  @integer
end

#to_time(in: 'UTC') ⇒ Time

Parameters:

  • in (String, Integer, nil) (defaults to: 'UTC')

Returns:

  • (Time)


432
433
434
# File 'lib/ulid.rb', line 432

def to_time(in: 'UTC')
  Time.at(0, @milliseconds, :millisecond, in: { in: }.fetch(:in))
end

#to_ulidself

Returns:

  • (self)


499
500
501
# File 'lib/ulid.rb', line 499

def to_ulid
  self
end

#to_uuidishString

Generate a UUID-like string that does not set the version and variants field. It means wrong in UUIDv4 spec, but reversible

Returns:

  • (String)


507
508
509
# File 'lib/ulid.rb', line 507

def to_uuidish
  UUID::Fields.raw_from_octets(octets).to_s.freeze
end

#to_uuidv4(force: false) ⇒ String

Generate a UUIDv4-like string that sets the version and variants field. It may conform to the UUID specification, but it is irreversible with the source ULID and may conflict with some other ULIDs. You can specify ‘force` keyword argument to turn off the irreversible check

Parameters:

  • force (bool) (defaults to: false)

Returns:

  • (String)

Raises:

  • (IrreversibleUUIDError)

    if the converted UUID cannot be reversible with the replacing above 2 fields

See Also:



519
520
521
522
523
524
525
526
527
# File 'lib/ulid.rb', line 519

def to_uuidv4(force: false)
  v4 = UUID::Fields.forced_v4_from_octets(octets)
  unless force
    uuidish = UUID::Fields.raw_from_octets(octets)
    raise(IrreversibleUUIDError) unless uuidish == v4
  end

  v4.to_s.freeze
end