Sha256: 69f858b288869b4c178e49645564d650baa7f60367c8bcc30e36caca63e11a66

Contents?: true

Size: 875 Bytes

Versions: 3

Compression:

Stored size: 875 Bytes

Contents

# frozen_string_literal: true

require 'securerandom'

module Lite
  module Uxid
    class Ulid < Lite::Uxid::Base

      class << self

        def encode
          klass = new
          klass.uxid_encode
        end

      end

      def uxid_encode
        (1..encoding_length).reduce('') do |str, num|
          shift = 128 - 5 * num
          "#{str}#{encoding_chars[(uxid_octect >> shift) & 0x1f]}"
        end
      end

      def uxid_bytes
        "#{uxid_unixtime_48bit}#{SecureRandom.random_bytes(10)}"
      end

      def uxid_octect
        (hi, lo) = uxid_bytes.unpack('Q>Q>')
        (hi << 64) | lo
      end

      def uxid_unixtime_flex
        time = Time.respond_to?(:current) ? Time.current : Time.now
        (time.to_f * 10_000).to_i
      end

      def uxid_unixtime_48bit
        [uxid_unixtime_flex].pack('Q>')[2..-1]
      end

    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
lite-uxid-1.0.2 lib/lite/uxid/ulid.rb
lite-uxid-1.0.1 lib/lite/uxid/ulid.rb
lite-uxid-1.0.0 lib/lite/uxid/ulid.rb