Mozzi  version v2.0
sound synthesis library for Arduino
CircularBuffer.h
1 /*
2  * CircularBuffer.h
3  *
4  * This file is part of Mozzi.
5  *
6  * Copyright 2014-2024 Tim Barrass and the Mozzi Team
7  *
8  * Mozzi is licensed under the GNU Lesser General Public Licence (LGPL) Version 2.1 or later.
9  *
10  */
11 
12 /*
13 Modified from https://en.wikipedia.org/wiki/Circular_buffer
14 Mirroring version
15 On 18 April 2014, the simplified version on the Wikipedia page for power of 2 sized buffers
16 doesn't work - cbIsEmpty() returns true whether the buffer is full or empty.
17 */
18 
19 #define MOZZI_BUFFER_SIZE 256 // do not expect to change and it to work.
20  // just here for forward compatibility if one day
21  // the buffer size might be editable
22 
23 /** Circular buffer object. Has a fixed number of cells, set to 256.
24 @tparam ITEM_TYPE the kind of data to store, eg. int, int8_t etc.
25 */
26 template <class ITEM_TYPE>
28 {
29 
30 public:
31  /** Constructor
32  */
34  {
35  }
36 
37  inline
38  bool isFull() {
39  return end == start && e_msb != s_msb;
40  }
41 
42  inline
43  bool isEmpty() {
44  return end == start && e_msb == s_msb;
45  }
46 
47  inline
48  void write(ITEM_TYPE in) {
49  items[end] = in;
50  //if (isFull()) cbIncrStart(); /* full, overwrite moves start pointer */
51  cbIncrEnd();
52  }
53 
54  inline
55  ITEM_TYPE read() {
56  ITEM_TYPE out = items[start];
57  cbIncrStart();
58  return out;
59  }
60 
61  inline
62  unsigned long count() {
63  return (num_buffers_read << 8) + start;
64  }
65  inline
66  ITEM_TYPE * address() {
67  return items;
68  }
69 
70 private:
71  ITEM_TYPE items[MOZZI_BUFFER_SIZE];
72  uint8_t start; /* index of oldest itement */
73  uint8_t end; /* index at which to write new itement */
74  uint8_t s_msb;
75  uint8_t e_msb;
76  unsigned long num_buffers_read;
77 
78 
79  inline
80  void cbIncrStart() {
81  start++;
82  if (start == 0) {
83  s_msb ^= 1;
84  num_buffers_read++;
85  }
86  }
87 
88  inline
89  void cbIncrEnd() {
90  end++;
91  if (end == 0) e_msb ^= 1;
92  }
93 
94 };