2023-03-06 14:42:04 +01:00
|
|
|
// SPDX-License-Identifier: BSD-2-Clause
|
|
|
|
// author: Max Kellermann <max.kellermann@gmail.com>
|
2014-08-07 18:10:23 +02:00
|
|
|
|
2024-02-26 13:01:12 +01:00
|
|
|
#pragma once
|
2014-08-07 18:10:23 +02:00
|
|
|
|
2020-03-13 00:46:28 +01:00
|
|
|
#include <cstddef>
|
2023-10-05 10:25:16 +02:00
|
|
|
#include <span>
|
2023-10-05 10:33:51 +02:00
|
|
|
#include <type_traits>
|
2014-08-07 18:10:23 +02:00
|
|
|
|
|
|
|
/**
|
|
|
|
* An interface that can read bytes from a stream until the stream
|
|
|
|
* ends.
|
|
|
|
*
|
|
|
|
* This interface is simpler and less cumbersome to use than
|
|
|
|
* #InputStream.
|
|
|
|
*/
|
|
|
|
class Reader {
|
|
|
|
public:
|
|
|
|
Reader() = default;
|
|
|
|
Reader(const Reader &) = delete;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Read data from the stream.
|
|
|
|
*
|
|
|
|
* @return the number of bytes read into the given buffer or 0
|
2015-12-16 11:05:33 +01:00
|
|
|
* on end-of-stream
|
2014-08-07 18:10:23 +02:00
|
|
|
*/
|
2023-10-05 11:01:46 +02:00
|
|
|
[[nodiscard]]
|
2023-10-05 10:25:16 +02:00
|
|
|
virtual std::size_t Read(std::span<std::byte> dest) = 0;
|
2023-10-05 10:33:51 +02:00
|
|
|
|
2023-10-05 11:00:01 +02:00
|
|
|
/**
|
|
|
|
* Like Read(), but throws an exception when there is not
|
|
|
|
* enough data to fill the destination buffer.
|
|
|
|
*/
|
|
|
|
void ReadFull(std::span<std::byte> dest);
|
|
|
|
|
2023-10-05 10:33:51 +02:00
|
|
|
template<typename T>
|
|
|
|
requires std::is_standard_layout_v<T> && std::is_trivially_copyable_v<T>
|
|
|
|
void ReadT(T &dest) {
|
2023-10-05 11:00:01 +02:00
|
|
|
ReadFull(std::as_writable_bytes(std::span{&dest, 1}));
|
2023-10-05 10:33:51 +02:00
|
|
|
}
|
2014-08-07 18:10:23 +02:00
|
|
|
};
|