All files / src buffer.ts

93.55% Statements 29/31
95.45% Branches 21/22
80% Functions 4/5
96.67% Lines 29/30

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 75 76                              7x 7x 7x   7x         10x         10x 10x 6x 4x   2x     4x 3x   1x       10x     7x 9x       7x 33x   7x 7x 100x 7x   93x 93x 6x     87x 2x         85x     7x  
/*
 * Copyright © 2019 Lisk Foundation
 *
 * See the LICENSE file at the top-level directory of this distribution
 * for licensing information.
 *
 * Unless otherwise agreed in a custom licensing agreement with the Lisk Foundation,
 * no part of this software, including this file, may be copied, modified,
 * propagated, or distributed except according to the terms contained in the
 * LICENSE file.
 *
 * Removal or modification of this copyright notice is prohibited.
 *
 */
 
export const BIG_ENDIAN = 'big';
export const LITTLE_ENDIAN = 'little';
const MAX_NUMBER_BYTE_LENGTH = 6;
 
export const intToBuffer = (
	value: number | string,
	byteLength: number,
	endianness: string = BIG_ENDIAN,
) => {
	Iif (![BIG_ENDIAN, LITTLE_ENDIAN].includes(endianness)) {
		throw new Error(
			`Endianness must be either ${BIG_ENDIAN} or ${LITTLE_ENDIAN}`,
		);
	}
	const buffer = Buffer.alloc(byteLength);
	if (endianness === 'big') {
		if (byteLength <= MAX_NUMBER_BYTE_LENGTH) {
			buffer.writeUIntBE(Number(value), 0, byteLength);
		} else {
			buffer.writeBigUInt64BE(BigInt(value));
		}
	} else {
		if (byteLength <= MAX_NUMBER_BYTE_LENGTH) {
			buffer.writeUIntLE(Number(value), 0, byteLength);
		} else {
			buffer.writeBigUInt64LE(BigInt(value));
		}
	}
 
	return buffer;
};
 
export const bufferToIntAsString = (buffer: Buffer): string =>
	buffer.length <= MAX_NUMBER_BYTE_LENGTH
		? buffer.readIntBE(0, buffer.length).toString()
		: buffer.readBigUInt64BE().toString();
 
export const bufferToHex = (buffer: Buffer): string =>
	Buffer.from(buffer).toString('hex');
 
const hexRegex = /^[0-9a-f]+/i;
export const hexToBuffer = (hex: string, argumentName = 'Argument'): Buffer => {
	if (typeof hex !== 'string') {
		throw new TypeError(`${argumentName} must be a string.`);
	}
	const matchedHex = (hex.match(hexRegex) || [])[0];
	if (!matchedHex || matchedHex.length !== hex.length) {
		throw new TypeError(`${argumentName} must be a valid hex string.`);
	}
	// tslint:disable-next-line no-magic-numbers
	if (matchedHex.length % 2 !== 0) {
		throw new TypeError(
			`${argumentName} must have a valid length of hex string.`,
		);
	}
 
	return Buffer.from(matchedHex, 'hex');
};
 
export const stringToBuffer = (str: string): Buffer => Buffer.from(str, 'utf8');