Allocate match_data once

This commit is contained in:
Roberto Alsina 2024-08-15 17:04:16 -03:00
parent 4612db58fe
commit 115debdec6

View File

@ -22,14 +22,15 @@ module BytesRegex
end end
raise Exception.new "Error #{msg} compiling regex at offset #{erroroffset}" raise Exception.new "Error #{msg} compiling regex at offset #{erroroffset}"
end end
@match_data = LibPCRE2.match_data_create_from_pattern(@re, nil)
end end
def finalize def finalize
LibPCRE2.match_data_free(@match_data)
LibPCRE2.code_free(@re) LibPCRE2.code_free(@re)
end end
def match(str : Bytes, pos = 0) : Array(Match) def match(str : Bytes, pos = 0) : Array(Match)
match_data = LibPCRE2.match_data_create_from_pattern(@re, nil)
match = [] of Match match = [] of Match
rc = LibPCRE2.match( rc = LibPCRE2.match(
@re, @re,
@ -37,12 +38,12 @@ module BytesRegex
str.size, str.size,
pos, pos,
LibPCRE2::NO_UTF_CHECK, LibPCRE2::NO_UTF_CHECK,
match_data, @match_data,
nil) nil)
if rc < 0 if rc < 0
# No match, do nothing # No match, do nothing
else else
ovector = LibPCRE2.get_ovector_pointer(match_data) ovector = LibPCRE2.get_ovector_pointer(@match_data)
(0...rc).each do |i| (0...rc).each do |i|
m_start = ovector[2 * i] m_start = ovector[2 * i]
m_size = ovector[2 * i + 1] - m_start m_size = ovector[2 * i + 1] - m_start
@ -54,7 +55,6 @@ module BytesRegex
match << Match.new(m_value, m_start, m_size) match << Match.new(m_value, m_start, m_size)
end end
end end
LibPCRE2.match_data_free(match_data)
match match
end end
end end