Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions .clang-format
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
BasedOnStyle: WebKit
Standard: Cpp11


AlignAfterOpenBracket: Align
AlignOperands: true
AlignTrailingComments: true
AllowShortFunctionsOnASingleLine: Inline
AlwaysBreakTemplateDeclarations: Yes
BraceWrapping:
AfterClass: true
AfterControlStatement: false
AfterEnum: false
AfterFunction: true
AfterNamespace: false
AfterObjCDeclaration: false
AfterStruct: true
AfterUnion: false
BeforeCatch: false
BeforeElse: false
IndentBraces: false
BreakBeforeBinaryOperators: NonAssignment
BreakBeforeBraces: Custom
BreakConstructorInitializers: BeforeColon
ColumnLimit: 100
ConstructorInitializerAllOnOneLineOrOnePerLine: true
ContinuationIndentWidth: 8
IndentPPDirectives: AfterHash
NamespaceIndentation: None
PointerBindsToType: false
SortIncludes: false
SpaceAfterTemplateKeyword: false
2 changes: 2 additions & 0 deletions .clang-tidy
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
---
Checks: 'bugprone-*,clang-analyzer-*,clang-diagnostic-*,modernize-*,performance-*,portability-*,readability-*'
10 changes: 10 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
root = true

[*.{cpp,hpp}]
charset = utf-8
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
indent_style = space
indent_size = 4
max_line_length = 100
14 changes: 14 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
cmake_minimum_required(VERSION 3.10 FATAL_ERROR)

project(CircularBuffer CXX)

include(CTest)

set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)

add_library(circularbuffer INTERFACE)
target_include_directories(circularbuffer INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/include)

add_subdirectory(test)
29 changes: 29 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,32 @@
3. Generic data type (e.g. uint8_t)
4. Two put(data) overflow behaviors: overwrite and discard data.
2. Write tests showing your circular buffer in action.

## Solution

### Design rationale

Since empty and full ring buffers both have `readPos == writePos`,
implementations have to find a small tradeoff between space utilization and runtime efficiency.
To resolve the ambiguity, they can either store `size - 1` elements and therefore waste one entry,
or they introduce separate state tracking, which complicates the implementation.

Since no further constraints were given in the objectives, it was decided to prefer the first approach.
In situations where memory was severely constrained, this would not be the best solution.

### Building and running

CMake (https://cmake.org) is used for building.
Tests can be executed by running `ctest`.

On Unix machines,
the following commands are sufficient:

```
$ mkdir build
$ cd build
$ cmake ..
...
$ cmake --build .
$ ctest -V
```
137 changes: 137 additions & 0 deletions include/core/CircularBuffer.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
#ifndef CORE_CIRCULAR_BUFFER_HPP_
#define CORE_CIRCULAR_BUFFER_HPP_

#include <array>
#include <cstdint>

namespace core {

/*!
* @brief Fixed size circular buffer.
*
* To simplify the implementation (and make it possible to change it to a * lock-free SPSC
* implementation), the capacity is size - 1. This way, no * separate tracking of the full or empty
* state is necessary.
*/
template<typename T, std::size_t Size>
class CircularBuffer
{
public:
using size_type = std::size_t;
using value_type = std::uint8_t;

/*!
* @brief Put a new element into the buffer, unless it is full.
*
* If the buffer is full, no other action is performed.
*
* @param value The element to put into the buffer.
*/
void putDiscard(T const &value);

/*!
* @brief Put a new element into the buffer.
*
* If the buffer is full, the oldest entry is overwritten.
*
* @param value The element to put into the buffer.
*/
void putOverwrite(T const &value);

/*!
* @brief Get the next element from the buffer.
*
* @param p Pointer to an element.
* @return {@c True} if an element was written into {@c p}, {@c false} if the buffer was empty.
*/
bool get(T *p);

/*!
* @brief Returns the number of elements currently in the buffer.
*
* @return The number of elements currently in the buffer.
*/
std::size_t size() const;

/*!
* @brief Returns the pointer to the raw data.
*
* @return A pointer to the raw data.
*/
constexpr T const *data() const { return m_data.data(); }

/*!
* @brief Returns the maximum number of elements that can be stored in the * buffer.
*
* @return The maximum number of elements.
*/
constexpr std::size_t capacity() const { return m_data.size() - 1; }

/*!
* @brief Returns {@c true} if the buffer is empty.
*
* @return {@c True} if the buffer is empty.
*/
constexpr bool empty() const { return m_readPos == m_writePos; }

private:
void doPut(T const &value);

std::array<T, Size> m_data {};
std::size_t m_readPos { 0 };
std::size_t m_writePos { 0 };
};

template<typename T, std::size_t Size>
std::size_t CircularBuffer<T, Size>::size() const
{
if (empty()) {
return 0;
}
if (m_writePos > m_readPos) {
return m_writePos - m_readPos;
}
return m_writePos + Size - m_readPos;
}

template<typename T, std::size_t Size>
void CircularBuffer<T, Size>::putDiscard(T const &value)
{
if (size() < capacity()) {
doPut(value);
}
}

template<typename T, std::size_t Size>
void CircularBuffer<T, Size>::putOverwrite(T const &value)
{
if (size() == capacity()) {
m_readPos = (m_readPos + 1) % Size;
}
doPut(value);
}

template<typename T, std::size_t Size>
bool CircularBuffer<T, Size>::get(T *p)
{
if (empty()) {
return false;
}
if (p != nullptr) {
*p = m_data[m_readPos];
}
m_readPos = (m_readPos + 1) % Size;
return true;
}

template<typename T, std::size_t Size>
void CircularBuffer<T, Size>::doPut(T const &value)
{
m_data[m_writePos] = value;
// might use '(m_writePos + 1) >> Size' if Size is a power of 2
m_writePos = (m_writePos + 1) % Size;
}

} // namespace core

#endif // CORE_CIRCULAR_BUFFER_HPP_
4 changes: 4 additions & 0 deletions test/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
add_executable(cbtest cbtest.cpp main.cpp)
target_link_libraries(cbtest PRIVATE circularbuffer)

add_test(NAME circular_buffer COMMAND cbtest)
Loading