#include "ds.h"
#include <string.h>

int char_cmp(const void *a, const void *b)
{
	char _a = *(char*)a;
	char _b = *(char*)b;
	if(_a < _b) return -1;
	if(_a > _b) return +1;
	return 0;
}

int u8_cmp (const void *a, const void *b)
{
	u8 _a = *(u8*)a;
	u8 _b = *(u8*)b;
	if(_a < _b) return -1;
	if(_a > _b) return +1;
	return 0;
}

int u32_cmp(const void *a, const void *b)
{
	u32 _a = *(u32*)a;
	u32 _b = *(u32*)b;
	if(_a < _b) return -1;
	if(_a > _b) return +1;
	return 0;
}

int u64_cmp(const void *a, const void *b)
{
	u64 _a = *(u64*)a;
	u64 _b = *(u64*)b;
	if(_a < _b) return -1;
	if(_a > _b) return +1;
	return 0;
}

int s32_cmp(const void *a, const void *b)
{
	s32 _a = *(s32*)a;
	s32 _b = *(s32*)b;
	if(_a < _b) return -1;
	if(_a > _b) return +1;
	return 0;
}

int s64_cmp(const void *a, const void *b)
{
	s64 _a = *(s64*)a;
	s64 _b = *(s64*)b;
	if(_a < _b) return -1;
	if(_a > _b) return +1;
	return 0;
}



u64 make_unique(void *array, u64 count, u64 element_size, compare_fn *cmp)
{
	qsort(array, count, element_size, cmp);

	// Remove duplicates
	u8 *start = (u8*)array;
	u8 *end   = start + element_size * count;

	u64 deleted = 0;

	u8 *prev = start;
	u8 *curr = start + element_size;
	while(curr < end)
	{
		if(cmp(prev, curr) == 0)
		{
			deleted++;
		}
		else
		{
			prev += element_size;
			memcpy(prev, curr, element_size);
		}
		curr += element_size;
	}

	return count - deleted;
}
