@kayahr/text-encoding
Version:
Text encoder and decoder
52 lines • 1.5 kB
JavaScript
/*
* Copyright (C) 2021 Klaus Reimer <k@ailis.de>
* See LICENSE.md for licensing information.
*/
import { AbstractEncoder } from "../AbstractEncoder.js";
import { END_OF_BUFFER } from "../ByteBuffer.js";
import { FINISHED } from "../constants.js";
import { indexOf, isASCII } from "../util.js";
/**
* Encoder for single byte encodings.
*/
export class SingleByteEncoder extends AbstractEncoder {
index;
/**
* Constructs new encoder for the given code points.
*
* @param codePoints - The code points of the encoding.
*/
constructor(index) {
super();
this.index = index;
}
/**
* Creates and returns a single byte encoder class for the given code points.
*
* @param codePoints - The code points of the encoding to encode.
* @returns The created single byte encoder class.
*/
static forCodePoints(codePoints) {
return class extends SingleByteEncoder {
constructor() {
super(codePoints);
}
};
}
/** @inheritdoc */
encode(buffer) {
const codePoint = buffer.read();
if (codePoint === END_OF_BUFFER) {
return FINISHED;
}
if (isASCII(codePoint)) {
return codePoint;
}
const index = indexOf(this.index, codePoint);
if (index == null) {
return this.fail(codePoint);
}
return index + 0x80;
}
}
//# sourceMappingURL=SingleByteEncoder.js.map