irctokens
Version:
RFC1459 and IRCv3 protocol tokeniser
74 lines • 2.56 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.StatefulEncoder = exports.StatefulDecoder = void 0;
const line_1 = require("./line");
class StatefulDecoder {
#encoding;
#fallback;
#buffer = new Uint8Array();
constructor(encoding = 'utf8', fallback = 'latin1') {
this.#encoding = encoding;
this.#fallback = fallback;
this.clear();
}
clear() {
this.#buffer = new Uint8Array();
}
pending() {
return this.#buffer;
}
push(data) {
if (!data.length)
return;
const newBuffer = new Uint8Array(this.#buffer.length + data.length);
newBuffer.set(this.#buffer);
newBuffer.set(data, this.#buffer.length);
this.#buffer = newBuffer;
const lineBuffers = [];
while (this.#buffer.includes('\n'.charCodeAt(0))) {
const lfIdx = this.#buffer.indexOf('\n'.charCodeAt(0));
const crIdx = this.#buffer.indexOf('\r'.charCodeAt(0));
lineBuffers.push(this.#buffer.slice(0, crIdx < lfIdx ? crIdx : lfIdx));
this.#buffer = this.#buffer.slice(lfIdx + 1);
}
const lines = [];
for (const line of lineBuffers) {
lines.push((0, line_1.tokenise)(line, this.#encoding, this.#fallback));
}
return lines;
}
}
exports.StatefulDecoder = StatefulDecoder;
class StatefulEncoder {
// #encoding: TextEncodingLabel // TODO only supports utf8 at the moment because of TextEncoder
#encoder = new TextEncoder();
#buffer = new Uint8Array();
#bufferedLines = [];
constructor() {
this.clear();
}
clear() {
this.#buffer = new Uint8Array();
this.#bufferedLines = [];
}
pending() {
return this.#buffer;
}
push(line) {
const lineBuffer = this.#encoder.encode(`${line.format()}\r\n`);
const newBuffer = new Uint8Array(this.#buffer.length + lineBuffer.length);
newBuffer.set(this.#buffer);
newBuffer.set(lineBuffer, this.#buffer.length);
this.#buffer = newBuffer;
this.#bufferedLines.push(line);
}
pop(byteCount) {
const sent = this.#buffer.slice(0, byteCount).reduce((acc, curr) => {
return acc + (curr === '\n'.charCodeAt(0) ? 1 : 0);
}, 0);
this.#buffer = this.#buffer.slice(byteCount);
return new Array(sent).fill(null).map(_ => this.#bufferedLines.shift());
}
}
exports.StatefulEncoder = StatefulEncoder;
//# sourceMappingURL=stateful.js.map