/* SPDX-License-Identifier: CC0-1.0 */
/* Link the pinned author's CQF unchanged; this is not a throughput test. */
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include "gqf.h"
#include "gqf_int.h"
#define REQUIRE(x) do { if (!(x)) { fprintf(stderr, "Failed: %s at %d\n", #x, __LINE__); exit(1); } } while (0)
static uint64_t count(QF *qf, uint64_t key) {
    return qf_count_key_value(qf, key, 0, QF_NO_LOCK);
}
int main(void) {
    QF qf;
    REQUIRE(qf_malloc(&qf, 64, 10, 0, QF_HASH_DEFAULT, 0));
    uint64_t a = 0, b = 0, c = 0;
    REQUIRE(count(&qf, a) == 0);
    REQUIRE(qf_insert(&qf, a, 0, 5, QF_NO_LOCK) >= 0);
    REQUIRE(count(&qf, a) == 5);
    /* Search deterministically using the default hash, not an injected hasher. */
    for (uint64_t key = 1; key <= 1000000 && (!b || !c); ++key) {
        if (count(&qf, key) == 5 && !b) b = key;
        if (count(&qf, key) == 0 && !c) c = key;
    }
    REQUIRE(b && c && a != b && b != c);
    REQUIRE(count(&qf, b) == 5);
    REQUIRE(qf_insert(&qf, b, 0, 2, QF_NO_LOCK) >= 0);
    REQUIRE(count(&qf, a) == 7 && count(&qf, b) == 7);
    REQUIRE(qf_get_sum_of_counts(&qf) == 7);
    REQUIRE(qf_resize_malloc(&qf, 128) >= 0);
    REQUIRE(qf_get_nslots(&qf) == 128 && qf_get_num_key_bits(&qf) == 10);
    REQUIRE(count(&qf, a) == 7 && count(&qf, b) == 7);
    REQUIRE(qf_remove(&qf, a, 0, 5, QF_NO_LOCK) >= 0);
    REQUIRE(count(&qf, b) == 2);
    REQUIRE(qf_remove(&qf, b, 0, 2, QF_NO_LOCK) >= 0);
    REQUIRE(count(&qf, a) == 0 && count(&qf, b) == 0);
    qf_reset(&qf);
    REQUIRE(qf_insert(&qf, a, 0, 1, QF_NO_LOCK) >= 0);
    REQUIRE(qf_remove(&qf, b, 0, 1, QF_NO_LOCK) >= 0);
    REQUIRE(count(&qf, a) == 0); /* Deliberately invalid history: B never inserted. */
    qf_reset(&qf);
    REQUIRE(qf_insert(&qf, a, 0, 5, QF_NO_LOCK) >= 0);
    int absent_result = qf_remove(&qf, c, 0, 1, QF_NO_LOCK);
    REQUIRE(absent_result == -1); /* Pinned implementation; header instead documents -3. */
    REQUIRE(count(&qf, a) == 5);
    REQUIRE(qf_remove(&qf, a, 0, 0, QF_NO_LOCK) >= 0);
    REQUIRE(count(&qf, a) == 5);
    REQUIRE(qf_delete_key_value(&qf, a, 0, QF_NO_LOCK) >= 0);
    REQUIRE(count(&qf, a) == 0);
    REQUIRE(qf_free(&qf));
    printf("{\"schemaVersion\":1,\"upstreamCommit\":\"68939f587b0f33f8c45be4f0e2a18e12bffa9fa6\","
           "\"hashMode\":\"QF_HASH_DEFAULT\",\"seed\":0,\"keyBits\":10,"
           "\"initialSlots\":64,\"resizedSlots\":128,\"keyA\":%" PRIu64 ","
           "\"collidingKeyB\":%" PRIu64 ",\"noncollidingKeyC\":%" PRIu64 ","
           "\"countAfterA5\":5,\"countAfterA5B2\":7,\"countAfterResize\":7,"
           "\"countAfterMatchedRemoveA5\":2,\"countAfterAbsentRemoveB1\":0,"
           "\"countAfterRemoveZero\":5,\"countAfterDeleteAll\":0}\n", a, b, c);
    return 0;
}
