Skip to content

Commit

Permalink
Implement chomp: option for gets, readline, readlines, `each_…
Browse files Browse the repository at this point in the history
…line`

It was added to IO methods in Ruby 2.4, but OpenSSL sockets don't have
them, so any code accepting SSL sockets can't make use of it.

Ref: ruby/ruby@a2144bd
  • Loading branch information
byroot committed Mar 21, 2022
1 parent d9111c2 commit be4c942
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 8 deletions.
18 changes: 10 additions & 8 deletions lib/openssl/buffering.rb
Expand Up @@ -232,7 +232,7 @@ def read_nonblock(maxlen, buf=nil, exception: true)
#
# Unlike IO#gets the separator must be provided if a limit is provided.

def gets(eol=$/, limit=nil)
def gets(eol=$/, limit=nil, chomp: false)
idx = @rbuffer.index(eol)
until @eof
break if idx
Expand All @@ -247,7 +247,9 @@ def gets(eol=$/, limit=nil)
if size && limit && limit >= 0
size = [size, limit].min
end
consume_rbuff(size)
str = consume_rbuff(size)
str.chomp!(eol) if chomp && str
str
end

##
Expand All @@ -256,8 +258,8 @@ def gets(eol=$/, limit=nil)
#
# See also #gets

def each(eol=$/)
while line = self.gets(eol)
def each(eol=$/, chomp: false)
while line = self.gets(eol, chomp: chomp)
yield line
end
end
Expand All @@ -268,9 +270,9 @@ def each(eol=$/)
#
# See also #gets

def readlines(eol=$/)
def readlines(eol=$/, chomp: false)
ary = []
while line = self.gets(eol)
while line = self.gets(eol, chomp: chomp)
ary << line
end
ary
Expand All @@ -281,9 +283,9 @@ def readlines(eol=$/)
#
# Raises EOFError if at end of file.

def readline(eol=$/)
def readline(eol=$/, chomp: false)
raise EOFError if eof?
gets(eol)
gets(eol, chomp: chomp)
end

##
Expand Down
33 changes: 33 additions & 0 deletions test/openssl/test_pair.rb
Expand Up @@ -115,6 +115,39 @@ def test_gets
}
end

def test_gets_chomp
ssl_pair {|s1, s2|
s1 << "abcd\r\n" * 50
s1.close

50.times do
assert_equal "abcd", s2.gets(chomp: true)
end
}
end

def test_gets_chomp_rs
rs = ":"
ssl_pair {|s1, s2|
s1 << "aaa:bbb:\r\n"
s1.close

assert_equal "aaa", s2.gets(rs, chomp: true)
assert_equal "bbb", s2.gets(rs, chomp: true)
}
end

def test_gets_chomp_default_rs
ssl_pair {|s1, s2|
s1 << "aaa\r\nbbb\nccc\r\n"
s1.close

assert_equal "aaa", s2.gets(chomp: true)
assert_equal "bbb", s2.gets(chomp: true)
assert_equal "ccc", s2.gets(chomp: true)
}
end

def test_gets_eof_limit
ssl_pair {|s1, s2|
s1.write("hello")
Expand Down

0 comments on commit be4c942

Please sign in to comment.