1.. _module-pw_ring_buffer: 2 3-------------- 4pw_ring_buffer 5-------------- 6The ``pw_ring_buffer`` module will eventually provide several ring buffer 7implementations, each with different tradeoffs. 8 9This documentation is incomplete :) 10 11Compatibility 12============= 13* C++14 14 15Iterator 16======== 17In crash contexts, it may be useful to scan through a ring buffer that may 18have a mix of valid (yet to be read), stale (read), and invalid entries. The 19`PrefixedEntryRingBufferMulti::iterator` class can be used to walk through 20entries in the provided buffer. 21 22.. code-block:: cpp 23 24 // A test string to push into the buffer. 25 constexpr char kExampleEntry[] = "Example!"; 26 27 // Setting up buffers and attaching a reader. 28 std::byte buffer[1024]; 29 std::byte read_buffer[256]; 30 PrefixedEntryRingBuffer ring_buffer(buffer); 31 PrefixedEntryRingBuffer::Reader reader; 32 ring_buffer.AttachReader(reader); 33 34 // Insert some entries and process some entries. 35 ring_buffer.PushBack(kExampleEntry); 36 ring_buffer.PushBack(kExampleEntry); 37 reader.PopFront(); 38 39 // !! A function causes a crash before we've read out all entries. 40 FunctionThatCrashes(); 41 42 // ... Crash Context ... 43 44 // You can use a range-based for-loop to walk through all entries. 45 for (auto entry : ring_buffer) { 46 PW_LOG_WARN("Read entry of size: %lu", entry.size()); 47 } 48 49In cases where a crash has caused the ring buffer to have corrupted data, the 50iterator will progress until it sees the corrupted section and instead move to 51`iterator::end()`. The `iterator::status()` function returns a `pw::Status` 52indicating the reason the iterator reached it's end. 53 54.. code-block:: cpp 55 56 // ... Crash Context ... 57 58 using iterator = PrefixedEntryRingBufferMulti::iterator; 59 60 // Hold the iterator outside any loops to inspect it later. 61 iterator it = ring_buffer.begin(); 62 for (; it != it.end(); ++it) { 63 PW_LOG_WARN("Read entry of size: %lu", it->size()); 64 } 65 66 // Warn if there was a failure during iteration. 67 if (!it.status().ok()) { 68 PW_LOG_WARN("Iterator failed to read some entries!"); 69 } 70 71Data corruption 72=============== 73``PrefixedEntryRingBufferMulti`` offers a circular ring buffer for arbitrary 74length data entries. Some metadata bytes are added at the beginning of each 75entry to delimit the size of the entry. Unlike the iterator, the methods in 76``PrefixedEntryRingBufferMulti`` require that data in the buffer is not corrupt. 77When these methods encounter data corruption, there is no generic way to 78recover, and thus, the application crashes. Data corruption is indicative of 79other issues. 80 81Dependencies 82============ 83* ``pw_span`` 84* ``pw_containers`` - for tests only 85