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 def initialize(input, size = nil, buffer = nil)
19 @wr = Tempfile.new(nil)
21 @rd = File.open(@wr.path, 'rb')
23 @rd.sync = @wr.sync = true
25 @wr.write(buffer) if buffer
27 @size = size # nil if chunked
33 while tee(Const::CHUNK_SIZE, buf)
38 # returns the size of the input. This is what the Content-Length
39 # header value should be, and how large our input is expected to be.
40 # For TE:chunked, this requires consuming all of the input stream
41 # before returning since there's no other way
43 @size and return @size
49 @input or return @rd.read(*args)
53 rv = @rd.read || Z.dup
55 while tee(Const::CHUNK_SIZE, tmp)
60 buf = args.shift || Z.dup
61 @rd.read(length, buf) || tee(length, buf)
65 # takes zero arguments for strict Rack::Lint compatibility, unlike IO#gets
67 @input or return @rd.gets
68 nil == $/ and return read
71 if @rd.pos < @wr.stat.size
72 line = @rd.gets # cannot be nil here
73 $/ == line[-$/.size, $/.size] and return line
75 # half the line was already read, and the rest of has not been read
82 elsif line = @input.gets
94 self # Rack does not specify what the return value here
98 @rd.rewind # Rack does not specify what the return value here
103 # tees off a +length+ chunk of data from the input into the IO
104 # backing store as well as returning it. +buf+ must be specified.
105 # returns nil if reading from the input returns nil
109 left = @size - @rd.stat.size
110 0 == left and return nil
112 @input.readpartial(left, buf) == left and @input = nil
116 @input.readpartial(length, buf)
118 else # ChunkedReader#readpartial just raises EOFError when done
119 @input.readpartial(length, buf)