Module: Flexr::Automaton::Accel

Defined in:
lib/flexr/automaton/accel.rb

Class Method Summary collapse

Class Method Details

.bytes_to_source(bytes) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/flexr/automaton/accel.rb', line 29

def bytes_to_source(bytes)
  ranges = []
  bytes.sort.each do |byte|
    if ranges.empty? || byte > ranges.last.last + 1
      ranges << [byte, byte]
    else
      ranges.last[1] = byte
    end
  end
  ranges.map do |lo, hi|
    lo == hi ? format("\\x%<byte>02X", byte: lo) : format("\\x%<lo>02X-\\x%<hi>02X", lo: lo, hi: hi)
  end.join
end

.extract(dfa) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/flexr/automaton/accel.rb', line 10

def extract(dfa)
  dfa.transitions.each_index.filter_map do |state|
    bytes = Analysis.self_loop_set(dfa, state)
    next if bytes.empty?

    Region.new(
      state: state, bytes: bytes.freeze,
      regexp: regexp_for(bytes, binary: true),
      utf8_regexp: bytes.all? { |byte| byte < 128 } ? regexp_for(bytes, binary: false) : nil
    )
  end
end

.regexp_for(bytes, binary: true) ⇒ Object



23
24
25
26
27
# File 'lib/flexr/automaton/accel.rb', line 23

def regexp_for(bytes, binary: true)
  source = bytes_to_source(bytes)
  options = binary ? ::Regexp::NOENCODING : 0
  ::Regexp.new("(?:[#{source}])+", options)
end