All files / app/src node-buffer.ts

100% Statements 32/32
91.67% Branches 11/12
100% Functions 9/9
100% Lines 31/31

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 752x             2x       72x 70x 70x     2x 2x 2x             2x 32x     2x 166x     2x 316480x                 2x 1106508x 1106492x     1106508x 1106508x 1106508x 1106508x     2x 64x             2x 1106508x 22x 22x     22x 22x 22x     2x  
import AbstractCharBuffer from './abstract-char-buffer';
 
/**
 * {@link AbstractCharBuffer} implementation using a [Node.js Buffer][1].
 *
 * [1]: http://nodejs.org/api/buffer.html
 */
export default class NodeBuffer extends AbstractCharBuffer {
	protected buffer: Buffer;
 
	public constructor(initCapacity: number) {
		super(initCapacity);
		initCapacity = initCapacity || 16;
		this.buffer = Buffer.alloc(initCapacity * 2);
	}
 
	public static get isSupported(): boolean {
		try {
			return Buffer.from('A', 'utf16le').readUInt16LE(0) === 65;
		} catch (_) {
			/* istanbul ignore next */
			return false;
		}
	}
 
	public static fromString(string: string, transform?: (value: number, index: number, string: string) => number, thisArg?: any): NodeBuffer {
		return super._fromString(new this(string.length), string, transform, thisArg);
	}
 
	public charAt(offset: number): string {
		return String.fromCharCode(this.read(offset));
	}
 
	public charCodeAt(offset: number): number {
		return this.buffer.readUInt16LE(offset * 2);
	}
 
	/**
	 * Write a charCode to the buffer using {@link Buffer.writeUInt16LE}.
	 *
	 * @param charCode charCode The charCode to append.
	 * @param offset offset The zero based offset to write at.
	 */
	public write(charCode: number, offset?: number): this {
		if (typeof offset === 'undefined') {
			offset = this._length;
		}
 
		this._ensureCapacity(offset + 1);
		this.buffer.writeUInt16LE(charCode, offset * 2);
		this._length = offset + 1 > this._length ? offset + 1 : this._length;
		return this;
	}
 
	public toString(): string {
		return this.buffer.toString('utf16le', 0, this._length * 2);
	}
 
	/**
	 * Ensures a minimum capacity.
	 * @param {Number} minCapacity The minimum capacity (i.e. the expected {@link String#length length} of the {@link String} this buffer may represent).
	 */
	private _ensureCapacity(minCapacity: number): void {
		if (this.buffer.length < minCapacity * 2) {
			Eif (minCapacity < this.buffer.length) {
				minCapacity = this.buffer.length; // I.e. double the capacity (!)
			}
 
			const buffer = Buffer.alloc(minCapacity * 2);
			this.buffer.copy(buffer);
			this.buffer = buffer;
		}
	}
}