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

Method write

ch6-ring-buffer/ring-buffer.js:31–58  ·  view source on GitHub ↗
(data /*: Uint8Array */)

Source from the content-addressed store, hash-verified

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) {
61 if (bytes > this.length) { // <1>

Callers 8

happycoin.mjsFile · 0.45
happycoin.jsFile · 0.45
actor.jsFile · 0.45
handlerFunction · 0.45
writeMethod · 0.45
ring-buffer.jsFile · 0.45

Calls

no outgoing calls

Tested by

no test coverage detected