From 10a8fc68678a644cff762ad25651106de862dd6a Mon Sep 17 00:00:00 2001 From: Ahmet Inan Date: Fri, 17 Apr 2020 01:10:00 +0200 Subject: [PATCH] added bip buffer --- README.md | 19 +++++++++++++++++++ bip_buffer.hh | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 bip_buffer.hh diff --git a/README.md b/README.md index 86bcfde..16a366d 100644 --- a/README.md +++ b/README.md @@ -104,6 +104,25 @@ The [simple moving average](https://en.wikipedia.org/wiki/Moving_average#Simple_ * SMA3 is based on SMA2 but uses the [Kahan summation algorithm](https://en.wikipedia.org/wiki/Kahan_summation_algorithm) to reduce drift significantly. * SMA4 uses a tree and only update nodes that depend on the new input value and is slower than SMA3 but it has no drift. +### [bip_buffer.hh](bip_buffer.hh) + +The [Bip buffer](https://en.wikipedia.org/wiki/Circular_buffer#Fixed-length-element_and_contiguous-block_circular_buffer) provides contiguous block access to the last N value stored in a circular buffer. + +Example: +``` +DSP::BipBuffer history; +*snip* +const TYPE *buf = history(new_value); +*snip* +TYPE newest_value = buf[NUM-1]; +TYPE previous_value = buf[NUM-2]; +TYPE oldest_value = buf[0]; +*snip* +DSP::FastFourierTransform fwd; +TYPE out[NUM]; +fwd(out, history(another_value)); +``` + ### [calculus.hh](calculus.hh) Some [calculus](https://en.wikipedia.org/wiki/Calculus) functions: diff --git a/bip_buffer.hh b/bip_buffer.hh new file mode 100644 index 0000000..ca0f9bc --- /dev/null +++ b/bip_buffer.hh @@ -0,0 +1,34 @@ +/* +Bip buffer + +Copyright 2020 Ahmet Inan +*/ + +#pragma once + +namespace DSP { + +template +class BipBuffer +{ + TYPE buf[2*NUM]; + int pos0, pos1; +public: + BipBuffer() : pos0(0), pos1(NUM) + { + for (int i = 0; i < 2*NUM; ++i) + buf[i] = 0; + } + const TYPE *operator () (TYPE input) + { + buf[pos0] = buf[pos1] = input; + if (++pos0 >= 2*NUM) + pos0 = 0; + if (++pos1 >= 2*NUM) + pos1 = 0; + return buf + min(pos0, pos1); + } +}; + +} +