[#1890] Correctly expand ByteBuffer array in all cases

The problem was that we did not handle the case correctly when doubling the array was not enough. We need to keep doubling until everything fits in.
Merge remote-tracking branch: upstream/master