I see my mistake, you used >= for the size check when I expected (and assumed) >. The size checks look correct to me now. The style is a little strange, though, with the code calculating the minimum size that would overrun the buffer, rather than required buffer size. I'd prefer it be changed for readability, if you don't mind.