io/Reader: add method ReadFull()

This commit is contained in:
Max Kellermann 2023-10-05 11:00:01 +02:00
parent 7ccc4ddf0d
commit 3032792563
3 changed files with 22 additions and 2 deletions

14
src/io/Reader.cxx Normal file
View File

@ -0,0 +1,14 @@
// SPDX-License-Identifier: BSD-2-Clause
// author: Max Kellermann <max.kellermann@gmail.com>
#include "Reader.hxx"
#include <stdexcept>
void
Reader::ReadFull(std::span<std::byte> dest)
{
const auto nbytes = Read(dest);
if (nbytes < dest.size())
throw std::runtime_error{"Unexpected end of file"};
}

View File

@ -28,11 +28,16 @@ public:
*/
virtual std::size_t Read(std::span<std::byte> dest) = 0;
/**
* Like Read(), but throws an exception when there is not
* enough data to fill the destination buffer.
*/
void ReadFull(std::span<std::byte> dest);
template<typename T>
requires std::is_standard_layout_v<T> && std::is_trivially_copyable_v<T>
void ReadT(T &dest) {
// TODO check return value
Read(std::as_writable_bytes(std::span{&dest, 1}));
ReadFull(std::as_writable_bytes(std::span{&dest, 1}));
}
};

View File

@ -2,6 +2,7 @@ io = static_library(
'io',
'FileDescriptor.cxx',
'Open.cxx',
'Reader.cxx',
'PeekReader.cxx',
'BufferedReader.cxx',
'BufferedOutputStream.cxx',