// ring_buffer.cpp // A simple fixed‑size circular (ring) buffer for uint8_t values. #include // std::fill_n #include // std::size_t #include // demo output (optional) namespace had { // Alias matching the original code – unsigned 8‑bit type. using uint8_t = unsigned char; // Buffer capacity (must be a compile‑time constant). constexpr std::size_t bufferSize = 16; class RingBuffer { uint8_t data[bufferSize]; // storage array std::size_t newest_index; // position to write next byte std::size_t oldest_index; // position to read next byte std::size_t count; // number of bytes currently stored public: // Status codes returned by read/write operations. enum BufferStatus { OK, EMPTY, FULL }; // Constructor – clears the buffer and sets indices to 0. RingBuffer() noexcept : newest_index(0), oldest_index(0), count(0) { std::fill_n(data, bufferSize, 0); } // Write a byte into the buffer. BufferStatus bufferWrite(uint8_t byte) noexcept { if (count == bufferSize) return FULL; // no space left data[newest_index] = byte; newest_index = (newest_index + 1) % bufferSize; ++count; return OK; } // Read a byte from the buffer. BufferStatus bufferRead(uint8_t& byte) noexcept { if (count == 0) return EMPTY; // nothing to read byte = data[oldest_index]; oldest_index = (oldest_index + 1) % bufferSize; --count; return OK; } }; } // namespace had int main() { had::RingBuffer r_buffer; had::uint8_t tempCharStorage; // ------------------------------------------------- // Fill the buffer with consecutive letters starting at 'A'. // The loop stops when the buffer reports FULL. // ------------------------------------------------- for (int i = 0; r_buffer.bufferWrite(static_cast('A' + i)) == had::RingBuffer::OK; ++i) { // nothing else needed here } // ------------------------------------------------- // Read and display the contents until the buffer is EMPTY. // ------------------------------------------------- while (r_buffer.bufferRead(tempCharStorage) == had::RingBuffer::OK) { std::cout << static_cast(tempCharStorage) << ' '; } std::cout << '\n'; return 0; }