cesr
Version:
[](https://www.npmjs.com/package/cesr) [](https://github.com/lenkan/cesr-js/blob/main/LICENSE) [ • 2.54 kB
JavaScript
import { CountCode_10, CountCode_20 } from "./codes.js";
import { encodeBinary, encodeText, decodeText, peekText, resolveQuadletCount, } from "./frame.js";
import { decodeUtf8 } from "./encoding-utf8.js";
function resolveCountCode(init) {
if (init.count < 64 ** 2) {
return `-${init.type}`;
}
return `--${init.type}`;
}
function resolveCounterSize(input) {
if (typeof input !== "string") {
input = decodeUtf8(input.slice(0, 4));
}
switch (input.charAt(0)) {
case "-":
switch (input.charAt(1)) {
case "-":
return { hs: 3, ss: 5, fs: 8 };
case "_":
return { hs: 5, ss: 3, fs: 8 };
default:
return { hs: 2, ss: 2, fs: 4 };
}
}
throw new Error(`Unknown code ${input.slice(0, 4)}`);
}
function createEncoder(types) {
return Object.entries(types).reduce((acc, [key, type]) => {
acc[key] = (count) => new Counter({ type, count });
return acc;
}, {});
}
export class Counter {
code;
count;
constructor(init) {
this.code = resolveCountCode(init);
this.count = init.count;
}
get quadlets() {
return resolveQuadletCount(this);
}
get size() {
return resolveCounterSize(this.code);
}
get soft() {
return this.count;
}
get raw() {
return new Uint8Array(0);
}
text() {
return encodeText(this);
}
binary() {
return encodeBinary(this);
}
get type() {
return this.code.replace(/^-+/, "");
}
static peek(input) {
if (input.length < 4) {
return { n: 0 };
}
const entry = resolveCounterSize(input);
const result = peekText(input, entry);
if (!result.frame) {
return { n: result.n };
}
return {
n: result.n,
frame: new Counter({
type: result.frame.code.replace(/^-+/, ""),
count: result.frame.soft ?? 0,
}),
};
}
static parse(input) {
const entry = resolveCounterSize(input);
const frame = decodeText(input, entry);
return new Counter({
type: frame.code.replace(/^-+/, ""),
count: frame.soft ?? 0,
});
}
static Code = {
v1: CountCode_10,
v2: CountCode_20,
};
static v1 = createEncoder(CountCode_10);
static v2 = createEncoder(CountCode_20);
}