about summary refs log tree commit homepage
path: root/lib/rainbows/fiber/io
diff options
context:
space:
mode:
Diffstat (limited to 'lib/rainbows/fiber/io')
-rw-r--r--lib/rainbows/fiber/io/compat.rb10
-rw-r--r--lib/rainbows/fiber/io/methods.rb44
-rw-r--r--lib/rainbows/fiber/io/pipe.rb7
-rw-r--r--lib/rainbows/fiber/io/socket.rb7
4 files changed, 68 insertions, 0 deletions
diff --git a/lib/rainbows/fiber/io/compat.rb b/lib/rainbows/fiber/io/compat.rb
new file mode 100644
index 0000000..2aaf416
--- /dev/null
+++ b/lib/rainbows/fiber/io/compat.rb
@@ -0,0 +1,10 @@
+# -*- encoding: binary -*-
+module Rainbows::Fiber::IO::Compat
+  def initialize(io, fiber = Fiber.current)
+    @to_io, @f = io, fiber
+  end
+
+  def close
+    @to_io.close
+  end
+end
diff --git a/lib/rainbows/fiber/io/methods.rb b/lib/rainbows/fiber/io/methods.rb
new file mode 100644
index 0000000..663fdb4
--- /dev/null
+++ b/lib/rainbows/fiber/io/methods.rb
@@ -0,0 +1,44 @@
+# -*- encoding: binary -*-
+
+module Rainbows::Fiber::IO::Methods
+  RD = Rainbows::Fiber::RD
+  WR = Rainbows::Fiber::WR
+  attr_accessor :f
+
+  # for wrapping output response bodies
+  def each(&block)
+    if buf = kgio_read(16384)
+      yield buf
+      yield buf while kgio_read(16384, buf)
+    end
+    self
+  end
+
+  def close
+    fd = fileno
+    RD[fd] = WR[fd] = nil
+    super
+  end
+
+  def wait_readable
+    fd = fileno
+    @f = Fiber.current
+    RD[fd] = self
+    Fiber.yield
+    RD[fd] = nil
+  end
+
+  def wait_writable
+    fd = fileno
+    @f = Fiber.current
+    WR[fd] = self
+    Fiber.yield
+    WR[fd] = nil
+  end
+
+  def self.included(klass)
+    if klass.method_defined?(:kgio_write)
+      klass.__send__(:alias_method, :write, :kgio_write)
+    end
+  end
+end
diff --git a/lib/rainbows/fiber/io/pipe.rb b/lib/rainbows/fiber/io/pipe.rb
new file mode 100644
index 0000000..c7ae508
--- /dev/null
+++ b/lib/rainbows/fiber/io/pipe.rb
@@ -0,0 +1,7 @@
+# -*- encoding: binary -*-
+# A Fiber-aware Pipe class, gives users the illusion of a synchronous
+# interface that yields away from the current Fiber whenever
+# the underlying descriptor is blocked on reads or write
+class Rainbows::Fiber::IO::Pipe < Kgio::Pipe
+  include Rainbows::Fiber::IO::Methods
+end
diff --git a/lib/rainbows/fiber/io/socket.rb b/lib/rainbows/fiber/io/socket.rb
new file mode 100644
index 0000000..61c451d
--- /dev/null
+++ b/lib/rainbows/fiber/io/socket.rb
@@ -0,0 +1,7 @@
+# -*- encoding: binary -*-
+# A Fiber-aware Socket class, gives users the illusion of a synchronous
+# interface that yields away from the current Fiber whenever
+# the underlying descriptor is blocked on reads or write
+class Rainbows::Fiber::IO::Socket < Kgio::Socket
+  include Rainbows::Fiber::IO::Methods
+end