UNPKG

lotus-sdk

Version:

Central repository for several classes of tools for integrating with, and building for, the Lotusia ecosystem

77 lines (76 loc) 2.55 kB
import { Preconditions } from './preconditions.js'; export class BufferUtil { static fill(buffer, value) { Preconditions.checkArgumentType(buffer, 'Buffer', 'buffer'); Preconditions.checkArgumentType(value, 'number', 'value'); const length = buffer.length; for (let i = 0; i < length; i++) { buffer[i] = value; } return buffer; } static copy(original) { const buffer = Buffer.alloc(original.length); original.copy(buffer); return buffer; } static isBuffer(arg) { return Buffer.isBuffer(arg) || arg instanceof Uint8Array; } static emptyBuffer(bytes) { Preconditions.checkArgumentType(bytes, 'number', 'bytes'); const result = Buffer.alloc(bytes); for (let i = 0; i < bytes; i++) { result.write('\0', i); } return result; } static concat(list, totalLength) { return Buffer.concat(list, totalLength); } static equals(a, b) { if (a.length !== b.length) { return false; } const length = a.length; for (let i = 0; i < length; i++) { if (a[i] !== b[i]) { return false; } } return true; } static equal(a, b) { return BufferUtil.equals(a, b); } static integerAsSingleByteBuffer(integer) { Preconditions.checkArgumentType(integer, 'number', 'integer'); return Buffer.from([integer & 0xff]); } static integerAsBuffer(integer) { Preconditions.checkArgumentType(integer, 'number', 'integer'); const bytes = []; bytes.push((integer >> 24) & 0xff); bytes.push((integer >> 16) & 0xff); bytes.push((integer >> 8) & 0xff); bytes.push(integer & 0xff); return Buffer.from(bytes); } static integerFromBuffer(buffer) { Preconditions.checkArgumentType(buffer, 'Buffer', 'buffer'); return (buffer[0] << 24) | (buffer[1] << 16) | (buffer[2] << 8) | buffer[3]; } static integerFromSingleByteBuffer(buffer) { Preconditions.checkArgumentType(buffer, 'Buffer', 'buffer'); return buffer[0]; } static bufferToHex(buffer) { Preconditions.checkArgumentType(buffer, 'Buffer', 'buffer'); return buffer.toString('hex'); } static reverse(param) { return Buffer.from(param).reverse(); } } export const NULL_HASH = BufferUtil.fill(Buffer.alloc(32), 0); export const EMPTY_BUFFER = Buffer.alloc(0);