userver: userver/engine/io/buffered.hpp Source File
Loading...
Searching...
No Matches
buffered.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/engine/io/buffered.hpp
4/// @brief Buffered I/O wrappers
5
6#include <functional>
7#include <string>
8
9#include <userver/compiler/select.hpp>
10#include <userver/engine/deadline.hpp>
11#include <userver/engine/io/common.hpp>
12#include <userver/engine/io/exception.hpp>
13#include <userver/utils/fast_pimpl.hpp>
14#include <userver/utils/function_ref.hpp>
15
16USERVER_NAMESPACE_BEGIN
17
18namespace engine::io {
19namespace impl {
20
21class Buffer;
22
23} // namespace impl
24
26public:
27 TerminatorNotFoundException();
28};
29
30/// Wrapper for buffered input
31class BufferedReader final {
32public:
33 /// Creates a buffered reader with default buffer size.
34 explicit BufferedReader(ReadableBasePtr source);
35
36 /// Creates a buffered reader with specified initial buffer size.
37 BufferedReader(ReadableBasePtr source, size_t buffer_size);
38
39 ~BufferedReader();
40
41 BufferedReader(BufferedReader&&) noexcept;
42 BufferedReader& operator=(BufferedReader&&) noexcept;
43
44 /// Whether the underlying source is valid.
45 bool IsValid() const;
46
47 /// Reads some bytes from the input stream.
48 std::string ReadSome(size_t max_bytes, Deadline deadline = {});
49
50 /// @brief Reads the exact number of bytes from the input stream.
51 /// @note May return less bytes than requested in case of EOF.
52 std::string ReadAll(size_t num_bytes, Deadline deadline = {});
53
54 /// @brief Reads a line from the input, skipping empty lines.
55 /// @note Does not return line terminators.
56 std::string ReadLine(Deadline deadline = {});
57
58 /// Reads the stream until the specified character of EOF is encountered.
59 std::string ReadUntil(char terminator, Deadline deadline = {});
60
61 /// @brief Reads the stream until the predicate returns `true`.
62 /// @param pred predicate that will be called for each byte read and EOF.
63 std::string ReadUntil(utils::function_ref<bool(int) const> pred, Deadline deadline = {});
64
65 /// Reads one byte from the stream or reports an EOF (-1).
66 int Getc(Deadline deadline = {});
67
68 /// Returns the first byte of the buffer or EOF (-1).
69 int Peek(Deadline deadline = {});
70
71 /// Discards the specified number of bytes from the buffer.
72 void Discard(size_t num_bytes, Deadline deadline = {});
73
74private:
75 size_t FillBuffer(Deadline deadline);
76
77 ReadableBasePtr source_;
78
79 constexpr static std::size_t kBufferSize = compiler::SelectSize() //
80 .For64Bit(40)
81 .For32Bit(20);
82 constexpr static std::size_t kBufferAlignment = alignof(void*);
83 utils::FastPimpl<impl::Buffer, kBufferSize, kBufferAlignment, true> buffer_;
84};
85
86} // namespace engine::io
87
88USERVER_NAMESPACE_END