Skip to content

Commit d2d7924

Browse files
committed
Fix FIFObuffer::get()
- Prevent actual_index being calculated as negative Add test_FIFObuffer_push_and_get
1 parent 827d572 commit d2d7924

File tree

4 files changed

+23
-8
lines changed

4 files changed

+23
-8
lines changed

README.md

-3
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,6 @@ Changes made:
88
- Added extra methods
99
- You can change the type and size of the buffer
1010

11-
Known issues/TODO:
12-
- `FIFObuffer::get()` doesn't work properly
13-
1411
# Explanation
1512

1613
https://en.wikipedia.org/wiki/FIFO_(computing_and_electronics)

platformio.ini

+2-1
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,5 @@
22
build_flags = -std=c++14
33

44
[env:native]
5-
platform = native
5+
platform = native
6+
debug_test = *

src/FIFObuffer.cpp

+3-1
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,9 @@ void FIFObuffer<T, FIFOsize>::clear() {
114114

115115
template<typename T, int FIFOsize>
116116
T FIFObuffer<T, FIFOsize>::get(int index) {
117-
int actual_index = (tail - index) % FIFOsize;
117+
// we add FIFOsize to (tail - index) to make sure actual_index never goes negative
118+
// as you can't have a negative index of an array
119+
int actual_index = (FIFOsize + tail - index) % FIFOsize;
118120
return buffer[actual_index];
119121
}
120122

test/test_FIFObuffer.cpp

+18-3
Original file line numberDiff line numberDiff line change
@@ -64,8 +64,13 @@ void test_FIFObuffer_sum() {
6464
FIFObuffer<int, 3> buffer;
6565
buffer.put(1);
6666
buffer.put(2);
67-
buffer.put(3);
67+
buffer.push(3);
6868
TEST_ASSERT_EQUAL(6, buffer.sum());
69+
70+
FIFObuffer<int, 3> buffer2;
71+
buffer2.put(1);
72+
buffer2.put(2);
73+
TEST_ASSERT_EQUAL(3, buffer2.sum());
6974
}
7075

7176
void test_FIFObuffer_clear() {
@@ -79,17 +84,27 @@ void test_FIFObuffer_clear() {
7984
TEST_ASSERT_EQUAL(10, buffer.sum());
8085
}
8186

87+
void test_FIFObuffer_push_and_get() {
88+
FIFObuffer<int, 2> buffer;
89+
buffer.put(0);
90+
buffer.put(1);
91+
buffer.push(2);
92+
TEST_ASSERT_EQUAL(2, buffer.get(0));
93+
TEST_ASSERT_EQUAL(1, buffer.get(1));
94+
}
95+
8296
int main(int args, char **argv) {
8397
UNITY_BEGIN();
84-
98+
RUN_TEST(test_FIFObuffer_push_and_get);
8599
RUN_TEST(test_FIFObuffer_count);
86100
RUN_TEST(test_FIFObuffer_full_empty);
87101
RUN_TEST(test_FIFObuffer_order);
88102
RUN_TEST(test_FIFObuffer_put);
89103
RUN_TEST(test_FIFObuffer_push);
90-
RUN_TEST(test_FIFObuffer_get);
91104
RUN_TEST(test_FIFObuffer_sum);
92105
RUN_TEST(test_FIFObuffer_clear);
106+
RUN_TEST(test_FIFObuffer_get);
107+
93108

94109
UNITY_END();
95110

0 commit comments

Comments
 (0)