MCPcopy Create free account
hub / github.com/MultithreadedJSBook/code-samples / RingBuffer

Class RingBuffer

ch6-ring-buffer/ring-buffer.js:1–85  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1class RingBuffer {
2 constructor(meta/*: Uint32Array[3]*/, buffer /*: Uint8Array */) {
3 this.meta = meta;
4 this.buffer = buffer;
5 }
6
7 get head() {
8 return this.meta[0];
9 }
10
11 set head(n) {
12 this.meta[0] = n;
13 }
14
15 get tail() {
16 return this.meta[1];
17 }
18
19 set tail(n) {
20 this.meta[1] = n;
21 }
22
23 get length() {
24 return this.meta[2];
25 }
26
27 set length(n) {
28 this.meta[2] = n;
29 }
30
31 write(data /*: Uint8Array */) { // <1>
32 let bytesWritten = data.length;
33 if (bytesWritten > this.buffer.length - this.length) { // <2>
34 bytesWritten = this.buffer.length - this.length;
35 data = data.subarray(0, bytesWritten);
36 }
37 if (bytesWritten === 0) {
38 return bytesWritten;
39 }
40 if (
41 (this.head >= this.tail && this.buffer.length - this.head >= bytesWritten) ||
42 (this.head < this.tail && bytesWritten <= this.tail - this.head) // <3>
43 ) {
44 // Enough space after the head. Just write it in and increase the head.
45 this.buffer.set(data, this.head);
46 this.head += bytesWritten;
47 } else { // <4>
48 // We need to split the chunk into two.
49 const endSpaceAvailable = this.buffer.length - this.head;
50 const endChunk = data.subarray(0, endSpaceAvailable);
51 const beginChunk = data.subarray(endSpaceAvailable);
52 this.buffer.set(endChunk, this.head);
53 this.buffer.set(beginChunk, 0);
54 this.head = beginChunk.length;
55 }
56 this.length += bytesWritten;
57 return bytesWritten;
58 }
59
60 read(bytes) {

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected