1 # Copyright (c) 2009 Eric Wong
2 # You can redistribute it and/or modify it under the same terms as Ruby.
6 # acts like tee(1) on an input input to provide a input-like stream
7 # while providing rewindable semantics through a Tempfile/StringIO
8 # backing store. On the first pass, the input is only read on demand
9 # so your Rack application can use input notification (upload progress
10 # and like). This should fully conform to the Rack::InputWrapper
11 # specification on the public API. This class is intended to be a
12 # strict interpretation of Rack::InputWrapper functionality and will
13 # not support any deviations from it.
18 Z.force_encoding(Encoding::BINARY) if Z.respond_to?(:force_encoding)
21 @rd = @wr = @size = @input = nil
26 @tmp = tmp = Tempfile.new(nil)
28 @rd = File.open(tmp.path, 'wb+')
30 @wr = File.open(tmp.path, 'wb')
31 @rd.sync = @wr.sync = true
39 def reopen(input, size = nil, buffer = nil)
42 @rd.truncate(0) # truncate read to flush luserspace read buffers
43 @wr.write(buffer) if buffer
45 @size = size # nil if chunked
52 while tee(Const::CHUNK_SIZE, buf)
57 # returns the size of the input. This is what the Content-Length
58 # header value should be, and how large our input is expected to be.
59 # For TE:chunked, this requires consuming all of the input stream
60 # before returning since there's no other way
62 @size and return @size
68 @input or return @rd.read(*args)
72 rv = @rd.read || Z.dup
74 while tee(Const::CHUNK_SIZE, tmp)
79 buf = args.shift || Z.dup
80 @rd.read(length, buf) || tee(length, buf)
84 # takes zero arguments for strict Rack::Lint compatibility, unlike IO#gets
86 @input or return @rd.gets
87 nil == $/ and return read
90 if @rd.pos < @wr.stat.size
91 line = @rd.gets # cannot be nil here
92 $/ == line[-$/.size, $/.size] and return line
94 # half the line was already read, and the rest of has not been read
101 elsif line = @input.gets
113 self # Rack does not specify what the return value here
117 @rd.rewind # Rack does not specify what the return value here
122 # tees off a +length+ chunk of data from the input into the IO
123 # backing store as well as returning it. +buf+ must be specified.
124 # returns nil if reading from the input returns nil
128 left = @size - @rd.stat.size
129 0 == left and return nil
131 @input.readpartial(left, buf) == left and @input = nil
135 @input.readpartial(length, buf)
137 else # ChunkedReader#readpartial just raises EOFError when done
138 @input.readpartial(length, buf)