@@ -81,21 +81,35 @@ def read(n=nil)
81
81
# Reads up to the next instance of +sep_string+ in the stream, and
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
- # could be read, #gets will return +nil+.
85
- def gets ( sep_string = $/)
86
- delim = if sep_string . length == 0
84
+ # could be read, #gets will return +nil+. If the first argument is an
85
+ # integer, or optional second argument is given, the returning string
86
+ # would not be longer than the given value in bytes.
87
+ def gets ( sep_or_limit = $/, limit = Float ::INFINITY )
88
+ if sep_or_limit . is_a? Integer
89
+ sep_string = $/
90
+ lim = sep_or_limit
91
+ else
92
+ sep_string = sep_or_limit
93
+ lim = limit
94
+ end
95
+
96
+ delim = if sep_string && sep_string . length == 0
87
97
"#{ $/} #{ $/} "
88
98
else
89
99
sep_string
90
100
end
91
101
92
102
loop do
93
- at = @buffer . index ( delim )
103
+ at = @buffer . index ( delim ) if delim
94
104
if at
95
- offset = at + delim . length
105
+ offset = [ at + delim . length , lim ] . min
96
106
@pos += offset
97
107
line , @buffer = @buffer [ 0 , offset ] , @buffer [ offset ..-1 ]
98
108
return line
109
+ elsif lim < @buffer . length
110
+ @pos += lim
111
+ line , @buffer = @buffer [ 0 , lim ] , @buffer [ lim ..-1 ]
112
+ return line
99
113
elsif !fill
100
114
return nil if @buffer . empty?
101
115
@pos += @buffer . length
@@ -107,12 +121,20 @@ def gets(sep_string=$/)
107
121
108
122
# Same as #gets, but raises EOFError if EOF is encountered before any
109
123
# data could be read.
110
- def readline ( sep_string = $/)
111
- line = gets ( sep_string )
124
+ def readline ( sep_or_limit = $/, limit = Float :: INFINITY )
125
+ line = gets ( sep_or_limit , limit )
112
126
raise EOFError if line . nil?
113
127
return line
114
128
end
115
129
130
+ # Resets position to beginning of file
131
+ def rewind
132
+ @pos = 0
133
+ @real_pos = 0
134
+ @real_eof = false
135
+ @buffer = ""
136
+ end
137
+
116
138
# Writes the given data to the stream, incrementing the file position and
117
139
# returning the number of bytes written.
118
140
def write ( data )
0 commit comments