LZW: prevent reading beyond the end of the stream (rebased onto develop)



This is the same as gh-419 but rebased onto develop.

----

Fixes #10525.