Skip to content

Commit

Permalink
StringIO#read(length) returns binary string when passed length
Browse files Browse the repository at this point in the history
Test Script
----
require 'stringio'
require 'test/unit/assertions.rb'
include Test::Unit::Assertions

str = "abcdefg" * 100
str.force_encoding('UTF-8')

io = StringIO.new(str)
s  = io.read(0)
assert_equal("", s)
assert_equal(Encoding::ASCII_8BIT, s.encoding)

s = io.read(10)
assert_equal("abcdefgabc", s)
assert_equal(Encoding::ASCII_8BIT, s.encoding)

s = io.read()
assert_equal(Encoding::UTF_8, s.encoding)

length = Object.new
def length.to_int
  0
end
io = StringIO.new("")
s = io.read(length)
assert_equal("", s)
assert_equal(Encoding::ASCII_8BIT, s.encoding)
  • Loading branch information
Watson1978 committed Feb 21, 2012
1 parent 28f7615 commit 2ef505b
Showing 1 changed file with 15 additions and 10 deletions.
25 changes: 15 additions & 10 deletions lib/stringio.rb
Original file line number Diff line number Diff line change
Expand Up @@ -131,23 +131,28 @@ def read(length = nil, buffer = String.new)
raise TypeError unless buffer.respond_to?(:to_str)
buffer = buffer.to_str

if length == 0
buffer.replace("")
elsif length == nil
if length.nil?
return buffer.replace("") if self.eof?
buffer.replace(@string[@pos..-1])
@pos = @string.size
else
if self.eof?
buffer.replace("")
return nil
end
raise TypeError unless length.respond_to?(:to_int)
length = length.to_int
raise ArgumentError if length < 0
buffer.replace(@string[@pos, length])
@pos += buffer.length
end

if length == 0
buffer.replace("")
else
if self.eof?
buffer.replace("")
return nil
end
buffer.replace(@string[@pos, length])
@pos += buffer.length
end
buffer.force_encoding('BINARY')
end


buffer
end
Expand Down

0 comments on commit 2ef505b

Please sign in to comment.