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, body)
19 @tmp = Tempfile.new(nil)
29 @size = size # nil if chunked
35 while tee(Const::CHUNK_SIZE, buf)
41 # returns the size of the input. This is what the Content-Length
42 # header value should be, and how large our input is expected to be.
43 # For TE:chunked, this requires consuming all of the input stream
44 # before returning since there's no other way
46 @size and return @size
48 @size = @tmp.stat.size
52 @input or return @tmp.read(*args)
56 rv = @tmp.read || Z.dup
58 while tee(Const::CHUNK_SIZE, tmp)
63 buf = args.shift || Z.dup
64 diff = @tmp.stat.size - @tmp.pos
68 @tmp.read(diff > length ? length : diff, buf)
73 # takes zero arguments for strict Rack::Lint compatibility, unlike IO#gets
75 @input or return @tmp.gets
76 nil == $/ and return read
79 if @tmp.pos < @tmp.stat.size
80 line = @tmp.gets # cannot be nil here
81 $/ == line[-$/.size, $/.size] and return line
83 # half the line was already read, and the rest of has not been read
90 elsif line = @input.gets
102 self # Rack does not specify what the return value here
106 @tmp.rewind # Rack does not specify what the return value here
111 # tees off a +length+ chunk of data from the input into the IO
112 # backing store as well as returning it. +buf+ must be specified.
113 # returns nil if reading from the input returns nil
117 left = @size - @tmp.stat.size
118 0 == left and return nil
120 @input.readpartial(left, buf) == left and @input = nil
124 @input.readpartial(length, buf)
126 else # ChunkedReader#readpartial just raises EOFError when done
127 @input.readpartial(length, buf)