Initial commit
[yaffs-website] / node_modules / websocket-extensions / lib / pipeline / ring_buffer.js
1 'use strict';
2
3 var RingBuffer = function(bufferSize) {
4   this._buffer     = new Array(bufferSize);
5   this._bufferSize = bufferSize;
6   this._ringOffset = 0;
7   this._ringSize   = bufferSize;
8   this._head       = 0;
9   this._tail       = 0;
10   this.length      = 0;
11 };
12
13 RingBuffer.prototype.push = function(value) {
14   var expandBuffer = false,
15       expandRing   = false;
16
17   if (this._ringSize < this._bufferSize) {
18     expandBuffer = (this._tail === 0);
19   } else if (this._ringOffset === this._ringSize) {
20     expandBuffer = true;
21     expandRing   = (this._tail === 0);
22   }
23
24   if (expandBuffer) {
25     this._tail       = this._bufferSize;
26     this._buffer     = this._buffer.concat(new Array(this._bufferSize));
27     this._bufferSize = this._buffer.length;
28
29     if (expandRing)
30       this._ringSize = this._bufferSize;
31   }
32
33   this._buffer[this._tail] = value;
34   this.length += 1;
35   if (this._tail < this._ringSize) this._ringOffset += 1;
36   this._tail = (this._tail + 1) % this._bufferSize;
37 };
38
39 RingBuffer.prototype.peek = function() {
40   if (this.length === 0) return void 0;
41   return this._buffer[this._head];
42 };
43
44 RingBuffer.prototype.shift = function() {
45   if (this.length === 0) return void 0;
46
47   var value = this._buffer[this._head];
48   this._buffer[this._head] = void 0;
49   this.length -= 1;
50   this._ringOffset -= 1;
51
52   if (this._ringOffset === 0 && this.length > 0) {
53     this._head       = this._ringSize;
54     this._ringOffset = this.length;
55     this._ringSize   = this._bufferSize;
56   } else {
57     this._head = (this._head + 1) % this._ringSize;
58   }
59   return value;
60 };
61
62 module.exports = RingBuffer;