Sha256: a0c9b85b410c3ebea01165aa4dbff499184e6ed41d5e76dfbc8bc2ed5029cef3

Contents?: true

Size: 1.55 KB

Versions: 3

Compression:

Stored size: 1.55 KB

Contents

# -*- encoding: binary -*-
module Rainbows
  module Fiber

    # A partially complete IO wrapper, this exports an IO.select()-able
    # #to_io method and gives users the illusion of a synchronous
    # interface that yields away from the current Fiber whenever
    # the underlying IO object cannot read or write
    class IO < Struct.new(:to_io, :f)

      # for wrapping output response bodies
      def each(&block)
        begin
          yield readpartial(16384)
        rescue EOFError
          break
        end while true
        self
      end

      def close
        to_io.close
      end

      def wait_readable
        RD[self] = false
        ::Fiber.yield
        RD.delete(self)
      end

      def wait_writable
        WR[self] = false
        ::Fiber.yield
        WR.delete(self)
      end

      def write(buf)
        begin
          (w = to_io.write_nonblock(buf)) == buf.size and return
          buf = buf[w..-1]
        rescue Errno::EAGAIN
          wait_writable
          retry
        end while true
      end

      # used for reading headers (respecting keepalive_timeout)
      def read_timeout
        expire = nil
        begin
          to_io.read_nonblock(16384)
        rescue Errno::EAGAIN
          return if expire && expire < Time.now
          expire ||= Time.now + G.kato
          wait_readable
          retry
        end
      end

      def readpartial(length, buf = "")
        begin
          to_io.read_nonblock(length, buf)
        rescue Errno::EAGAIN
          wait_readable
          retry
        end
      end

    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
rainbows-0.90.2 lib/rainbows/fiber/io.rb
rainbows-0.90.1 lib/rainbows/fiber/io.rb
rainbows-0.90.0 lib/rainbows/fiber/io.rb