Skip to content

Commit 25a3d18

Browse files
committed
Implement chomp: option for gets, readline, readlines, each_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
1 parent ac1eccc commit 25a3d18

File tree

2 files changed

+46
-8
lines changed

2 files changed

+46
-8
lines changed

lib/openssl/buffering.rb

+10-8
Original file line numberDiff line numberDiff line change
@@ -232,7 +232,7 @@ def read_nonblock(maxlen, buf=nil, exception: true)
232232
#
233233
# Unlike IO#gets the separator must be provided if a limit is provided.
234234

235-
def gets(eol=$/, limit=nil)
235+
def gets(eol=$/, limit=nil, chomp: false)
236236
idx = @rbuffer.index(eol)
237237
until @eof
238238
break if idx
@@ -247,7 +247,9 @@ def gets(eol=$/, limit=nil)
247247
if size && limit && limit >= 0
248248
size = [size, limit].min
249249
end
250-
consume_rbuff(size)
250+
str = consume_rbuff(size)
251+
str.chomp!(eol) if chomp && str
252+
str
251253
end
252254

253255
##
@@ -256,8 +258,8 @@ def gets(eol=$/, limit=nil)
256258
#
257259
# See also #gets
258260

259-
def each(eol=$/)
260-
while line = self.gets(eol)
261+
def each(eol=$/, chomp: false)
262+
while line = self.gets(eol, chomp: chomp)
261263
yield line
262264
end
263265
end
@@ -268,9 +270,9 @@ def each(eol=$/)
268270
#
269271
# See also #gets
270272

271-
def readlines(eol=$/)
273+
def readlines(eol=$/, chomp: false)
272274
ary = []
273-
while line = self.gets(eol)
275+
while line = self.gets(eol, chomp: chomp)
274276
ary << line
275277
end
276278
ary
@@ -281,9 +283,9 @@ def readlines(eol=$/)
281283
#
282284
# Raises EOFError if at end of file.
283285

284-
def readline(eol=$/)
286+
def readline(eol=$/, chomp: false)
285287
raise EOFError if eof?
286-
gets(eol)
288+
gets(eol, chomp: chomp)
287289
end
288290

289291
##

test/openssl/test_ssl.rb

+36
Original file line numberDiff line numberDiff line change
@@ -206,6 +206,42 @@ def test_getbyte
206206
}
207207
end
208208

209+
def test_gets_chomp
210+
start_server { |port|
211+
server_connect(port) { |ssl|
212+
ssl.syswrite("abcd\r\n" * 50)
213+
214+
50.times do
215+
assert_equal "abcd", ssl.gets(chomp: true)
216+
end
217+
}
218+
}
219+
end
220+
221+
def test_gets_chomp_rs
222+
rs = ":"
223+
start_server { |port|
224+
server_connect(port) { |ssl|
225+
ssl.syswrite("aaa:bbb:\r\n")
226+
227+
assert_equal "aaa",ssl.gets(rs, chomp: true)
228+
assert_equal "bbb", ssl.gets(rs, chomp: true)
229+
}
230+
}
231+
end
232+
233+
def test_gets_chomp_default_rs
234+
start_server { |port|
235+
server_connect(port) { |ssl|
236+
ssl.syswrite("aaa\r\nbbb\nccc\r\n")
237+
238+
assert_equal "aaa", ssl.gets(chomp: true)
239+
assert_equal "bbb", ssl.gets(chomp: true)
240+
assert_equal "ccc", ssl.gets(chomp: true)
241+
}
242+
}
243+
end
244+
209245
def test_sync_close
210246
start_server do |port|
211247
begin

0 commit comments

Comments
 (0)