UNPKG

@iotize/device-client.js

Version:

IoTize Device client for Javascript

46 lines (45 loc) 1.66 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.BYTE_SWAP_ORDER_REGEX = /^(B[0-9]+)(_B[0-9]+)*$/; var ByteSwapConverter = /** @class */ (function () { function ByteSwapConverter(order) { this.order = order; } ByteSwapConverter.prototype.encode = function (input) { return swapBytes(input, this.order); }; ByteSwapConverter.prototype.decode = function (input) { return this.encode(input); }; return ByteSwapConverter; }()); exports.ByteSwapConverter = ByteSwapConverter; /** * This function is symetric * * If we have array A,B,C,D with swap order B2_B3_B0_B1 it returns B,A,D,C * * @param input array * @param order string that defined how to swap bytes * @return a new array with byte swap */ function swapBytes(input, order) { if (!order.match(exports.BYTE_SWAP_ORDER_REGEX)) { throw new Error("Invalid byte order: " + order + ". Should match regex " + exports.BYTE_SWAP_ORDER_REGEX); } var parts = order.split("_"); var indexMap = parts.reduce(function (prev, current, index) { prev[current] = index; return prev; }, {}); if (parts.length != input.length) { throw new Error("Expection " + parts.length + " bytes but found " + input.length + " bytes"); } var result = new Uint8Array(input.length); // let maxLength = Math.min(parts.length, input.length) for (var index = 0; index < result.length; index++) { result[indexMap["B" + (result.length - index - 1)]] = input[index]; } return result; } exports.swapBytes = swapBytes;