Project

General

Profile

Feature #4646 ยป 0001-io-wait-add-IO-wait_writable-method.patch

normalperson (Eric Wong), 05/05/2011 07:25 AM

View differences:

ext/io/wait/wait.c
130 130
}
131 131

  
132 132
/*
133
 * call-seq:
134
 *   io.wait_writable          -> IO
135
 *   io.wait_writable(timeout) -> IO or nil
136
 *
137
 * Waits until IO writable is available or times out and returns self or
138
 * nil when EOF is reached.
139
 */
140
static VALUE
141
io_wait_writable(int argc, VALUE *argv, VALUE io)
142
{
143
    rb_io_t *fptr;
144
    int i;
145
    VALUE timeout;
146
    struct timeval timerec;
147
    struct timeval *tv;
148

  
149
    GetOpenFile(io, fptr);
150
    rb_io_check_writable(fptr);
151
    rb_scan_args(argc, argv, "01", &timeout);
152
    if (NIL_P(timeout)) {
153
	tv = NULL;
154
    }
155
    else {
156
	timerec = rb_time_interval(timeout);
157
	tv = &timerec;
158
    }
159

  
160
    i = rb_wait_for_single_fd(fptr->fd, RB_WAITFD_OUT, tv);
161
    if (i < 0)
162
	rb_sys_fail(0);
163
    rb_io_check_closed(fptr);
164
    if (i & RB_WAITFD_OUT)
165
	return io;
166
    return Qnil;
167
}
168

  
169
/*
133 170
 * IO wait methods
134 171
 */
135 172

  
......
139 176
    rb_define_method(rb_cIO, "nread", io_nread, 0);
140 177
    rb_define_method(rb_cIO, "ready?", io_ready_p, 0);
141 178
    rb_define_method(rb_cIO, "wait", io_wait, -1);
179
    rb_define_method(rb_cIO, "wait_writable", io_wait_writable, -1);
142 180
}
test/io/wait/test_io_wait.rb
61 61
    Thread.new { sleep 0.01; @w.close }
62 62
    assert_nil @r.wait
63 63
  end
64

  
65
  def test_wait_writable
66
    assert_equal @w, @w.wait_writable
67
  end
68

  
69
  def test_wait_writable_timeout
70
    assert_equal @w, @w.wait_writable(0.001)
71
    written = fill_pipe
72
    assert_nil @w.wait_writable(0.001)
73
    @r.read(written)
74
    assert_equal @w, @w.wait_writable(0.001)
75
  end
76

  
77
  def test_wait_writable_EPIPE
78
    fill_pipe
79
    @r.close
80
    assert_equal @w, @w.wait_writable
81
  end
82

  
83
  def test_wait_writable_closed
84
    @w.close
85
    assert_raises(IOError) { @w.wait_writable }
86
  end
87

  
88
  def test_wait_writable_closed_while_waiting
89
    thr = Thread.new do
90
      begin
91
        @w.wait_writable
92
      rescue => err
93
        err
94
      end
95
    end
96
    Thread.pass until thr.stop?
97
    @w.close
98
    assert_instance_of IOError, thr.value
99
  end
100

  
101
private
102

  
103
  def fill_pipe
104
    written = 0
105
    buf = " " * 4096
106
    begin
107
      written += @w.write_nonblock(buf)
108
    rescue Errno::EAGAIN
109
      return written
110
    end while true
111
  end
64 112
end if IO.method_defined?(:wait)