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 cafde8e
Show file tree
Hide file tree
Showing 2 changed files with 46 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
36 changes: 36 additions & 0 deletions test/openssl/test_ssl.rb
Expand Up @@ -206,6 +206,42 @@ def test_getbyte
}
end

def test_gets_chomp
start_server { |port|
server_connect(port) { |ssl|
ssl.syswrite("abcd\r\n" * 50)

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

def test_gets_chomp_rs
rs = ":"
start_server { |port|
server_connect(port) { |ssl|
ssl.syswrite("aaa:bbb:\r\n")

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

def test_gets_chomp_default_rs
start_server { |port|
server_connect(port) { |ssl|
ssl.syswrite("aaa\r\nbbb\nccc\r\n")

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

def test_sync_close
start_server do |port|
begin
Expand Down

0 comments on commit cafde8e

Please sign in to comment.