#include <stdio.h>

#include "sparse.hpp"

static int checks = 0, failures = 0;

bool check(bool ok, const char *msg)
{
    checks++;
    if (!ok) {
        fprintf(stderr, "wrong %s\n", msg);
        failures++;
    }
    return ok;
}

void check_int(long got, long want, const char *msg)
{
    if (!check(got == want, msg))
        fprintf(stderr, "    got %ld, want %ld\n", got, want);
}

void test_assignment()
{
    SparseArray<int> a(0);
    check_int(a[5], 0, "missing element is the default");
    check_int(a.NonzeroCount(), 0, "empty array stores nothing");
    a[5] = 10;
    a[-3] = 20;
    a[1000000] = 30;
    check_int(a[5], 10, "assigned element");
    check_int(a[-3], 20, "negative index");
    check_int(a[1000000], 30, "large index");
    check_int(a.NonzeroCount(), 3, "count after three assignments");
    a[5] = 11;
    check_int(a[5], 11, "overwritten element");
    check_int(a.NonzeroCount(), 3, "overwriting adds nothing");
    a[5] = 0;
    check_int(a[5], 0, "element assigned the default");
    check_int(a.NonzeroCount(), 2, "assigning the default removes");
    a[77] = 0;
    check_int(a.NonzeroCount(), 2, "default to a missing element");
    check_int(a[8] = 9, 9, "value of an assignment");
}

void test_element_to_element()
{
    SparseArray<int> a(0);
    a[1] = 10;
    a[2] = 20;
    a[1] = a[2];
    check_int(a[1], 20, "a[1] = a[2]");
    a[3] = a[9];
    check_int(a.NonzeroCount(), 2, "a[3] = missing stores nothing");
    a[2] = a[9];
    check_int(a.NonzeroCount(), 1, "a[2] = missing removes a[2]");
    a[1] = a[1];
    check_int(a[1], 20, "a[1] = a[1]");
    a[4] = a[5] = 7;
    check_int(a[4] + a[5], 14, "a[4] = a[5] = 7");
}

/* every operator generated by SPARSE_ASSIGN, on the same start value */
void test_assign_operators()
{
    SparseArray<int> a(0);
    int i;
    for (i = 0; i < 10; i++)
        a[i] = 12;
    check_int(a[0] += 5, 17, "+=");
    check_int(a[1] -= 5, 7, "-=");
    check_int(a[2] *= 5, 60, "*=");
    check_int(a[3] /= 5, 2, "/=");
    check_int(a[4] %= 5, 2, "%=");
    check_int(a[5] |= 3, 15, "|=");
    check_int(a[6] &= 5, 4, "&=");
    check_int(a[7] ^= 5, 9, "^=");
    check_int(a[8] <<= 2, 48, "<<=");
    check_int(a[9] >>= 2, 3, ">>=");
    check_int(a[0] + a[1] + a[2] + a[3] + a[4], 88, "stored: first five");
    check_int(a[5] + a[6] + a[7] + a[8] + a[9], 79, "stored: last five");
}

/* an operator whose result is the default must remove the element */
void test_operators_remove()
{
    SparseArray<int> a(0);
    int i;
    for (i = 0; i < 8; i++)
        a[i] = 12;
    a[0] += -12;
    a[1] -= 12;
    a[2] *= 0;
    a[3] /= 13;
    a[4] %= 12;
    a[5] &= 3;
    a[6] ^= 12;
    a[7] >>= 4;
    check_int(a.NonzeroCount(), 0, "results equal to the default");
    a[9] += 5;
    check_int(a[9], 5, "+= on a missing element");
    a[8] += 0;
    check_int(a.NonzeroCount(), 1, "+= 0 on a missing element");
    a[9] += a[9];
    check_int(a[9], 10, "a[9] += a[9]");
    a[9] -= a[9];
    check_int(a.NonzeroCount(), 0, "a[9] -= a[9]");
}

/* the operators generated by SPARSE_STEP */
void test_steps()
{
    SparseArray<int> a(0);
    a[1] = 5;
    check_int(++a[1], 6, "prefix ++ gives the new value");
    check_int(a[1]++, 6, "postfix ++ gives the old value");
    check_int(a[1], 7, "after two increments");
    check_int(--a[1], 6, "prefix -- gives the new value");
    check_int(a[1]--, 6, "postfix -- gives the old value");
    check_int(a[1], 5, "after two decrements");
    check_int(a[2]++, 0, "postfix ++ on a missing element");
    check_int(a[2], 1, "missing element after ++");
    a[2]--;
    check_int(a.NonzeroCount(), 1, "-- down to the default removes");
    a[3] = -1;
    ++a[3];
    check_int(a.NonzeroCount(), 1, "++ up to the default removes");
}

void test_nonzero_default()
{
    SparseArray<int> a(100);
    check_int(a[5], 100, "missing element, default 100");
    a[5] += 1;
    check_int(a[5], 101, "+= starts from the default");
    a[6] = 0;
    check_int(a.NonzeroCount(), 2, "zero is stored when default is 100");
    a[5]--;
    a[6] = 100;
    check_int(a.NonzeroCount(), 0, "back to the default");
}

void test_const_reference()
{
    SparseArray<int> a(0);
    const SparseArray<int>& c = a;
    int i, sum = 0;
    a[1] = 10;
    a[3] = 30;
    for (i = 0; i < 100; i++)
        sum += c[i];
    check_int(sum, 40, "sum through a const reference");
    check_int(a.NonzeroCount(), 2, "reading creates nothing");
    check(&c[1] == &c[1], "same object for an existing element");
    check(&c[2] == &c[99], "one object for all missing elements");
    check(&c[1] != &c[3], "different objects for different elements");
    const int& r = c[3];
    a[3] = 31;
    check_int(r, 31, "a reference follows its element");
}

void test_double()
{
    SparseArray<double> d(0.5);
    d[1] = 2.0;
    d[1] *= 4;
    d[2] += 1.5;
    d[3] = 0.5;
    check(d[1] == 8.0, "double: *=");
    check(d[2] == 2.0, "double: += from the default");
    check(d[9] == 0.5, "double: missing element");
    check_int(d.NonzeroCount(), 2, "double: count");
    d[2] -= 1.5;
    check_int(d.NonzeroCount(), 1, "double: back to the default");
}

class Money {                   /* has ==, =, copying; nothing else */
    long cents;
public:
    Money(long a_cents = 0) : cents(a_cents) {}
    long Cents() const { return cents; }
    bool operator==(const Money& other) const { return cents == other.cents; }
};

void test_class_element()
{
    SparseArray<Money> m(Money(0));
    const SparseArray<Money>& c = m;
    m[1] = Money(250);
    m[2] = Money(999);
    m[2] = Money(0);
    check_int(c[1].Cents(), 250, "class: stored element");
    check_int(c[2].Cents(), 0, "class: removed element");
    check_int(Money(m[1]).Cents(), 250, "class: conversion to a copy");
    check_int(m.NonzeroCount(), 1, "class: count");
    m[3] = m[1];
    check_int(c[3].Cents(), 250, "class: element to element");
}

struct Point {
    int x, y;
};

void test_pointers()
{
    Point p = { 3, 4 };
    SparseArray<Point*> s(0);
    bool thrown = false;
    s[1] = &p;
    check_int(s[1]->x + s[1]->y, 7, "pointers: reading through ->");
    s[1]->x = 30;
    check_int(p.x, 30, "pointers: changing through ->");
    try {
        s[9]->x = 1;
    }
    catch (const NullElement& ex) {
        thrown = ex.Index() == 9;
    }
    check(thrown, "pointers: NullElement for a missing element");
    check_int(s.NonzeroCount(), 1, "pointers: -> creates nothing");
}

void test_bool()
{
    SparseArray<bool> b(false), t(true);
    const SparseArray<bool>& c = b;
    b[5] = true;
    b[1000000] = true;
    b[1] = 25;
    check(c[5] && c[1000000] && c[1], "bool: elements set");
    check(!c[0] && !c[6], "bool: missing elements are false");
    check_int(c[1], 1, "bool: 25 is stored as true");
    b[5] = true;
    check_int(b.NonzeroCount(), 3, "bool: no duplicate index");
    b[1] = false;
    check_int(b.NonzeroCount(), 2, "bool: false removes");
    b[0] = b[5];
    check(c[0], "bool: element to element");
    t[5] = false;
    check(!t[5] && t[4], "bool: default true");
    check_int(t.NonzeroCount(), 1, "bool: false stored, default true");
}

void test_bool_operators()
{
    SparseArray<bool> b(false);
    b[1] |= true;
    b[2] |= false;
    check_int(b.NonzeroCount(), 1, "bool: |=");
    b[1] &= false;
    check_int(b.NonzeroCount(), 0, "bool: &=");
    b[3] ^= true;
    b[3] ^= true;
    b[4] ^= true;
    check(!b[3] && b[4], "bool: ^=");
}

struct DivisionByZero {};

class Frac {                    /* /= throws on zero */
    int n;
public:
    Frac(int a_n = 0) : n(a_n) {}
    int Num() const { return n; }
    bool operator==(const Frac& other) const { return n == other.n; }
    Frac& operator/=(const Frac& other);
};

Frac& Frac::operator/=(const Frac& other)
{
    if (other.n == 0)
        throw DivisionByZero();
    n /= other.n;
    return *this;
}

/* an operator that throws must leave the array as it was */
void test_throwing_operator()
{
    SparseArray<Frac> f(Frac(0));
    bool thrown = false;
    f[1] = Frac(8);
    try {
        f[5] /= Frac(0);
    }
    catch (const DivisionByZero&) {
        thrown = true;
    }
    check(thrown, "throwing: the exception gets out");
    check_int(f.NonzeroCount(), 1, "throwing: a failed op stores nothing");
    f[1] /= Frac(2);
    check_int(Frac(f[1]).Num(), 4, "throwing: a good op still works");
}

class Tag {                     /* no default constructor */
    int id;
public:
    Tag(int a_id) : id(a_id) {}
    int Id() const { return id; }
    bool operator==(const Tag& other) const { return id == other.id; }
};

void test_no_default_constructor()
{
    SparseArray<Tag> t(Tag(0));
    const SparseArray<Tag>& c = t;
    t[1] = Tag(7);
    t[2] = t[1];
    check_int(c[2].Id(), 7, "no default constructor: stored");
    check_int(c[9].Id(), 0, "no default constructor: missing");
    check_int(t.NonzeroCount(), 2, "no default constructor: count");
}

template <class T>
int count_set(SparseArray<T>& a, int n)
{
    int i, count = 0;
    for (i = 0; i < n; i++)
        if (a[i])
            count++;
    return count;
}

void test_many()
{
    SparseArray<int> a(0);
    SparseArray<bool> b(false);
    int i;
    for (i = 0; i < 1000; i++) {
        a[3 * i] = i + 1;
        b[3 * i] = true;
    }
    check_int(a.NonzeroCount(), 1000, "many: int count");
    check_int(b.NonzeroCount(), 1000, "many: bool count");
    check_int(count_set(a, 3000), 1000, "many: int values");
    check_int(count_set(b, 3000), 1000, "many: bool values");
    for (i = 0; i < 1000; i += 2) {
        a[3 * i] = 0;
        b[3 * i] = false;
    }
    check_int(a.NonzeroCount(), 500, "many: int count after removal");
    check_int(b.NonzeroCount(), 500, "many: bool count after removal");
    check_int(a[3 * 999], 1000, "many: last element intact");
}

int main()
{
    test_assignment();
    test_element_to_element();
    test_assign_operators();
    test_operators_remove();
    test_steps();
    test_nonzero_default();
    test_const_reference();
    test_double();
    test_class_element();
    test_pointers();
    test_bool();
    test_bool_operators();
    test_throwing_operator();
    test_no_default_constructor();
    test_many();
    if (failures)
        fprintf(stderr, "%d of %d checks failed\n", failures, checks);
    else
        printf("all %d checks passed\n", checks);
    return failures != 0;
}
