"use strict";
/*!
 * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
 * Licensed under the MIT License.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.getUpperBoundOfPreviousSequenceId = exports.maxSequenceId = exports.minSequenceId = exports.equalSequenceIds = exports.sequenceIdComparator = void 0;
const internal_1 = require("@fluidframework/core-utils/internal");
const index_js_1 = require("../util/index.js");
/**
 * Compares two sequenceIds. Returns a negative number if a \< b, a positive number if a \> b, and 0 if a === b.
 * Note that this handles cases where indexInBatch is Number.POSITIVE_INFINITY.
 */
const sequenceIdComparator = (a, b) => a.sequenceNumber !== b.sequenceNumber
    ? a.sequenceNumber - b.sequenceNumber
    : a.indexInBatch === b.indexInBatch
        ? 0
        : (a.indexInBatch ?? 0) - (b.indexInBatch ?? 0);
exports.sequenceIdComparator = sequenceIdComparator;
const equalSequenceIds = (a, b) => (0, exports.sequenceIdComparator)(a, b) === 0;
exports.equalSequenceIds = equalSequenceIds;
const minSequenceId = (a, b) => (0, exports.sequenceIdComparator)(a, b) < 0 ? a : b;
exports.minSequenceId = minSequenceId;
const maxSequenceId = (a, b) => (0, exports.sequenceIdComparator)(a, b) > 0 ? a : b;
exports.maxSequenceId = maxSequenceId;
/**
 * Returns the upper bound (maximum possible) sequenceId that can occur just before the given sequenceId.
 * Some examples:
 * 1. sequenceId = \{ sequenceNumber: 1, indexInBatch: 2 \}. The upper bound is \{ sequenceNumber: 1, indexInBatch: 1 \}.
 * 2. sequenceId = \{ sequenceNumber: 2 \}. The upper bound is \{ sequenceNumber: 1, indexInBatch: Number.POSITIVE_INFINITY \}.
 * The indexInBatch value of the previous commit will depend on how many ops were in the previous batch of messages received.
 */
const getUpperBoundOfPreviousSequenceId = (sequenceId) => {
    (0, internal_1.assert)(sequenceId.indexInBatch === undefined || Number.isFinite(sequenceId.indexInBatch), 0xabc /* indexInBatch must not be infinity */);
    return sequenceId.indexInBatch === undefined || sequenceId.indexInBatch === 0
        ? {
            sequenceNumber: (0, index_js_1.brand)(sequenceId.sequenceNumber - 1),
            indexInBatch: Number.POSITIVE_INFINITY,
        }
        : {
            sequenceNumber: (0, index_js_1.brand)(sequenceId.sequenceNumber),
            indexInBatch: sequenceId.indexInBatch - 1,
        };
};
exports.getUpperBoundOfPreviousSequenceId = getUpperBoundOfPreviousSequenceId;
//# sourceMappingURL=sequenceIdUtils.js.map