Sha256: edac5fdd432c392646c99bb367df27abb7df23a897b24db508c3a61db6e5b87d

Contents?: true

Size: 1.5 KB

Versions: 3

Compression:

Stored size: 1.5 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 write(buf)
        begin
          (w = to_io.write_nonblock(buf)) == buf.size and return
          buf = buf[w..-1]
        rescue Errno::EAGAIN
          WR[self] = false
          ::Fiber.yield
          WR.delete(self)
          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
          RD[self] = false
          expire ||= Time.now + G.kato
          ::Fiber.yield
          RD.delete(self)
          retry
        end
      end

      def readpartial(length, buf = "")
        begin
          to_io.read_nonblock(length, buf)
        rescue Errno::EAGAIN
          RD[self] = false
          ::Fiber.yield
          RD.delete(self)
          retry
        end
      end

    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
rainbows-0.9.0 lib/rainbows/fiber/io.rb
rainbows-0.8.0 lib/rainbows/fiber/io.rb
rainbows-0.7.0 lib/rainbows/fiber/io.rb