Skip to content

Instantly share code, notes, and snippets.

@cdata
Created August 6, 2014 21:24
Show Gist options
  • Save cdata/0fd1d8db66420fd20d2a to your computer and use it in GitHub Desktop.
Save cdata/0fd1d8db66420fd20d2a to your computer and use it in GitHub Desktop.
ES6 Sample
import { Primitive } from 'primitive';
let Buffer = Primitive.extend((Super) => {
return {
init (ArrayType, itemSize, pageSize) {
this.used = new Set();
this.freeByteIndices = [];
this.pages = [];
this.itemSize = itemSize;
this.pageSize = pageSize || itemSize * 100;
if (this.pageSize < this.itemSize) {
throw new Error('Invalid page size (cannot be less than item size).');
}
this.maxAllocatedItems = 0;
this.ArrayType = ArrayType;
this.itemInitializerValues = this.allocate();
},
get itemByteLength () {
return this.itemSize * this.ArrayType.BYTES_PER_ELEMENT;
},
get lastItemByteIndex () {
return ((this.maxAllocatedItems - 1) * this.itemByteLength) % this.pageByteLength;
},
get pageByteLength () {
return this.pageSize * this.ArrayType.BYTES_PER_ELEMENT;
},
get currentPageIsFull () {
return this.lastItemByteIndex >= this.pageByteLength - this.itemByteLength;
},
get currentPage () {
return this.pages[this.currentPageIndex];
},
get currentPageIndex () {
return this.pages.length - 1;
},
get numberOfPages () {
return this.pages.length;
},
get itemsPerPage () {
return Math.floor(this.pageSize / this.itemSize);
},
allocate () {
let page;
let itemByteIndex;
let item;
if (this.freeByteIndices.length) {
itemByteIndex = this.freeByteIndices.pop();
page = this.pages[this.freeByteIndices.pop()];
}
if (itemByteIndex === undefined) {
if (!this.pages.length || this.currentPageIsFull) {
this.pages.push(new ArrayBuffer(this.pageByteLength));
}
++this.maxAllocatedItems;
itemByteIndex = this.lastItemByteIndex
page = this.currentPage;
}
item = new this.ArrayType(page, itemByteIndex, this.itemSize);
item.bufferByteIndex = itemByteIndex;
item.pageIndex = this.currentPageIndex;
return item;
},
free (item) {
this.freeByteIndices.push(item.pageIndex, item.bufferByteIndex);
item.set(this.itemInitializerValues);
item.free = true;
}
};
});
export { Buffer }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment