Sha256: 53b82966c398318e03ff7697d2c549ca865ac126ade69a760bca1ca3e70e896f

Contents?: true

Size: 1015 Bytes

Versions: 3

Compression:

Stored size: 1015 Bytes

Contents

# frozen_string_literal: true

module ActiveUxid
  class Hash < ActiveUxid::Base

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

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

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

    def encode_uxid
      uxid_encode_chars((@id + encoding_salt) << encoding_length)
    end

    def decode_uxid
      (uxid_decode_chars(@id) >> encoding_length) - encoding_salt
    end

    def uxid_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 uxid_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

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
active_uxid-5.0.1 lib/active_uxid/hash.rb
active_uxid-5.0.0 lib/active_uxid/hash.rb
active_uxid-1.0.13 lib/active_uxid/hash.rb