module SourceMap::VLQ

def self.decode(str)

Returns an Array of Integers.

str - VLQ encoded String

Public: Decode a VLQ string.
def self.decode(str)
  result = []
  chars = str.split('')
  while chars.any?
    vlq = 0
    shift = 0
    continuation = true
    while continuation
      char = chars.shift
      raise ArgumentError unless char
      digit = BASE64_VALUES[char]
      continuation = false if (digit & VLQ_CONTINUATION_BIT) == 0
      digit &= VLQ_BASE_MASK
      vlq   += digit << shift
      shift += VLQ_BASE_SHIFT
    end
    result << (vlq & 1 == 1 ? -(vlq >> 1) : vlq >> 1)
  end
  result
end

def self.decode_mappings(str)

Returns an two dimensional Array of Integers.

str - VLQ encoded String

Public: Decode a VLQ string into mapping numbers.
def self.decode_mappings(str)
  mappings = []
  str.split(';').each_with_index do |group, index|
    mappings[index] = []
    group.split(',').each do |segment|
      mappings[index] << decode(segment)
    end
  end
  mappings
end

def self.encode(ary)

Returns a VLQ String.

ary - An Array of Integers

Public: Encode a list of numbers into a compact VLQ string.
def self.encode(ary)
  result = []
  ary.each do |n|
    vlq = n < 0 ? ((-n) << 1) + 1 : n << 1
    loop do
      digit  = vlq & VLQ_BASE_MASK
      vlq  >>= VLQ_BASE_SHIFT
      digit |= VLQ_CONTINUATION_BIT if vlq > 0
      result << BASE64_DIGITS[digit]
      break unless vlq > 0
    end
  end
  result.join
end

def self.encode_mappings(ary)

Returns a VLQ encoded String seperated by , and ;.

ary - Two dimensional Array of Integers.

Public: Encode a mapping array into a compact VLQ string.
def self.encode_mappings(ary)
  ary.map { |group|
    group.map { |segment|
      encode(segment)
    }.join(',')
  }.join(';')
end