1 # -*- encoding: binary -*-
3 # A Fiber-aware IO class, gives users the illusion of a synchronous
4 # interface that yields away from the current Fiber whenever
5 # the underlying descriptor is blocked on reads or write
7 # This is a stable, legacy interface and should be preserved for all
8 # future versions of Rainbows! However, new apps should use
9 # Rainbows::Fiber::IO::Socket or Rainbows::Fiber::IO::Pipe instead.
11 class Rainbows::Fiber::IO
15 # see Rainbows::Fiber::IO::Compat for initialize implementation
21 # needed to write errors with
22 def write_nonblock(buf)
23 @to_io.write_nonblock(buf)
30 # for wrapping output response bodies
32 buf = readpartial(16384)
34 yield buf while readpartial(16384, buf)
48 if @to_io.respond_to?(:kgio_trywrite)
50 case rv = @to_io.kgio_trywrite(buf)
61 (rv = @to_io.write_nonblock(buf)) == buf.bytesize and return
62 buf = byte_slice(buf, rv..-1)
69 def byte_slice(buf, range) # :nodoc:
70 if buf.encoding != Encoding::BINARY
71 buf.dup.force_encoding(Encoding::BINARY)[range]
77 # used for reading headers (respecting keepalive_timeout)
80 if @to_io.respond_to?(:kgio_tryread)
82 case rv = @to_io.kgio_tryread(16384, buf)
84 return if expire && expire < Time.now
85 expire ||= read_expire
93 return @to_io.read_nonblock(16384, buf)
95 return if expire && expire < Time.now
96 expire ||= read_expire
102 def readpartial(length, buf = "")
103 if @to_io.respond_to?(:kgio_tryread)
105 rv = @to_io.kgio_tryread(length, buf)
108 raise EOFError, "end of file reached", []
117 return @to_io.read_nonblock(length, buf)
125 @to_io.kgio_read(*args)
128 def kgio_read!(*args)
129 @to_io.kgio_read!(*args)
132 def kgio_trywrite(*args)
133 @to_io.kgio_trywrite(*args)
136 autoload :Socket, 'rainbows/fiber/io/socket'
137 autoload :Pipe, 'rainbows/fiber/io/pipe'
141 require 'rainbows/fiber/io/methods'
142 require 'rainbows/fiber/io/compat'
143 Rainbows::Client.__send__(:include, Rainbows::Fiber::IO::Methods)
144 class Rainbows::Fiber::IO
145 include Rainbows::Fiber::IO::Compat
146 include Rainbows::Fiber::IO::Methods
147 alias_method :wait_readable, :kgio_wait_readable
148 alias_method :wait_writable, :kgio_wait_writable