Skip to content

Commit c962913

Browse files
committed
Add assertion to make CounterType consistent with BufferSize.
CounterType is used to define type of _head and _tail counters. This may cause the following problems: - counters are used as array indexes so only unsigned types should be used for counters, - CounterType must be consistent with BufferSize and BufferSize is of uint32_t type (i.e. Circular Buffer with the following parameters: BufferSize = 1000, CounterType = unsigned char will not work properly).
1 parent 47bae16 commit c962913

File tree

1 file changed

+28
-1
lines changed

1 file changed

+28
-1
lines changed

platform/CircularBuffer.h

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,23 @@
1919
#include "platform/mbed_critical.h"
2020

2121
namespace mbed {
22+
23+
namespace internal {
24+
/* Detect if CounterType of the Circular buffer is of unsigned type. */
25+
template<typename T>
26+
struct is_unsigned { static const bool value = false; };
27+
template<>
28+
struct is_unsigned<unsigned char> { static const bool value = true; };
29+
template<>
30+
struct is_unsigned<unsigned short> { static const bool value = true; };
31+
template<>
32+
struct is_unsigned<unsigned int> { static const bool value = true; };
33+
template<>
34+
struct is_unsigned<unsigned long> { static const bool value = true; };
35+
template<>
36+
struct is_unsigned<unsigned long long> { static const bool value = true; };
37+
};
38+
2239
/** \addtogroup platform */
2340
/** @{*/
2441
/**
@@ -29,11 +46,22 @@ namespace mbed {
2946
/** Templated Circular buffer class
3047
*
3148
* @note Synchronization level: Interrupt safe
49+
* @note CounterType must be unsigned and consistent with BufferSize
3250
*/
3351
template<typename T, uint32_t BufferSize, typename CounterType = uint32_t>
3452
class CircularBuffer {
3553
public:
3654
CircularBuffer() : _head(0), _tail(0), _full(false) {
55+
MBED_STATIC_ASSERT(
56+
internal::is_unsigned<CounterType>::value,
57+
"CounterType must be unsigned"
58+
);
59+
60+
MBED_STATIC_ASSERT(
61+
(sizeof(CounterType) >= sizeof(uint32_t)) ||
62+
(BufferSize < (((uint64_t) 1) << (sizeof(CounterType) * 8))),
63+
"Invalid BufferSize for the CounterType"
64+
);
3765
}
3866

3967
~CircularBuffer() {
@@ -140,4 +168,3 @@ class CircularBuffer {
140168
}
141169

142170
#endif
143-

0 commit comments

Comments
 (0)