diff --git a/firmware/util/cyclic_buffer.h b/firmware/util/cyclic_buffer.h index 5215943698..edc673d1cf 100644 --- a/firmware/util/cyclic_buffer.h +++ b/firmware/util/cyclic_buffer.h @@ -37,6 +37,7 @@ class cyclic_buffer T get(int index); T sum(int length); T maxValue(int length); + T minValue(int length); void setSize(int size); int getSize(); void clear(); @@ -131,7 +132,7 @@ T cyclic_buffer::maxValue(int length) { length = count; } int ci = currentIndex; // local copy to increase thread-safety - T result = 0; // todo: better min value? + T result = -2000000; // todo: better min value? for (int i = 0; i < length; ++i) { int index = ci - i; while (index < 0) { @@ -142,7 +143,26 @@ T cyclic_buffer::maxValue(int length) { result = elements[index]; } } + return result; +} +template +T cyclic_buffer::minValue(int length) { + if (length > count) { + length = count; + } + int ci = currentIndex; // local copy to increase thread-safety + T result = +2000000; // todo: better max value? + for (int i = 0; i < length; ++i) { + int index = ci - i; + while (index < 0) { + index += size; + } + + if (elements[index] < result) { + result = elements[index]; + } + } return result; } diff --git a/unit_tests/test_util.cpp b/unit_tests/test_util.cpp index 7ffa916d86..d50f0b6f90 100644 --- a/unit_tests/test_util.cpp +++ b/unit_tests/test_util.cpp @@ -73,6 +73,8 @@ void testCyclicBuffer(void) { assertEquals(4, sb.maxValue(3)); assertEquals(4, sb.maxValue(113)); + assertEquals(2, sb.minValue(3)); + assertEquals(1, sb.minValue(113)); } }