Important changes to repositories hosted on mbed.com
Mbed hosted mercurial repositories are deprecated and are due to be permanently deleted in July 2026.
To keep a copy of this software download the repository Zip archive or clone locally using Mercurial.
It is also possible to export all your personal repositories from the account settings page.
Diff: CircularBuffer.h
- Revision:
- 3:1a33490e1990
- Parent:
- 2:4080c1770d51
- Child:
- 4:13b626890ad4
--- a/CircularBuffer.h Sun Aug 05 22:18:39 2012 +0000
+++ b/CircularBuffer.h Mon Aug 06 06:13:11 2012 +0000
@@ -4,71 +4,92 @@
template <typename T, int S>
-class CircularBuffer
-{
+class CircularBuffer {
public:
- CircularBuffer() { currentIndex = 0; }
+ CircularBuffer() {
+ headIndex = 0;
+ }
T read(int index);
T& operator[](int index);
void write(T value, int index);
void push(T value);
void revert(int amount);
-
+
protected:
T data[S];
- int currentIndex;
+ int headIndex;
inline int getRealIndex(int i);
};
+/* getRealIndex()
+ *
+ * Translates head-based indices into absolute indices.
+ * Private function used by other members.
+ */
template <typename T, int S>
-inline int CircularBuffer<T, S>::getRealIndex(int index)
-{
- int realIndex = (currentIndex - index) % S;
+inline int CircularBuffer<T, S>::getRealIndex(int index) {
+ int realIndex = (headIndex - index) % S;
if (realIndex < 0) realIndex += S;
return realIndex;
}
+/* read(int index)
+ *
+ * Returns the object stored at a given index.
+ */
template <typename T, int S>
-inline T CircularBuffer<T, S>::read(int index)
-{
+inline T CircularBuffer<T, S>::read(int index) {
return data[getRealIndex(index)];
}
+/* operator[int index]
+ *
+ * Returns a reference to the object stored at a given index.
+ */
template <typename T, int S>
-inline T& CircularBuffer<T, S>::operator[](int index)
-{
+inline T& CircularBuffer<T, S>::operator[](int index) {
return data[getRealIndex(index)];
}
+/* write(T value, int index)
+ *
+ * Sets the value of the object stored at the given index.
+ */
template <typename T, int S>
-inline void CircularBuffer<T, S>::write(T value, int index)
-{
+inline void CircularBuffer<T, S>::write(T value, int index) {
data[getRealIndex(index)] = value;
}
+/* push(T value)
+ *
+ * Pushes the given value to the head of the buffer.
+ * Moves the head forward.
+ */
template <typename T, int S>
-inline void CircularBuffer<T, S>::push(T value)
-{
- currentIndex = ++currentIndex % S;
- data[currentIndex] = value;
+inline void CircularBuffer<T, S>::push(T value) {
+ headIndex = ++headIndex % S;
+ data[headIndex] = value;
}
+/* revert(int amount)
+ *
+ * Pushes the head back by a given amount.
+ */
template <typename T, int S>
-inline void CircularBuffer<T, S>::revert(int amount)
-{
- currentIndex = currentIndex >= amount ? currentIndex - amount : currentIndex - amount + S;
+inline void CircularBuffer<T, S>::revert(int amount) {
+ headIndex = headIndex >= amount ? headIndex - amount : headIndex - amount + S;
}
