// Written by retoor@molodetz.nl

// This source code demonstrates a test suite for memory allocation using custom `malloc`, `realloc`, and `calloc` in the `rtest` framework.
// It performs a series of memory allocation and deallocation operations, checking the count of allocations and deallocations to ensure
// proper memory management and detect any leaks or errors.

// Dependencies:
// This code relies on the custom libraries `rtest` and `rmalloc` specific to this testing framework.

// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

#include "rtest.h"
#include "rmalloc.h"

void rtest_malloc() {
    rtest_banner("count");
    void *x = malloc(10);
    void *y = malloc(10);
    void *z = malloc(10);
    void *ptr = NULL;
    realloc(ptr, 10);
    void *w = calloc(1, 10);
    rtest_true(rmalloc_alloc_count == 5);

    rtest_banner("free");
    x = free(x);
    rtest_true(x == NULL);
    rtest_true(rmalloc_count == 4);

    rtest_banner("another free");
    y = free(y);
    rtest_true(y == NULL);
    rtest_true(rmalloc_count == 3);

    rtest_banner("third free");
    z = free(z);
    rtest_true(z == NULL);
    rtest_true(rmalloc_count == 2);

    rtest_banner("third four");
    w = free(w);
    rtest_true(w == NULL);
    rtest_true(rmalloc_count == 1);

    rtest_banner("third five");
    ptr = free(ptr);
    rtest_true(ptr == NULL);
    rtest_true(rmalloc_count == 0);

    rtest_banner("totals");
    rtest_true(rmalloc_alloc_count == 5);
    rtest_true(rmalloc_free_count == 5);
    rtest_true(rmalloc_count == 0);
}

int main() {
    rtest_banner("malloc.h");
    rtest_malloc();
    return rtest_end("rtest_malloc");
}