Commit 9508be9b by Janko Marohnić

Use buffer string to avoid allocating new strings

parent 63ae54f7
...@@ -112,25 +112,26 @@ class MimeMagic ...@@ -112,25 +112,26 @@ class MimeMagic
if io.respond_to?(:seek) && io.respond_to?(:read) if io.respond_to?(:seek) && io.respond_to?(:read)
io.binmode io.binmode
io.set_encoding(Encoding::BINARY) if io.respond_to?(:set_encoding) io.set_encoding(Encoding::BINARY) if io.respond_to?(:set_encoding)
MAGIC.send(method) { |type, matches| magic_match_io(io, matches) } buffer = "".force_encoding(Encoding::BINARY)
MAGIC.send(method) { |type, matches| magic_match_io(io, matches, buffer) }
else else
str = io.respond_to?(:read) ? io.read : io.to_s str = io.respond_to?(:read) ? io.read : io.to_s
magic_match(StringIO.new(str), method) magic_match(StringIO.new(str), method)
end end
end end
def self.magic_match_io(io, matches) def self.magic_match_io(io, matches, buffer)
matches.any? do |offset, value, children| matches.any? do |offset, value, children|
match = match =
if Range === offset if Range === offset
io.seek(offset.begin) io.seek(offset.begin)
x = io.read(offset.end - offset.begin + value.bytesize) x = io.read(offset.end - offset.begin + value.bytesize, buffer)
x && x.include?(value) x && x.include?(value)
else else
io.seek(offset) io.seek(offset)
io.read(value.bytesize) == value io.read(value.bytesize, buffer) == value
end end
match && (!children || magic_match_io(io, children)) match && (!children || magic_match_io(io, children, buffer))
end end
end end
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment