6 // control protocol buffer, a circular buffer with 1024-byte capacity.
11 int length = 0; // number of elements in the buffer
14 int get_length() noexcept
19 // fill by reading from the given fd, return positive if some was read or -1 on error.
20 int fill(int fd) noexcept
22 int pos = cur_idx + length;
23 if (pos >= 1024) pos -= 1024;
24 int max_count = std::min(1024 - pos, 1024 - length);
25 ssize_t r = read(fd, buf + pos, max_count);
32 // fill by readin from the given fd, until at least the specified number of bytes are in
33 // the buffer. Return 0 if end-of-file reached before fill complete, or -1 on error.
34 int fillTo(int fd, int rlength) noexcept
36 while (length < rlength) {
43 int operator[](int idx) noexcept
45 int dest_idx = cur_idx + idx;
46 if (dest_idx > 1024) dest_idx -= 1024;
50 void consume(int amount) noexcept
53 if (cur_idx >= 1024) cur_idx -= 1024;
57 void extract(char *dest, int index, int length) noexcept
60 if (index >= 1024) index -= 1024;
61 if (index + length > 1024) {
63 int half = 1024 - index;
64 std::memcpy(dest, buf + index, half);
65 std::memcpy(dest + half, buf, length - half);
68 std::memcpy(dest, buf + index, length);
72 // Extract string of give length from given index
73 // Throws: std::bad_alloc on allocation failure
74 std::string extract_string(int index, int length)
77 if (index >= 1024) index -= 1024;
78 if (index + length > 1024) {
79 std::string r(buf + index, 1024 - index);
80 r.insert(r.end(), buf, buf + length - (1024 - index));
84 return std::string(buf + index, length);