Checks for buffer out of bounds before writing to the stream. Fixes #636