Merge branch 'master' of github.com:poolifier/poolifier
[poolifier.git] / src / circular-buffer.ts
index cbe733d8f2d0841e27a0773a81a5d17d735c9adc..2975ef7797389b2cb370c0184de493c81fe85ed7 100644 (file)
@@ -1,43 +1,86 @@
 /**
- * Default buffer size
+ * Default buffer size.
  */
 export const defaultBufferSize = 2048
 
 /**
- * Circular buffer
+ * Circular buffer.
+ *
+ * @typeParam T - Type of buffer data.
+ * @internal
  */
 export class CircularBuffer<T> {
-  private readonly readIdx: number
+  private readIdx: number
   private writeIdx: number
   private items: Array<T | undefined>
   private readonly maxArrayIdx: number
+  /* Buffer number of elements */
+  public size: number
 
   /**
-   * @param size - Buffer size
-   * @returns CircularBuffer
+   * @param size - Buffer size. @defaultValue defaultBufferSize
+   * @returns CircularBuffer.
    */
   constructor (size: number = defaultBufferSize) {
     this.checkSize(size)
     this.readIdx = 0
     this.writeIdx = 0
     this.maxArrayIdx = size - 1
+    this.size = 0
     this.items = new Array<T | undefined>(size)
   }
 
   /**
-   * Puts data into buffer
+   * Checks whether the buffer is empty.
    *
-   * @param data - Data to push
+   * @returns Whether the buffer is empty.
+   */
+  public empty (): boolean {
+    return this.size === 0
+  }
+
+  /**
+   * Checks whether the buffer is full.
+   *
+   * @returns Whether the buffer is full.
+   */
+  public full (): boolean {
+    return this.size === this.items.length
+  }
+
+  /**
+   * Puts data into buffer.
+   *
+   * @param data - Data to put into buffer.
    */
   public put (data: T): void {
     this.items[this.writeIdx] = data
     this.writeIdx = this.writeIdx === this.maxArrayIdx ? 0 : this.writeIdx + 1
+    if (this.size < this.items.length) {
+      ++this.size
+    }
+  }
+
+  /**
+   * Gets data from buffer.
+   *
+   * @returns Data from buffer.
+   */
+  public get (): T | undefined {
+    const data = this.items[this.readIdx]
+    if (data == null) {
+      return
+    }
+    this.items[this.readIdx] = undefined
+    this.readIdx = this.readIdx === this.maxArrayIdx ? 0 : this.readIdx + 1
+    --this.size
+    return data
   }
 
   /**
-   * Returns buffer as array
+   * Returns buffer as array.
    *
-   * @returns T[]
+   * @returns Array of buffer data.
    */
   public toArray (): T[] {
     return this.items.filter(item => item != null) as T[]