biner
Version:
Declarative binary data encoder / decoder.
125 lines • 3.52 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class Chunk {
constructor(buffer, next) {
this.buffer = buffer;
this.next = next;
}
}
class LinkedList {
constructor() {
this.length = 0;
this.count = 0;
}
push(buf) {
const entry = new Chunk(buf);
if (this.tail) {
this.tail.next = entry;
}
else {
this.head = entry;
}
this.tail = entry;
this.length += buf.length;
this.count += 1;
}
unshift(buf) {
const entry = new Chunk(buf, this.head);
if (this.isEmpty()) {
this.tail = entry;
}
this.head = entry;
this.length += buf.length;
this.count += 1;
}
shift() {
if (this.isEmpty()) {
return;
}
const ret = this.head && this.head.buffer;
if (this.head === this.tail) {
this.head = undefined;
this.tail = undefined;
}
else if (this.head) {
this.head = this.head.next;
}
if (ret) {
this.length -= ret.length;
this.length = Math.max(this.length, 0);
this.count -= 1;
}
return ret;
}
get first() {
if (this.isEmpty()) {
return null;
}
return this.head && this.head.buffer;
}
get last() {
if (this.isEmpty()) {
return null;
}
return this.tail && this.tail.buffer;
}
isEmpty() {
return this.length === 0;
}
clear() {
this.head = undefined;
this.tail = undefined;
this.length = 0;
this.count = 0;
}
slice(start, end) {
if (start < 0 || start >= this.length) {
return new LinkedList();
}
if (end < 0 || end > this.length || end < start) {
return new LinkedList();
}
const list = new LinkedList();
let leaf = this.head;
let offsetStart = start;
let offsetEnd = end;
while (leaf) {
if (leaf.buffer.length > offsetStart) {
if (offsetStart === 0 && leaf.buffer.length <= offsetEnd) {
list.push(leaf.buffer);
}
else if (leaf.buffer.length >= offsetEnd) {
list.push(leaf.buffer.slice(offsetStart, offsetEnd));
}
else {
list.push(leaf.buffer.slice(offsetStart));
}
break;
}
offsetStart -= leaf.buffer.length;
offsetEnd -= leaf.buffer.length;
leaf = leaf.next;
}
if (leaf && (leaf.buffer.length < offsetEnd)) {
while (leaf) {
if (leaf.buffer.length === offsetEnd) {
list.push(leaf.buffer);
break;
}
else if (leaf.buffer.length > offsetEnd) {
list.push(leaf.buffer.slice(0, offsetEnd));
break;
}
else if (offsetStart < 0 && leaf.buffer.length < offsetEnd) {
list.push(leaf.buffer);
}
offsetStart -= leaf.buffer.length;
offsetEnd -= leaf.buffer.length;
leaf = leaf.next;
}
}
return list;
}
}
exports.LinkedList = LinkedList;
//# sourceMappingURL=ll.js.map