diff --git a/src/io/Reader.cxx b/src/io/Reader.cxx new file mode 100644 index 000000000..26c904f23 --- /dev/null +++ b/src/io/Reader.cxx @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#include "Reader.hxx" + +#include + +void +Reader::ReadFull(std::span dest) +{ + const auto nbytes = Read(dest); + if (nbytes < dest.size()) + throw std::runtime_error{"Unexpected end of file"}; +} diff --git a/src/io/Reader.hxx b/src/io/Reader.hxx index 7babefc49..01ea7c375 100644 --- a/src/io/Reader.hxx +++ b/src/io/Reader.hxx @@ -28,11 +28,16 @@ public: */ virtual std::size_t Read(std::span dest) = 0; + /** + * Like Read(), but throws an exception when there is not + * enough data to fill the destination buffer. + */ + void ReadFull(std::span dest); + template requires std::is_standard_layout_v && std::is_trivially_copyable_v 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})); } }; diff --git a/src/io/meson.build b/src/io/meson.build index 3f4383578..f9049521d 100644 --- a/src/io/meson.build +++ b/src/io/meson.build @@ -2,6 +2,7 @@ io = static_library( 'io', 'FileDescriptor.cxx', 'Open.cxx', + 'Reader.cxx', 'PeekReader.cxx', 'BufferedReader.cxx', 'BufferedOutputStream.cxx',