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
26 public:
27 TerminatorNotFoundException();
28};
29
30/// Wrapper for buffered input
31class BufferedReader final {
32 public:
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,
64 Deadline deadline = {});
65
66 /// Reads one byte from the stream or reports an EOF (-1).
67 int Getc(Deadline deadline = {});
68
69 /// Returns the first byte of the buffer or EOF (-1).
70 int Peek(Deadline deadline = {});
71
72 /// Discards the specified number of bytes from the buffer.
73 void Discard(size_t num_bytes, Deadline deadline = {});
74
75 private:
76 size_t FillBuffer(Deadline deadline);
77
78 ReadableBasePtr source_;
79
80 constexpr static std::size_t kBufferSize = compiler::SelectSize() //
81 .For64Bit(40)
82 .For32Bit(20);
83 constexpr static std::size_t kBufferAlignment = alignof(void*);
84 utils::FastPimpl<impl::Buffer, kBufferSize, kBufferAlignment, true> buffer_;
85};
86
87} // namespace engine::io
88
89USERVER_NAMESPACE_END