Fix reading 0 bytes after ungetting a character

This replaces #2250. It's exactly the same code but I have some other pull requests incoming and restructured my repository.