Skip to content

Commit

Permalink
Fix zero-byte writes in IOStream.
Browse files Browse the repository at this point in the history
Previously zero-byte writes would cause the CPU to run at 100% and
would never call their callback (if any).
  • Loading branch information
bdarnell committed Oct 25, 2011
1 parent a9e92e2 commit bf75571
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
5 changes: 4 additions & 1 deletion tornado/iostream.py
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,10 @@ def write(self, data, callback=None):
"""
assert isinstance(data, bytes_type)
self._check_closed()
self._write_buffer.append(data)
if data:
# We use bool(_write_buffer) as a proxy for write_buffer_size>0,
# so never put empty strings in the buffer.
self._write_buffer.append(data)
self._write_callback = stack_context.wrap(callback)
self._handle_write()
if self._write_buffer:
Expand Down
11 changes: 11 additions & 0 deletions tornado/test/iostream_test.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from tornado import netutil
from tornado.ioloop import IOLoop
from tornado.iostream import IOStream
from tornado.testing import AsyncHTTPTestCase, LogTrapTestCase, get_unused_port
from tornado.util import b
Expand Down Expand Up @@ -57,6 +58,16 @@ def test_read_zero_bytes(self):
data = self.wait()
self.assertEqual(data, b("200"))

def test_write_zero_bytes(self):
# Attempting to write zero bytes should run the callback without
# going into an infinite loop.
server, client = self.make_iostream_pair()
server.write(b(''), callback=self.stop)
self.wait()
# As a side effect, the stream is now listening for connection
# close (if it wasn't already), but is not listening for writes
self.assertEqual(server._state, IOLoop.READ|IOLoop.ERROR)

def test_connection_refused(self):
# When a connection is refused, the connect callback should not
# be run. (The kqueue IOLoop used to behave differently from the
Expand Down

0 comments on commit bf75571

Please sign in to comment.