Class: ULID
- Inherits:
-
Object
- Object
- ULID
- 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.9.0'
Instance Attribute Summary collapse
- #entropy ⇒ Integer readonly
- #milliseconds ⇒ Integer readonly
Class Method Summary collapse
-
.at(time) ⇒ ULID
Short hand of ‘ULID.generate(moment: time)`.
-
.decode_time(string, in: 'UTC') ⇒ Time
Almost same as ‘ULID.parse(string).to_time` except directly returning Time instance without needless object creation.
-
.encode(moment: Utils.current_milliseconds, entropy: Utils.reasonable_entropy) ⇒ String
Almost same as [.generate] except directly returning String without needless object creation.
- .floor(time) ⇒ Time
- .from_integer(integer) ⇒ ULID
- .from_uuid_v4(uuid) ⇒ ULID
- .from_uuid_v7(uuid) ⇒ ULID
- .from_uuidish(uuidish) ⇒ ULID
- .generate(moment: Utils.current_milliseconds, entropy: Utils.reasonable_entropy) ⇒ ULID
- .max(moment = MAX_MILLISECONDS) ⇒ ULID
- .min(moment = 0) ⇒ ULID
- .normalize(string) ⇒ String
- .normalized?(string) ⇒ Boolean
- .parse(string) ⇒ ULID
- .parse_variant_format(string) ⇒ ULID
- .range(period) ⇒ Range<ULID>
- .sample(number = nil, period: nil) ⇒ Object
- .scan(string) {|ulid| ... } ⇒ Enumerator
- .try_convert(object) ⇒ ULID?
- .valid_as_variant_format?(string) ⇒ Boolean
Instance Method Summary collapse
-
#+(other) ⇒ ULID?
When returning URID might be greater than ‘7ZZZZZZZZZZZZZZZZZZZZZZZZZ`, returns `nil` instead of ULID.
-
#-(other) ⇒ ULID?
When returning URID might be less than ‘00000000000000000000000000`, returns `nil` instead of ULID.
- #<=>(other) ⇒ -1, ...
-
#===(other) ⇒ Boolean
Return ‘true` for same value of ULID, variant formats of strings, same Time in ULID precision(msec).
- #clone(freeze: true) ⇒ ULID
- #dup ⇒ ULID
- #encode ⇒ String (also: #to_s)
- #eql?(other) ⇒ Boolean (also: #==)
- #hash ⇒ Integer
- #initialize(milliseconds:, entropy:, integer:, encoded:) ⇒ void constructor
- #inspect ⇒ String
- #marshal_dump ⇒ Integer
- #marshal_load(integer) ⇒ void
- #octets ⇒ Array(Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)
-
#pred ⇒ ULID?
When called on ULID as ‘00000000000000000000000000`, returns `nil` instead of ULID.
- #randomness ⇒ String
-
#succ ⇒ ULID?
(also: #next)
When called on ULID as ‘7ZZZZZZZZZZZZZZZZZZZZZZZZZ`, returns `nil` instead of ULID.
- #timestamp ⇒ String
- #to_i ⇒ Integer
- #to_time(in: 'UTC') ⇒ Time
- #to_ulid ⇒ self
-
#to_uuid_v4(force: false) ⇒ String
Generate a UUIDv4-like string that sets the version and variants field.
- #to_uuid_v7(force: false) ⇒ String
-
#to_uuidish ⇒ String
Generate a UUID-like string that does not touch the version and variants field.
Constructor Details
#initialize(milliseconds:, entropy:, integer:, encoded:) ⇒ void
373 374 375 376 377 378 379 380 |
# File 'lib/ulid.rb', line 373 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
#entropy ⇒ Integer (readonly)
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 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 |
# 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.slice(0, TIMESTAMP_ENCODED_LENGTH) base32hex_randomness = base32hex.slice(TIMESTAMP_ENCODED_LENGTH, RANDOMNESS_ENCODED_LENGTH) raise(UnexpectedError) unless && base32hex_randomness milliseconds = Integer(, 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 = string.slice(0, TIMESTAMP_ENCODED_LENGTH).freeze || raise(UnexpectedError) Time.at(0, CrockfordBase32.decode(), :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_uuid_v4(uuid) from_integer(UUID.parse_v4_to_int(uuid)) end # @param [String, #to_str] uuid # @return [ULID] # @raise [ParserError] if the given format is not correct for UUIDv4 specs def self.from_uuid_v7(uuid) from_integer(UUID.parse_v7_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 @encoded.slice(0, TIMESTAMP_ENCODED_LENGTH) || raise(UnexpectedError) end # @return [String] def randomness @encoded.slice(TIMESTAMP_ENCODED_LENGTH, RANDOMNESS_ENCODED_LENGTH) || raise(UnexpectedError) end # @param [Integer] other # @return [ULID, nil] when returning URID might be greater than `7ZZZZZZZZZZZZZZZZZZZZZZZZZ`, returns `nil` instead of ULID def +(other) raise(ArgumentError, 'ULID#+ takes only integers') unless Integer === other new_int = @integer + other case new_int when MAX_INTEGER MAX when 0 MIN else if new_int > MAX_INTEGER || new_int < 0 nil else ULID.from_integer(new_int) end end end # @param [Integer] other # @return [ULID, nil] when returning URID might be less than `00000000000000000000000000`, returns `nil` instead of ULID def -(other) raise(ArgumentError, 'ULID#- takes only integers') unless Integer === other self + -other end # @return [ULID, nil] when called on ULID as `7ZZZZZZZZZZZZZZZZZZZZZZZZZ`, returns `nil` instead of ULID def succ self + 1 end alias_method(:next, :succ) # @return [ULID, nil] when called on ULID as `00000000000000000000000000`, returns `nil` instead of ULID def pred self - 1 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 touch the version and variants field. # It means basically wrong in UUID specs, 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_uuid_v4(force: false) v4 = UUID::Fields.forced_version_from_octets(octets, mask: 0x4000) unless force uuidish = UUID::Fields.raw_from_octets(octets) raise(IrreversibleUUIDError) unless uuidish == v4 end v4.to_s.freeze end # @see [#to_uuid_v4] and https://datatracker.ietf.org/doc/rfc9562/ # @param [bool] force # @return [String] def to_uuid_v7(force: false) v7 = UUID::Fields.forced_version_from_octets(octets, mask: 0x7000) unless force uuidish = UUID::Fields.raw_from_octets(octets) raise(IrreversibleUUIDError) unless uuidish == v7 end v7.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 |
#milliseconds ⇒ Integer (readonly)
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 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 |
# 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.slice(0, TIMESTAMP_ENCODED_LENGTH) base32hex_randomness = base32hex.slice(TIMESTAMP_ENCODED_LENGTH, RANDOMNESS_ENCODED_LENGTH) raise(UnexpectedError) unless && base32hex_randomness milliseconds = Integer(, 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 = string.slice(0, TIMESTAMP_ENCODED_LENGTH).freeze || raise(UnexpectedError) Time.at(0, CrockfordBase32.decode(), :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_uuid_v4(uuid) from_integer(UUID.parse_v4_to_int(uuid)) end # @param [String, #to_str] uuid # @return [ULID] # @raise [ParserError] if the given format is not correct for UUIDv4 specs def self.from_uuid_v7(uuid) from_integer(UUID.parse_v7_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 @encoded.slice(0, TIMESTAMP_ENCODED_LENGTH) || raise(UnexpectedError) end # @return [String] def randomness @encoded.slice(TIMESTAMP_ENCODED_LENGTH, RANDOMNESS_ENCODED_LENGTH) || raise(UnexpectedError) end # @param [Integer] other # @return [ULID, nil] when returning URID might be greater than `7ZZZZZZZZZZZZZZZZZZZZZZZZZ`, returns `nil` instead of ULID def +(other) raise(ArgumentError, 'ULID#+ takes only integers') unless Integer === other new_int = @integer + other case new_int when MAX_INTEGER MAX when 0 MIN else if new_int > MAX_INTEGER || new_int < 0 nil else ULID.from_integer(new_int) end end end # @param [Integer] other # @return [ULID, nil] when returning URID might be less than `00000000000000000000000000`, returns `nil` instead of ULID def -(other) raise(ArgumentError, 'ULID#- takes only integers') unless Integer === other self + -other end # @return [ULID, nil] when called on ULID as `7ZZZZZZZZZZZZZZZZZZZZZZZZZ`, returns `nil` instead of ULID def succ self + 1 end alias_method(:next, :succ) # @return [ULID, nil] when called on ULID as `00000000000000000000000000`, returns `nil` instead of ULID def pred self - 1 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 touch the version and variants field. # It means basically wrong in UUID specs, 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_uuid_v4(force: false) v4 = UUID::Fields.forced_version_from_octets(octets, mask: 0x4000) unless force uuidish = UUID::Fields.raw_from_octets(octets) raise(IrreversibleUUIDError) unless uuidish == v4 end v4.to_s.freeze end # @see [#to_uuid_v4] and https://datatracker.ietf.org/doc/rfc9562/ # @param [bool] force # @return [String] def to_uuid_v7(force: false) v7 = UUID::Fields.forced_version_from_octets(octets, mask: 0x7000) unless force uuidish = UUID::Fields.raw_from_octets(octets) raise(IrreversibleUUIDError) unless uuidish == v7 end v7.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)`
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
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 = string.slice(0, TIMESTAMP_ENCODED_LENGTH).freeze || raise(UnexpectedError) Time.at(0, CrockfordBase32.decode(), :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
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
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
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.slice(0, TIMESTAMP_ENCODED_LENGTH) base32hex_randomness = base32hex.slice(TIMESTAMP_ENCODED_LENGTH, RANDOMNESS_ENCODED_LENGTH) raise(UnexpectedError) unless && base32hex_randomness milliseconds = Integer(, 32, exception: true) entropy = Integer(base32hex_randomness, 32, exception: true) new( milliseconds:, entropy:, integer:, encoded: CrockfordBase32.from_base32hex(base32hex).freeze ) end |
.from_uuid_v4(uuid) ⇒ ULID
354 355 356 |
# File 'lib/ulid.rb', line 354 def self.from_uuid_v4(uuid) from_integer(UUID.parse_v4_to_int(uuid)) end |
.from_uuid_v7(uuid) ⇒ ULID
361 362 363 |
# File 'lib/ulid.rb', line 361 def self.from_uuid_v7(uuid) from_integer(UUID.parse_v7_to_int(uuid)) end |
.from_uuidish(uuidish) ⇒ ULID
347 348 349 |
# File 'lib/ulid.rb', line 347 def self.from_uuidish(uuidish) from_integer(UUID.parse_any_to_int(uuidish)) end |
.generate(moment: Utils.current_milliseconds, entropy: Utils.reasonable_entropy) ⇒ ULID
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
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
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
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
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
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
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>
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
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
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
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?
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
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) ⇒ ULID?
Returns when returning URID might be greater than ‘7ZZZZZZZZZZZZZZZZZZZZZZZZZ`, returns `nil` instead of ULID.
461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 |
# File 'lib/ulid.rb', line 461 def +(other) raise(ArgumentError, 'ULID#+ takes only integers') unless Integer === other new_int = @integer + other case new_int when MAX_INTEGER MAX when 0 MIN else if new_int > MAX_INTEGER || new_int < 0 nil else ULID.from_integer(new_int) end end end |
#-(other) ⇒ ULID?
Returns when returning URID might be less than ‘00000000000000000000000000`, returns `nil` instead of ULID.
481 482 483 484 485 |
# File 'lib/ulid.rb', line 481 def -(other) raise(ArgumentError, 'ULID#- takes only integers') unless Integer === other self + -other end |
#<=>(other) ⇒ -1, ...
399 400 401 |
# File 'lib/ulid.rb', line 399 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`.
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 |
# File 'lib/ulid.rb', line 420 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
565 566 567 568 569 |
# File 'lib/ulid.rb', line 565 def clone(freeze: true) raise(ArgumentError, 'unfreezing ULID is an unexpected operation') unless freeze == true super end |
#encode ⇒ String Also known as: to_s
383 384 385 |
# File 'lib/ulid.rb', line 383 def encode @encoded end |
#eql?(other) ⇒ Boolean Also known as: ==
409 410 411 |
# File 'lib/ulid.rb', line 409 def eql?(other) equal?(other) || (ULID === other && @integer == other.to_i) end |
#inspect ⇒ String
404 405 406 |
# File 'lib/ulid.rb', line 404 def inspect "ULID(#{to_time.strftime(TIME_FORMAT_IN_INSPECT)}: #{@encoded})" end |
#marshal_dump ⇒ Integer
499 500 501 |
# File 'lib/ulid.rb', line 499 def marshal_dump @integer end |
#marshal_load(integer) ⇒ void
This method returns an undefined value.
505 506 507 508 509 510 511 512 513 |
# File 'lib/ulid.rb', line 505 def marshal_load(integer) unmarshaled = ULID.from_integer(integer) initialize( integer: unmarshaled.to_i, milliseconds: unmarshaled.milliseconds, entropy: unmarshaled.entropy, encoded: unmarshaled.encoded ) end |
#octets ⇒ Array(Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer, Integer)
444 445 446 447 |
# File 'lib/ulid.rb', line 444 def octets digits = @integer.digits(256) digits.fill(0, digits.size, OCTETS_LENGTH - digits.size).reverse end |
#pred ⇒ ULID?
Returns when called on ULID as ‘00000000000000000000000000`, returns `nil` instead of ULID.
494 495 496 |
# File 'lib/ulid.rb', line 494 def pred self - 1 end |
#randomness ⇒ String
455 456 457 |
# File 'lib/ulid.rb', line 455 def randomness @encoded.slice(TIMESTAMP_ENCODED_LENGTH, RANDOMNESS_ENCODED_LENGTH) || raise(UnexpectedError) end |
#succ ⇒ ULID? Also known as: next
Returns when called on ULID as ‘7ZZZZZZZZZZZZZZZZZZZZZZZZZ`, returns `nil` instead of ULID.
488 489 490 |
# File 'lib/ulid.rb', line 488 def succ self + 1 end |
#timestamp ⇒ String
450 451 452 |
# File 'lib/ulid.rb', line 450 def @encoded.slice(0, TIMESTAMP_ENCODED_LENGTH) || raise(UnexpectedError) end |
#to_i ⇒ Integer
389 390 391 |
# File 'lib/ulid.rb', line 389 def to_i @integer end |
#to_time(in: 'UTC') ⇒ Time
439 440 441 |
# File 'lib/ulid.rb', line 439 def to_time(in: 'UTC') Time.at(0, @milliseconds, :millisecond, in: { in: }.fetch(:in)) end |
#to_ulid ⇒ self
516 517 518 |
# File 'lib/ulid.rb', line 516 def to_ulid self end |
#to_uuid_v4(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
536 537 538 539 540 541 542 543 544 |
# File 'lib/ulid.rb', line 536 def to_uuid_v4(force: false) v4 = UUID::Fields.forced_version_from_octets(octets, mask: 0x4000) unless force uuidish = UUID::Fields.raw_from_octets(octets) raise(IrreversibleUUIDError) unless uuidish == v4 end v4.to_s.freeze end |
#to_uuid_v7(force: false) ⇒ String
549 550 551 552 553 554 555 556 557 |
# File 'lib/ulid.rb', line 549 def to_uuid_v7(force: false) v7 = UUID::Fields.forced_version_from_octets(octets, mask: 0x7000) unless force uuidish = UUID::Fields.raw_from_octets(octets) raise(IrreversibleUUIDError) unless uuidish == v7 end v7.to_s.freeze end |
#to_uuidish ⇒ String
Generate a UUID-like string that does not touch the version and variants field. It means basically wrong in UUID specs, but reversible
524 525 526 |
# File 'lib/ulid.rb', line 524 def to_uuidish UUID::Fields.raw_from_octets(octets).to_s.freeze end |