Avoid infinity loop when empty string pattern
MODIFY
mrblib/string.rb
mrblib/string.rb
@@ -52,17 +52,22 @@ class String
# ISO 15.2.10.5.18
def gsub(*args, &block)
if args.size == 2
- s = ""
- i = 0
- while j = index(args[0], i)
- seplen = args[0].length
- k = j + seplen
- pre = self[0, j]
- post = self[k, length-k]
- s += self[i, j-i] + args[1].__sub_replace(pre, args[0], post)
- i = k
- end
- s + self[i, length-i]
+ pattern, replace = *args
+ plen = pattern.length
+ replace = replace.to_str
+ offset = 0
+ result = []
+ while found = index(pattern, offset)
+ result << self[offset, found - offset]
+ offset = found + plen
+ result << replace.__sub_replace(self[0, found], pattern, self[offset..-1] || "")
+ if plen == 0
+ result << self[offset, 1]
+ offset += 1
+ end
+ end
+ result << self[offset..-1] if offset < length
+ result.join
elsif args.size == 1 && block
split(args[0], -1).join(block.call(args[0]))
else

MODIFY
test/t/string.rb
test/t/string.rb
@@ -365,6 +365,7 @@ assert('String#gsub', '15.2.10.5.18') do
assert_equal('$$a$$', '##a##'.gsub('##'){|w| '$$' }, 'mruby/mruby#847 another case with block')
assert_equal('A', 'a'.gsub('a', 'A'))
assert_equal('A', 'a'.gsub('a'){|w| w.capitalize })
+ assert_equal(".h.e.l.l.o.", "hello".gsub("", "."))
end
assert('String#gsub with backslash') do

Avoid infinity loop when empty string pattern