1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-26 07:47:37 +00:00

AK: Lower the requirements for InputStream::eof and rename it.

Consider the following snippet:

    void foo(InputStream& stream) {
        if(!stream.eof()) {
            u8 byte;
            stream >> byte;
        }
    }

There is a very subtle bug in this snippet, for some input streams eof()
might return false even if no more data can be read. In this case an
error flag would be set on the stream.

Until now I've always ensured that this is not the case, but this made
the implementation of eof() unnecessarily complicated.
InputFileStream::eof had to keep a ByteBuffer around just to make this
possible. That meant a ton of unnecessary copies just to get a reliable
eof().

In most cases it isn't actually necessary to have a reliable eof()
implementation.

In most other cases a reliable eof() is avaliable anyways because in
some cases like InputMemoryStream it is very easy to implement.
This commit is contained in:
asynts 2020-09-13 12:24:17 +02:00 committed by Andreas Kling
parent 8a21c528ad
commit 96edcbc27c
12 changed files with 61 additions and 89 deletions

View file

@ -75,10 +75,22 @@ namespace AK {
class InputStream : public virtual AK::Detail::Stream {
public:
// Does nothing and returns zero if there is already an error.
// Reads at least one byte unless none are requested or none are avaliable. Does nothing
// and returns zero if there is already an error.
virtual size_t read(Bytes) = 0;
// If this function returns true, then no more data can be read. If read(Bytes) previously
// returned zero even though bytes were requested, then the inverse is true as well.
virtual bool unreliable_eof() const = 0;
// Some streams additionally define a method with the signature:
//
// bool eof() const;
//
// This method has the same semantics as unreliable_eof() but returns true if and only if no
// more data can be read. (A failed read is not necessary.)
virtual bool read_or_error(Bytes) = 0;
virtual bool eof() const = 0;
virtual bool discard_or_error(size_t count) = 0;
};