TaskManagerIO
Loading...
Searching...
No Matches
SCCircularBuffer.h
Go to the documentation of this file.
1/*
2 * Copyright (c) 2018 https://www.thecoderscorner.com (Dave Cherry)
3 * This product is licensed under an Apache license, see the LICENSE file in the top-level directory.
4 */
5
6#ifndef TASKMANAGERIO_CIRCULARBUFFER_H
7#define TASKMANAGERIO_CIRCULARBUFFER_H
8
9#include <string.h>
10#include <inttypes.h>
11#include "TaskPlatformDeps.h"
12using namespace tm_internal;
13
18
19namespace tccollection {
20
30
31 template<class T> class GenericCircularBuffer {
32 public:
33 enum BufferType { CIRCULAR_BUFFER, MEMORY_POOL };
34
35#ifdef SC_DEBUG_CHECKER
36 volatile uint32_t casExchangeSpins = 0;
37#endif
38
39 private:
40 position_t readerPosition;
41 position_t writerPosition;
42 const uint16_t bufferSize;
43 T *const buffer;
44 bool actingAsMemoryPool;
45
46 public:
47 explicit GenericCircularBuffer(uint16_t size, BufferType asMemPool = CIRCULAR_BUFFER) : readerPosition(0), writerPosition(0),
48 bufferSize(size), buffer(new T[size]), actingAsMemoryPool(asMemPool) {}
49 ~GenericCircularBuffer() { delete[] buffer; }
50
51 [[nodiscard]] bool available() const { return actingAsMemoryPool || readerPosition != writerPosition; }
52 void put(const T& by) { buffer[nextPosition(&writerPosition)] = by; }
53 T& get() { return buffer[nextPosition(&readerPosition)]; }
54
55 int16_t nextPosition(position_ptr_t positionPtr) {
56 bool successfullyUpdated = false;
57 position_t existing;
58 while(!successfullyUpdated) {
59 existing = atomicRead32(positionPtr);
60 position_t newPos = existing + 1;
61 if (newPos >= bufferSize) {
62 newPos = 0;
63 }
64 successfullyUpdated = atomicSwap32(positionPtr, existing, newPos);
65#ifdef SC_DEBUG_CHECKER
66 if(!successfullyUpdated) casExchangeSpins++;
67#endif
68 }
69 return existing;
70 }
71 };
72
73 class SCCircularBuffer {
74 private:
75 position_t readerPosition;
76 position_t writerPosition;
77 const uint16_t bufferSize;
78 uint8_t *const buffer;
79
80 public:
81 explicit SCCircularBuffer(uint16_t size);
82
83 ~SCCircularBuffer();
84
85 [[nodiscard]] bool available() const { return readerPosition != writerPosition; }
86
87 void put(uint8_t by);
88
89 uint8_t get();
90
91 private:
92 uint16_t nextPosition(position_ptr_t by) const;
93 };
94
95}
96
97
98
99#endif
provides the platform specific configuration for task manager