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,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYnl0ZS1zd2FwLWNvbnZlcnRlci5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