fs/io/BufferedReader: add method ReadFull()

This commit is contained in:
Max Kellermann 2016-08-16 08:46:44 +02:00
parent 87e0459fcc
commit 31ae50b137
2 changed files with 44 additions and 0 deletions

View File

@ -22,6 +22,11 @@
#include "Reader.hxx"
#include "util/TextFile.hxx"
#include <stdexcept>
#include <stdint.h>
#include <string.h>
bool
BufferedReader::Fill(bool need_more)
{
@ -48,6 +53,32 @@ BufferedReader::Fill(bool need_more)
return true;
}
size_t
BufferedReader::ReadFromBuffer(WritableBuffer<void> dest)
{
auto src = Read();
size_t nbytes = std::min(src.size, dest.size);
memcpy(dest.data, src.data, nbytes);
return nbytes;
}
void
BufferedReader::ReadFull(WritableBuffer<void> _dest)
{
auto dest = WritableBuffer<uint8_t>::FromVoid(_dest);
assert(dest.size == _dest.size);
while (true) {
size_t nbytes = ReadFromBuffer(dest.ToVoid());
dest.skip_front(nbytes);
if (dest.size == 0)
break;
if (!Fill(true))
throw std::runtime_error("Premature end of file");
}
}
char *
BufferedReader::ReadLine()
{

View File

@ -55,6 +55,19 @@ public:
buffer.Consume(n);
}
/**
* Read (and consume) data from the input buffer into the
* given buffer. Does not attempt to refill the buffer.
*/
size_t ReadFromBuffer(WritableBuffer<void> dest);
/**
* Read data into the given buffer and consume it from our
* buffer. Throw an exception if the request cannot be
* forfilled.
*/
void ReadFull(WritableBuffer<void> dest);
char *ReadLine();
unsigned GetLineNumber() const {