"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var number_decoder_1 = require("../../client/impl/converter/body/number-decoder");
// import { crc32 } from "crc";
var CRC = /** @class */ (function () {
    function CRC() {
    }
    // public static default(data: Uint8Array){
    //     return crc32(data.buffer);
    // }
    CRC.fromBytes = function (data, polynomial) {
        if ((data.length % CRC.MODULO) != 0) {
            throw new Error("Cannot compute CRC, input size must be a multiple of 4. Length is " + data.length + " % " + CRC.MODULO + " = " + (data.length % CRC.MODULO));
        }
        var uint32Data = new Uint32Array(data.length / 4);
        for (var offset = 0; offset < uint32Data.byteLength; offset++) {
            uint32Data[offset] = number_decoder_1.NumberConverter.fromOpaqueMsb(data.slice((offset * 4), (offset + 1) * 4), 32);
        }
        return CRC.fromWord(uint32Data, polynomial);
    };
    //crc 32 calculation by word.
    CRC.fromWord = function (buffer, polynomial) {
        if (polynomial === void 0) { polynomial = 0; }
        polynomial |= this.DEFAULT_POLYNOMIAL;
        //don't follow null pointers
        if (!buffer) {
            throw new Error("Buffer is null");
        }
        //don't accept buffers larger than 16MB
        if (buffer.byteLength > 16 * 1024 * 1024) {
            throw new Error("Buffers larger than 16MB");
        }
        var i;
        var myword;
        var crc;
        var length = buffer.length;
        // let remain: number = length/4;
        // const number * buf = ((const number *)(buffer));
        //don't accept length not multiple of 4
        // if ( length % 4 ){
        //     throw new Error("Not module 4");
        // }
        i = 0;
        crc = 0xFFFFFFFF;
        for (i = 0; i < length; i++) {
            myword = buffer[i]; // Get next word.
            crc = CRC._crc32(crc, myword, polynomial);
        }
        return crc;
    };
    CRC._crc32 = function (Crc, Data, polynomial) {
        Crc = Crc ^ Data;
        for (var i = 0; i < 32; i++) {
            if (Crc & 0x80000000) {
                Crc = ((Crc << 1) ^ polynomial) >>> 0; // Polynomial
                //Crc = (Crc << 1) ^ 0x04C11DB7; // Polynomial used in STM32
            }
            else {
                Crc = (Crc << 1) >>> 0;
            }
        }
        return (Crc);
    };
    CRC.DEFAULT_POLYNOMIAL = 0x4C11DB7;
    CRC.MODULO = 4;
    return CRC;
}());
exports.CRC = CRC;
