Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

81
LINES

< > BotCompany Repo | #1000774 // CircularFifoBuffer

JavaX fragment (include) [tags: use-pretranspiled]

Libraryless. Click here for Pure Java version (10074L/55K).

sclass CircularFifoBuffer<E> is Iterable<E>, IntSize {
  int capacity;
  long base;
  ArrayDeque<E> storage;
  
  public CircularFifoBuffer(int capacity) {
    this.capacity = capacity;
    storage = new ArrayDeque<E>(capacity);
  }
  
  /**
   * Adds the given element to the buffer. If the buffer is full, the least recently added element is discarded so
   * that a new element can be inserted.
   */
  public void add(E e) {
    if (isFull()) remove();
    storage.addLast(e);
  }
  
  /**
   * Removes and returns the least recently inserted element from this buffer.
   */
  public E remove() {
    ++base;
    return storage.removeFirst();
  }
  
  /**
   * Returns true iff the buffers remaining capacity is 0.
   */
  public boolean isFull() {
    return storage.size() == capacity;
  }
  
  /**
   * Returns true iff the buffers size is 0.
   */
  public boolean isEmpty() {
    return storage.isEmpty();
  }
  
  /**
   * Returns the number of elements in the buffer.
   */
  public int size() {
    return storage.size();
  }
  
  public Object[] toArray() {
    return storage.toArray();
  }
  
  public<T> T[] toArray(T[] a) {
    return storage.toArray(a);
  }
  
  public List<E> asList() {
    return new ArrayList<E>(storage);
  }
  
  public ArrayDeque getBackingStore() {
    return storage;
  }
  
  public Iterator<E> iterator() {
    return storage.iterator();
  }
  
  public E last() {
    ret storage.peekLast();
  }
  
  void removeToSize(int size) {
    while (size() > max(size, 0)) remove();
  }
  
  // how many elements were discarded
  long getBase() { ret base; }
  
  int getCapacity() { ret capacity; }
}

Author comment

from https://raw.githubusercontent.com/OliverColeman/ahni/master/src/com/ojcoleman/ahni/util/CircularFifoBuffer.java

download  show line numbers  debug dex  old transpilations   

Travelled to 13 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, gwrvuhgaqvyk, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tslmcundralx, tvejysmllsmz, vouqrxazstgt

No comments. add comment

Snippet ID: #1000774
Snippet name: CircularFifoBuffer
Eternal ID of this version: #1000774/7
Text MD5: 328851bf6ac32c141f72e56f5ee033d8
Transpilation MD5: aaaaa41f993396d293e3b71d7e3542c5
Author: stefan
Category:
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2022-12-12 02:16:55
Source code size: 1720 bytes / 81 lines
Pitched / IR pitched: No / No
Views / Downloads: 698 / 1678
Version history: 6 change(s)
Referenced in: [show references]