Created
August 11, 2015 19:24
-
-
Save JackStouffer/49707a0ad440a93a5202 to your computer and use it in GitHub Desktop.
A simple ring buffer implementation in D with unit tests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import std.traits : isNumeric; | |
struct RingBuffer (T, uint buffer_length = 4) if (isNumeric!T) { | |
private T[buffer_length] buffer; | |
private T sum; | |
private byte lastIndex; | |
@safe @nogc nothrow pure { | |
this(const T initial_value) { | |
this.lastIndex = 0; | |
reset(initial_value); | |
} | |
void reset(const T value) { | |
this.sum = value * this.buffer.length; | |
for (byte i = 0; i < this.buffer.length; ++i) { | |
this.buffer[i] = value; | |
} | |
} | |
void pushValue(const T value) { | |
this.sum -= this.buffer[this.lastIndex]; // subtract the oldest sample from the sum | |
this.sum += value; // add the new sample | |
this.buffer[this.lastIndex] = value; // store the new sample | |
// advance the index and wrap it around | |
this.lastIndex += 1; | |
if (this.lastIndex >= buffer_length) { | |
this.lastIndex = 0; | |
} | |
} | |
T smoothValue() const @property { | |
return this.sum / buffer_length; | |
} | |
} | |
} unittest { | |
auto buffer = RingBuffer!float(0); | |
buffer.pushValue(10); | |
buffer.pushValue(20); | |
buffer.pushValue(30); | |
buffer.pushValue(40); | |
assert(buffer.smoothValue == 25); | |
buffer.pushValue(50); | |
buffer.pushValue(60); | |
assert(buffer.smoothValue == 45); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment