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

69
LINES

< > BotCompany Repo | #1029225 // ChunkedLongList - stored in fixed-size chunks

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

Libraryless. Click here for Pure Java version (2816L/18K).

final sclass ChunkedLongList extends RandomAccessAbstractList<Long> {
  int chunkShift = 16; // => chunkSize = 65536
  new ArrayList<long[]> chunks;
  int actualChunks; // roughly keep track of chunk list's internal capacity so we can shrink in time
  int size;
  
  public void add(long i) {
    ensureCapacityInternal(size+1);
    set(size, i);
    ++size;
  }
  
  public Long set(int i, Long value) {
    ret set(i, (long) value);
  }
  
  public long set(int i, long value) {
    long[] chunk = chunks.get(i >> chunkShift);
    int idx = i & (chunkSize()-1);
    long old = chunk[idx];
    chunk[idx] = value;
    ret old;
  }
  
  public bool add(Long i) {
    add((long) i);
    true;
  }
  
  public int size() { ret size; }
  
  public Long get(int i) {
    ret getPrimitive(i);
  }
  
  public long getPrimitive(int i) {
    if (i >= 0 && i < size) ret chunks.get(i >> chunkShift)[i & (chunkSize()-1)];
    throw new IndexOutOfBoundsException(i + "/" + size);
  }
  
  void ensureCapacityInternal(int minCapacity) {
    while (l(chunks) << chunkShift < minCapacity) {
      chunks.add(new long[chunkSize()]);
      actualChunks = max(actualChunks, l(chunks));
    }
  }
  
  long[] toLongArray() {
    long[] a = new long[size];
    int i = 0;
    for (long[] chunk : chunks) {
      System.arraycopy(chunk, 0, a, i, min(chunk.length, size-i));
      i += chunk.length;
    }
    ret a;
  }
  
  int chunkSize() { ret 1 << chunkShift; }
  
  void truncateAt(int idx) {
    size = idx;
    while (size <= (l(chunks)-1) << chunkShift)
      popLast(chunks);
    if (l(chunks)*2 < actualChunks) {
      chunks.trimToSize();
      actualChunks = l(chunks);
    }
  }
}

Author comment

Began life as a copy of #1028525

download  show line numbers  debug dex  old transpilations   

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

No comments. add comment

Snippet ID: #1029225
Snippet name: ChunkedLongList - stored in fixed-size chunks
Eternal ID of this version: #1029225/1
Text MD5: 9b83abab903d87763e78754ea9029460
Transpilation MD5: 86cb0b7cd6455f8dc09962fd49ebdc33
Author: stefan
Category: javax
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2020-07-26 13:37:27
Source code size: 1742 bytes / 69 lines
Pitched / IR pitched: No / No
Views / Downloads: 212 / 478
Referenced in: #1034167 - Standard Classes + Interfaces (LIVE, continuation of #1003674)