File tree Expand file tree Collapse file tree 2 files changed +26
-3
lines changed Expand file tree Collapse file tree 2 files changed +26
-3
lines changed Original file line number Diff line number Diff line change @@ -82,7 +82,15 @@ def read(n=nil)
82
82
# returns the bytes read (including +sep_string+). If +sep_string+ is
83
83
# omitted, it defaults to +$/+. If EOF is encountered before any data
84
84
# could be read, #gets will return +nil+.
85
- def gets ( sep_string = $/)
85
+ def gets ( sep_or_limit = $/, limit = Float ::INFINITY )
86
+ if sep_or_limit . is_a? Integer
87
+ sep_string = $/
88
+ lim = sep_or_limit
89
+ else
90
+ sep_string = sep_or_limit
91
+ lim = limit
92
+ end
93
+
86
94
delim = if sep_string . length == 0
87
95
"#{ $/} #{ $/} "
88
96
else
@@ -92,7 +100,7 @@ def gets(sep_string=$/)
92
100
loop do
93
101
at = @buffer . index ( delim )
94
102
if at
95
- offset = at + delim . length
103
+ offset = [ at + delim . length , lim ] . min
96
104
@pos += offset
97
105
line , @buffer = @buffer [ 0 , offset ] , @buffer [ offset ..-1 ]
98
106
return line
Original file line number Diff line number Diff line change @@ -91,6 +91,21 @@ def test_gets_when_no_such_delimiter_exists_in_stream_should_read_to_EOF
91
91
assert @file . eof?
92
92
end
93
93
94
+ def test_gets_with_integer_argument_should_read_number_of_bytes
95
+ @sftp . expects ( :read! ) . returns ( "hello world\n goodbye world\n \n farewell!\n " )
96
+ assert_equal "hello w" , @file . gets ( 7 )
97
+ end
98
+
99
+ def test_gets_with_delimiter_and_limit_should_read_to_delimiter_if_less_than_limit
100
+ @sftp . expects ( :read! ) . returns ( "hello world\n goodbye world\n \n farewell!\n " )
101
+ assert_equal "hello w" , @file . gets ( "w" , 11 )
102
+ end
103
+
104
+ def test_gets_with_delimiter_and_limit_should_read_to_limit_if_less_than_delimiter
105
+ @sftp . expects ( :read! ) . returns ( "hello world\n goodbye world\n \n farewell!\n " )
106
+ assert_equal "hello" , @file . gets ( "w" , 5 )
107
+ end
108
+
94
109
def test_gets_at_EOF_should_return_nil
95
110
@sftp . expects ( :read! ) . returns ( nil )
96
111
assert_nil @file . gets
@@ -156,4 +171,4 @@ def test_stat_should_return_attributes_object_for_handle
156
171
@sftp . expects ( :fstat! ) . with ( "handle" ) . returns ( stat )
157
172
assert_equal stat , @file . stat
158
173
end
159
- end
174
+ end
You can’t perform that action at this time.
0 commit comments