mpd/src/io/Reader.hxx

43 lines
959 B
C++
Raw Normal View History

// 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
#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
* 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
};