Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement chomp: option for gets, readline, readlines, each_line #503

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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
35 changes: 35 additions & 0 deletions test/openssl/test_pair.rb
Expand Up @@ -115,6 +115,41 @@ 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"
s1.close

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

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

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

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