Sha256: 39e7ddb05d0b0f08efa7c670b222bdf801ee8067a24a74f51bbc9a0e65c1283d

Contents?: true

Size: 997 Bytes

Versions: 3

Compression:

Stored size: 997 Bytes

Contents

# frozen_string_literal: true

module Lite
  module Uxid
    class Hashid < Base::Reversible

      def encode
        uxid = encode_chars((id + coder_salt) << coder_size)
        "#{coder_prefix}#{uxid}"
      end

      def decode
        uxid = id.delete_prefix(coder_prefix.to_s)
        (decode_chars(uxid) >> coder_size) - coder_salt
      end

      private

      def encode_chars(decoded_id)
        return "0" if decoded_id.zero?
        return nil if decoded_id.negative?

        str = ""

        while decoded_id.positive?
          str = "#{coder_charset[decoded_id % coder_length]}#{str}"
          decoded_id /= coder_length
        end

        str
      end

      def decode_chars(encoded_id)
        pos = 0
        num = 0
        len = encoded_id.size
        max = len - 1

        while pos < len
          pow = coder_length**(max - pos)
          num += coder_charset.index(encoded_id[pos]) * pow
          pos += 1
        end

        num
      end

    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
lite-uxid-1.5.2 lib/lite/uxid/hashid.rb
lite-uxid-1.5.1 lib/lite/uxid/hashid.rb
lite-uxid-1.5.0 lib/lite/uxid/hashid.rb