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

73
LINES

< > BotCompany Repo | #1025789 // SimpleCircularBuffer (synchronized)

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

Transpiled version (10025L) is out of date.

// Has long indices!
persistable sclass SimpleCircularBuffer<A> is Iterable<A>, IntSize {
  A[] buffer;
  long base; // elements dropped due to overcapacity
  int size;  // elements actually contained
  
  *(int capacity) {
    buffer = (A[]) new O[capacity];
  }
  
  synchronized void add(A a) {
    if (size == buffer.length) {
      --size;
      ++base;
    }
    buffer[(int) ((base+size) % buffer.length)] = a;
    ++size;
  }
  
  synchronized A get(long pos) {
    if (pos < base || pos >= base+size) null;
    ret buffer[(int) (pos % buffer.length)];
  }
  
  synchronized A getFromBase(long pos) {
    ret get(pos+base);
  }
  
  public synchronized int size() {
    ret size;
  }
  
  public Iterator<A> iterator() {
    ret new ItIt<A> {
      long i;
      public bool hasNext() { ret i < size(); }
      public A next() { ret get(base + (i++)); }
    };
  }
  
  synchronized int capacity() {
    ret buffer.length;
  }
  
  synchronized bool isFull() {
    ret size() == capacity();
  }
  
  public bool isEmpty() {
    ret size() == 0;
  }
  
  synchronized long getBase aka base() {
    ret base;
  }
  
  // pop first actually contained element
  synchronized A popFirst aka remove() {
    if (isEmpty()) null;
    A a = get(base);
    --size;
    ++base;
    ret a;
  }
  
  synchronized A nextToLast() { ret get(base+size-2); }
  synchronized A last() { ret get(base+size-1); }
  synchronized A first() { ret get(base); }
  
  L<A> asList() {
    ret main asList(this);
  }
}

download  show line numbers  debug dex  old transpilations   

Travelled to 6 computer(s): bhatertpkbcr, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tvejysmllsmz, vouqrxazstgt

No comments. add comment

Snippet ID: #1025789
Snippet name: SimpleCircularBuffer (synchronized)
Eternal ID of this version: #1025789/25
Text MD5: f012b243829fb1036f45bd91b51a7010
Author: stefan
Category: javax
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2022-12-20 23:10:09
Source code size: 1570 bytes / 73 lines
Pitched / IR pitched: No / No
Views / Downloads: 331 / 885
Version history: 24 change(s)
Referenced in: #1026626 - CircularByteBuffer
#1034167 - Standard Classes + Interfaces (LIVE, continuation of #1003674)