Module: Dhall::Util

Defined in:
lib/dhall/util.rb

Defined Under Namespace

Modules: ArrayAllTheSame Classes: AllOf, ArrayOf, Deadline, HashOf, NoDeadline, Not

Class Method Summary collapse

Class Method Details

.longest_common_prefix(a, b) ⇒ Object



181
182
183
# File 'lib/dhall/util.rb', line 181

def self.longest_common_prefix(a, b)
  a.zip(b).take_while { |(x, y)| x == y }.map(&:first)
end

.match_result_promises(xs = nil, ys = nil) ⇒ Object



112
113
114
115
116
# File 'lib/dhall/util.rb', line 112

def self.match_result_promises(xs=nil, ys=nil)
  match_results(yield(Array(xs)), ys) do |promise, promises|
    promises.each { |p| p.fulfill(promise) }
  end
end

.match_results(xs = nil, ys = nil) ⇒ Object



106
107
108
109
110
# File 'lib/dhall/util.rb', line 106

def self.match_results(xs=nil, ys=nil)
  Array(xs).each_with_index.map do |r, idx|
    yield r, ys[idx]
  end
end

.promise_all_hash(hash) ⇒ Object



118
119
120
121
122
123
124
125
126
127
128
# File 'lib/dhall/util.rb', line 118

def self.promise_all_hash(hash)
  keys, promises = hash.to_a.transpose

  return Promise.resolve(hash) unless keys

  Promise.all(promises).then do |values|
    Hash[Util.match_results(keys, values) do |k, v|
      [k, v]
    end]
  end
end

.psych_coder_for(tag, v) ⇒ Object



130
131
132
133
134
135
136
137
138
139
140
# File 'lib/dhall/util.rb', line 130

def self.psych_coder_for(tag, v)
  c = Psych::Coder.new(tag)
  case v
  when Hash
    c.map = v
  when Array
    c.seq = v
  else
    c.scalar = v
  end
end

.psych_coder_from(tag, o) ⇒ Object



142
143
144
145
146
147
148
149
150
151
152
153
154
# File 'lib/dhall/util.rb', line 142

def self.psych_coder_from(tag, o)
  coder = Psych::Coder.new(tag)

  if o.respond_to?(:encode_with)
    o.encode_with(coder)
  else
    o.instance_variables.each do |ivar|
      coder[ivar.to_s[1..-1]] = o.instance_variable_get(ivar)
    end
  end

  coder
end

.text_or_binary(str) ⇒ Object



167
168
169
170
171
172
173
174
175
176
177
178
179
# File 'lib/dhall/util.rb', line 167

def self.text_or_binary(str)
  unless str.valid_encoding?
    raise ArgumentError, "invalid byte sequence in #{str.encoding}"
  end

  if str.encoding == Encoding::BINARY
    return str if str =~ /(?!\s)[[:cntrl:]]/

    utf8_if_possible(str)
  else
    str.encode(Encoding::UTF_8)
  end
end

.transform_keys(hash_or_not) ⇒ Object



156
157
158
159
160
# File 'lib/dhall/util.rb', line 156

def self.transform_keys(hash_or_not)
  return hash_or_not unless hash_or_not.is_a?(Hash)

  Hash[hash_or_not.map { |k, v| [(yield k), v] }]
end

.utf8_if_possible(str) ⇒ Object



162
163
164
165
# File 'lib/dhall/util.rb', line 162

def self.utf8_if_possible(str)
  utf8 = str.dup.force_encoding(Encoding::UTF_8)
  utf8.valid_encoding? ? utf8 : str
end