export const BYTE_SWAP_ORDER_REGEX = /^(B[0-9]+)(_B[0-9]+)*$/;
export class ByteSwapConverter {
    constructor(order) {
        this.order = order;
    }
    encode(input) {
        return swapBytes(input, this.order);
    }
    decode(input) {
        return this.encode(input);
    }
}
/**
 * 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}`);
    }
    const 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`
    //     );
    // }
    const result = new Uint8Array(parts.length);
    // let maxLength = Math.min(parts.length, input.length)
    for (let index = 0; index < result.length; index++) {
        const 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;
}
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYnl0ZS1zd2FwLWNvbnZlcnRlci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