#include "ref.h"
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

void *rc_alloc(size_t size, void (*destructor)(void *self))
{
    printf("rc_alloc %zu bytes\n", size);
    ref_header *header = malloc(sizeof(ref_header) + size);
    memset(header, 0, size);
    if (!header)
    {
        exit(69);
    }

    header->ref_count = 1;
    header->destructor = destructor;

    return (void *)(header + 1);
}

void rc_retain(void *obj)
{
    if (!obj)
        return;

    printf("rc_retain\n");
    ref_header *header = ((ref_header *)obj) - 1;
    header->ref_count++;
}

void rc_release(void *obj)
{
    if (!obj)
        return;

    ref_header *header = ((ref_header *)obj) - 1;
    printf("rc_release\n");
    if (--header->ref_count == 0)
    {
        if (header->destructor)
        {
            header->destructor(obj);
        }

        free(header);
        printf("rc_free\n");
    }
}