export var 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;
}());
export { ByteSwapConverter };
/**
 * Swap byte position
 * B0 represents the first byte from the right
 * BN represents the N byte from the right
 *
 * This function is symetric
 *
 * Example:
 * ```typescript
 * const input = Uint8Array.from([1,2,3,4]);
 * expect(swapBytes(input, 'B2_B3_B0_B1')).to.be.deep.eq(Uint8Array.from([2,1,4,3]));
 * ```
 *
 * @param input array
 * @param order string that defined how to swap bytes
 * @return a new array with byte swap
 */
export function swapBytes(input, order) {
    if (!order.match(BYTE_SWAP_ORDER_REGEX)) {
        throw new Error("swatpBytes error, invalid byte order \"" + order + "\". Should match regex " + BYTE_SWAP_ORDER_REGEX);
    }
    var parts = order.split('_');
    // // Create a mapping between byte number and byte position
    // // For example B0_B3_B1
    // // Will give mapping 
    // // { B0: 0, B3: 1, B1: 2 }
    // const indexMap: { [key: string]: number } = parts.reduce(
    //     (accumulator: { [key: string]: number }, current: string, index: number) => {
    //         accumulator[current] = index;
    //         return accumulator;
    //     },
    //     {}
    // );
    // if (parts.length !== input.length) {
    //     throw new Error(
    //         `swatpBytes error: ${parts.length} bytes but found ${input.length} bytes`
    //     );
    // }
    var result = new Uint8Array(parts.length);
    // let maxLength = Math.min(parts.length, input.length)
    for (var index = 0; index < result.length; index++) {
        var prevByteIndex = parseInt(parts[index].substr(1));
        if (prevByteIndex >= input.length) {
            throw new Error("swapBytes error, byte index " + prevByteIndex + " is out of range (input length is " + input.length + " byte(s))");
        }
        result[index] = input[input.length - prevByteIndex - 1];
        // const byteIndex = (result.length - index - 1);
        // const newIndex = indexMap['B' + byteIndex];
        // if (newIndex !== undefined) {
        //     result[newIndex] = input[index];
        // }
    }
    return result;
}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