Module: SourceMap::VLQ

Defined in:
opal/stdlib/source_map/vlq.rb

Overview

Constant Summary

VLQ_BASE_SHIFT =
5
VLQ_BASE =
1 << VLQ_BASE_SHIFT
VLQ_BASE_MASK =
VLQ_BASE - 1
VLQ_CONTINUATION_BIT =
VLQ_BASE
BASE64_DIGITS =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('')
BASE64_VALUES =
(0...64).inject({}) { |h, i| h[BASE64_DIGITS[i]] = i; h }

Class Method Summary collapse

Class Method Details

.decode(str) ⇒ Object

Public: Decode a VLQ string.

str - VLQ encoded String

Returns an Array of Integers.



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'opal/stdlib/source_map/vlq.rb', line 47

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

.decode_mappings(str) ⇒ Object

Public: Decode a VLQ string into mapping numbers.

str - VLQ encoded String

Returns an two dimensional Array of Integers.



86
87
88
89
90
91
92
93
94
95
96
97
# File 'opal/stdlib/source_map/vlq.rb', line 86

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

.encode(ary) ⇒ Object

Public: Encode a list of numbers into a compact VLQ string.

ary - An Array of Integers

Returns a VLQ String.



27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'opal/stdlib/source_map/vlq.rb', line 27

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

.encode_mappings(ary) ⇒ Object

Public: Encode a mapping array into a compact VLQ string.

ary - Two dimensional Array of Integers.

Returns a VLQ encoded String seperated by , and ;.



73
74
75
76
77
78
79
# File 'opal/stdlib/source_map/vlq.rb', line 73

def self.encode_mappings(ary)
  ary.map { |group|
    group.map { |segment|
      encode(segment)
    }.join(',')
  }.join(';')
end