import { assert } from "../../../assert.js";
import { largest_common_alignment_uint32 } from "../../../binary/largest_common_alignment_uint32.js";
import { isArrayEqualStrict } from "../isArrayEqualStrict.js";

/**
 *
 * @param {ArrayBuffer} a
 * @param {number} a_offset
 * @param {ArrayBuffer} b
 * @param {number} b_offset
 * @param {number} length in bytes
 * @returns {boolean}
 */
export function is_array_buffer_equals(
    a, a_offset,
    b, b_offset,
    length
) {

    assert.isNonNegativeInteger(a_offset, 'a_offset');
    assert.isNonNegativeInteger(b_offset, 'b_offset');
    assert.isNonNegativeInteger(length, 'length');

    if (a === b && a_offset === b_offset) {
        // same buffer, same range
        return true;
    }

    const alignment = largest_common_alignment_uint32(a_offset, b_offset, length);

    let a_arr, b_arr;

    if (alignment === 4) {
        a_arr = new Uint32Array(a, a_offset, length >>> 2);
        b_arr = new Uint32Array(b, b_offset, length >>> 2);
    } else if (alignment === 2) {
        a_arr = new Uint16Array(a, a_offset, length >>> 1);
        b_arr = new Uint16Array(b, b_offset, length >>> 1);
    } else {
        a_arr = new Uint8Array(a, a_offset, length);
        b_arr = new Uint8Array(b, b_offset, length);
    }

    return isArrayEqualStrict(a_arr, b_arr);
}