Fix a race condition in ChunkedOutputStream.write and add a write buffer limit.

write() was issuing a call to leastSize on the input stream twice which may result in two different values. This would lead to the wrong amount of data written to the current chunk.