io/Reader: add method ReadFull()
This commit is contained in:
parent
7ccc4ddf0d
commit
3032792563
14
src/io/Reader.cxx
Normal file
14
src/io/Reader.cxx
Normal 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"};
|
||||||
|
}
|
@ -28,11 +28,16 @@ public:
|
|||||||
*/
|
*/
|
||||||
virtual std::size_t Read(std::span<std::byte> dest) = 0;
|
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>
|
template<typename T>
|
||||||
requires std::is_standard_layout_v<T> && std::is_trivially_copyable_v<T>
|
requires std::is_standard_layout_v<T> && std::is_trivially_copyable_v<T>
|
||||||
void ReadT(T &dest) {
|
void ReadT(T &dest) {
|
||||||
// TODO check return value
|
ReadFull(std::as_writable_bytes(std::span{&dest, 1}));
|
||||||
Read(std::as_writable_bytes(std::span{&dest, 1}));
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -2,6 +2,7 @@ io = static_library(
|
|||||||
'io',
|
'io',
|
||||||
'FileDescriptor.cxx',
|
'FileDescriptor.cxx',
|
||||||
'Open.cxx',
|
'Open.cxx',
|
||||||
|
'Reader.cxx',
|
||||||
'PeekReader.cxx',
|
'PeekReader.cxx',
|
||||||
'BufferedReader.cxx',
|
'BufferedReader.cxx',
|
||||||
'BufferedOutputStream.cxx',
|
'BufferedOutputStream.cxx',
|
||||||
|
Loading…
Reference in New Issue
Block a user