Line data Source code
1 : /*
2 : * Protobuf serialization library - buffered reader, between io::reader and detail::istream.
3 : *
4 : * Copyright (c) 2024 Antonin Kriz <antonin.kriz@gmail.com>
5 : * Released under the MIT License. See LICENSE in the project root.
6 : */
7 :
8 : #pragma once
9 : #include "io.hpp"
10 : #include <array>
11 : #include <cassert>
12 : #include <cstdlib>
13 : #include <cstring>
14 : #include <string_view>
15 : #include <sys/types.h>
16 :
17 : namespace spb::io
18 : {
19 : class buffered_reader
20 : {
21 : public:
22 : static constexpr size_t BUFFER_SIZE = 256;
23 :
24 : private:
25 : using buffer_index_type = uint16_t;
26 : std::array<char, BUFFER_SIZE> buffer;
27 : io::reader on_read;
28 : buffer_index_type begin_index = 0;
29 : buffer_index_type end_index = 0;
30 : bool eof_reached = false;
31 :
32 21813 : auto bytes_in_buffer() const noexcept -> size_t
33 : {
34 21813 : return end_index - begin_index;
35 : }
36 :
37 776 : auto space_left_in_buffer() const noexcept -> size_t
38 : {
39 1552 : return buffer.size() - end_index;
40 : }
41 :
42 833 : void shift_data_to_start() noexcept
43 : {
44 833 : if (begin_index == 0)
45 410 : return;
46 :
47 846 : memmove(buffer.data(), buffer.data() + begin_index, bytes_in_buffer());
48 423 : end_index -= begin_index;
49 423 : begin_index = 0;
50 : }
51 :
52 833 : void read_buffer()
53 : {
54 833 : shift_data_to_start();
55 :
56 3218 : while (bytes_in_buffer() < buffer.size() && !eof_reached)
57 : {
58 : auto bytes_in =
59 776 : static_cast<buffer_index_type>(on_read(&buffer[end_index], space_left_in_buffer()));
60 776 : eof_reached |= bytes_in == 0;
61 776 : end_index += bytes_in;
62 : }
63 833 : }
64 :
65 : public:
66 388 : explicit buffered_reader(io::reader reader) : on_read(reader)
67 : {
68 388 : }
69 :
70 7087 : [[nodiscard]] auto view(size_t minimal_size) -> std::string_view
71 : {
72 7087 : minimal_size = std::max<size_t>(minimal_size, 1U);
73 7087 : if (bytes_in_buffer() < minimal_size)
74 833 : read_buffer();
75 :
76 7087 : return std::string_view(&buffer[begin_index], bytes_in_buffer());
77 : }
78 :
79 5607 : void skip(size_t size) noexcept
80 : {
81 5607 : assert(size <= bytes_in_buffer());
82 5607 : begin_index += static_cast<buffer_index_type>(size);
83 5607 : }
84 : };
85 :
86 : } // namespace spb::io
|