deprecate SCViewHolder-layRight
[supercollider.git] / SCClassLibrary / Common / Collections / RingBuffer.sc
blobcd6027ba42fa07ad54b4a76e299a5e0abc839849
1 // Fixed size ringbuffer
2 RingBuffer : SequenceableCollection
4         var <array, <readPos, <writePos;
6         *new { | size, collectionClass(Array) |
7                 ^this.newCopyArgs(collectionClass.newClear(size), 0, 0)
8         }
10         // return maximum capacity.
11         maxSize {
12                 ^array.size
13         }
14         // return number of readable items.
15         size {
16                 ^this.readable
17         }
19         // return number of readble items.
20         readable {
21                 ^if (readPos <= writePos)
22                 { writePos - readPos }
23                 { array.size - readPos + writePos }
24         }
25         // return number of writable items.
26         writable {
27                 ^array.size - this.readable - 1
28         }
30         // add value and increase writePos.
31         // do nothing if no items can be written.
32         add { | value |
33                 if (this.writable > 0) {
34                         array.put(writePos, value);
35                         writePos = (writePos + 1) % array.size;
36                 }
37         }
38         // return next readable item and increase readPos.
39         // return nil if no items can be read.
40         pop {
41                 var result;
42                 if (this.readable > 0) {
43                         result = array.at(readPos);
44                         readPos = (readPos + 1) % array.size;
45                 };
46                 ^result
47         }
48         // add value and increase writePos by overwriting oldest readable
49         // item.
50         overwrite { | value |
51                 var result;
52                 if (this.writable == 0) {
53                         result = this.pop;
54                 };
55                 this.add(value);
56                 ^result
57         }
59         // iterate over the currently readable items.
60         do { | function |
61                 var n = this.readable, i = 0;
62                 while { i < n } {
63                         function.value(array.wrapAt(readPos + i), i);
64                         i = i + 1;
65                 }
66         }