UNPKG

bps.js

Version:

BPS patching utility

83 lines (72 loc) 1.9 kB
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.defaultLog = defaultLog; exports.encodeNumber = encodeNumber; exports.decodeNumber = decodeNumber; exports.toIntBE = toIntBE; exports.formatHex = formatHex; var BPS_START = exports.BPS_START = Buffer.from('BPS1'); var BPS_FOOTER_LENGTH = exports.BPS_FOOTER_LENGTH = 12; var SOURCE_READ = exports.SOURCE_READ = 0; var TARGET_READ = exports.TARGET_READ = 1; var SOURCE_COPY = exports.SOURCE_COPY = 2; var TARGET_COPY = exports.TARGET_COPY = 3; /* eslint-disable no-console */ function defaultLog(message) { if (console) { if (console.debug) { console.debug(message); } else if (console.log) { console.log(message); } } } /* eslint-enable no-console */ function encodeNumber(value) { var data = value; var encoded = []; while (true) { // eslint-disable-line no-constant-condition var x = data & 0x7f; data >>= 7; if (!data) { encoded.push(0x80 | x); break; } encoded.push(x); data--; } return Buffer.from(encoded); } function decodeNumber(data) { var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; var index = offset; var value = 0; var shift = 1; while (true) { // eslint-disable-line no-constant-condition var x = data[index]; index += 1; value += (x & 0x7f) * shift; if (x & 0x80) { break; } shift <<= 7; value += shift; } return [value, index]; } function toIntBE(buffer) { var value = 0; for (var i = 0; i < buffer.length; i++) { value = value << 8 | buffer.readUInt8(i); } return value >>> 0; } function formatHex(v) { var byteLength = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; var value = Buffer.isBuffer(v) ? toIntBE(v) : v; return '0x' + value.toString(16).padStart(2 * byteLength, '0'); }