Sha256: 1d7317643d86927c834ca49ea5bf4bd69d14edfdcedaff381799f1dc1805f294

Contents?: true

Size: 1.1 KB

Versions: 6

Compression:

Stored size: 1.1 KB

Contents

# frozen_string_literal: true

module Lite
  module Uxid
    class Hashid < Lite::Uxid::Base

      def initialize(id)
        @id = id
        super()
      end

      class << self

        def encode(id)
          klass = new(id)
          klass.encode
        end

        def decode(id)
          klass = new(id)
          klass.decode
        end

      end

      def encode
        encode_chars((@id + encoding_salt) << encoding_length)
      end

      def decode
        (decode_chars(@id) >> encoding_length) - encoding_salt
      end

      private

      def encode_chars(id)
        return '0' if id.zero?
        return nil if id.negative?

        str = ''

        while id.positive?
          str = "#{encoding_chars[id % encoding_base]}#{str}"
          id /= encoding_base
        end

        str
      end

      def decode_chars(id)
        pos = 0
        num = 0
        len = id.length
        max = len - 1

        while pos < len
          pow = encoding_base**(max - pos)
          num += encoding_chars.index(id[pos]) * pow
          pos += 1
        end

        num
      end

    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
lite-uxid-1.1.3 lib/lite/uxid/hashid.rb
lite-uxid-1.1.2 lib/lite/uxid/hashid.rb
lite-uxid-1.1.1 lib/lite/uxid/hashid.rb
lite-uxid-1.1.0 lib/lite/uxid/hashid.rb
lite-uxid-1.0.8 lib/lite/uxid/hashid.rb
lite-uxid-1.0.7 lib/lite/uxid/hashid.rb