sonic-forest
Version:
High-performance (binary) tree and sorted map implementation (AVL, Splay, Radix, Red-Black)
61 lines (60 loc) • 1.97 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Slice = void 0;
class Slice {
constructor(data, start, length) {
this.data = data;
this.start = start;
this.length = length;
}
at(index) {
if (index < 0 || index >= this.length) {
throw new Error(`Index ${index} out of bounds for slice of length ${this.length}`);
}
return this.data[this.start + index];
}
substring(start, length) {
if (start < 0 || start > this.length) {
throw new Error(`Start ${start} out of bounds for slice of length ${this.length}`);
}
const newLength = length !== undefined ? Math.min(length, this.length - start) : this.length - start;
return new Slice(this.data, this.start + start, newLength);
}
equals(other) {
if (this.length !== other.length)
return false;
for (let i = 0; i < this.length; i++) {
if (this.at(i) !== other.at(i))
return false;
}
return true;
}
compare(other) {
const minLength = Math.min(this.length, other.length);
for (let i = 0; i < minLength; i++) {
const thisByte = this.at(i);
const otherByte = other.at(i);
if (thisByte !== otherByte) {
return thisByte - otherByte;
}
}
return this.length - other.length;
}
toUint8Array() {
return this.data.slice(this.start, this.start + this.length);
}
toString() {
return `Slice(${Array.from(this.toUint8Array()).join(',')})`;
}
getCommonPrefixLength(other) {
const len = Math.min(this.length, other.length);
let i = 0;
for (; i < len && this.at(i) === other.at(i); i++)
;
return i;
}
static fromUint8Array(data) {
return new Slice(data, 0, data.length);
}
}
exports.Slice = Slice;