/*-
 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
 *
 * Copyright (c) 2019 Tobias Kortkamp <tobik@FreeBSD.org>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include "config.h"

#include <sys/types.h>
#include <inttypes.h>
#include <limits.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>

#include "array.h"
#include "diff.h"
#include "flow.h"
#include "mem.h"
#include "mempool.h"
#include "trait/compare.h"
#include "util.h"

struct Array {
	void **buf;
	size_t cap;
	size_t len;
	size_t value_size;
};

struct ArrayIterator {
	void **buf;
	size_t i;
	size_t len;
};

// Prototypes
static void array_ensure_capacity(struct Array *, size_t);

// Constants
static const size_t INITIAL_ARRAY_CAP = 16;

struct Array *
array_new()
{
	struct Array *array = xmalloc(sizeof(struct Array));

	array->cap = INITIAL_ARRAY_CAP;
	array->len = 0;
	array->value_size = sizeof(void *);
	array->buf = xrecallocarray(NULL, 0, array->cap, array->value_size);

	return array;
}

void
array_ensure_capacity(struct Array *array, size_t newlen)
{
	if (newlen < array->cap) {
		return;
	}

	size_t cap = next_power_of_2(newlen);
	if (cap > array->cap) {
		array->buf = xrecallocarray(array->buf, array->cap, cap, array->value_size);
		array->cap = cap;
	}
}

void
array_append(struct Array *array, const void *v)
{
	array_ensure_capacity(array, array->len + 1);
	array->buf[array->len++] = (void *)v;
}

void
array_insert(struct Array *array, size_t index, const void *v)
{
	if (index >= array->len) {
		array->len = index;
	}
	array_ensure_capacity(array, array->len + 1);
	memmove(array->buf + index + 1, array->buf + index, (array->len - index) * array->value_size);
	array->len++;
	array->buf[index] = (void *)v;
}

void *
array_remove(struct Array *array, size_t index)
{
	if (index >= array->len) {
		return NULL;
	} else if (index == array->len - 1) {
		array->len--;
		return array->buf[index];
	} else {
		void *val = array->buf[index];
		array->len--;
		memmove(array->buf + index, array->buf + index + 1, (array->len - index) * array->value_size);
		return val;
	}
}

void
array_join(struct Array *array, struct Array *arrays[], size_t arrayslen)
{
	for (size_t i = 0; i < arrayslen; i++) {
		struct Array *other = arrays[i];
		// save len because the other array might be this
		// array and array_append() modifies it
		size_t otherlen = other->len;
		for (size_t j = 0; j < otherlen; j++) {
			array_append(array, other->buf[j]);
		}
	}
}

struct diff *
array_diff(struct Array *base1, struct Array *base2, struct Mempool *pool, struct CompareTrait *compare)
{
	panic_unless(base1->value_size == base2->value_size, "array values are not comparable");
	struct diff *d = xmalloc(sizeof(struct diff));
	int retval = diff(d, compare->compare, compare->compare_userdata, base1->value_size,
			  base1->buf, base1->len, base2->buf, base2->len);
	panic_if(retval < 0, "memory allocation failure");
	if (retval == 0) { // sequence too complicated to generate
		free(d);
		return NULL;
	} else {
		mempool_take(pool, d);
		mempool_take(pool, d->lcs);
		mempool_take(pool, d->ses);
		return d;
	}
}

void
array_free(struct Array *array)
{
	if (array == NULL) {
		return;
	}
	free(array->buf);
	free(array);
}

ssize_t
array_find(struct Array *array, const void *k, struct CompareTrait *compare)
{
	for (size_t i = 0; i < array->len; i++) {
		const void *v = array->buf[i];
		if (compare->compare(&v, &k, compare->compare_userdata) == 0) {
			return i;
		}
	}
	return -1;
}

void *
array_get(struct Array *array, size_t i)
{
	if (i < array->len) {
		return array->buf[i];
	}
	return NULL;
}

size_t
array_len(struct Array *array)
{
	return array->len;
}

void *
array_pop(struct Array *array)
{
	if (array->len > 0) {
		array->len--;
		return array->buf[array->len];
	}
	return NULL;
}

void
array_set(struct Array *array, size_t index, const void *v)
{
	if (index >= array->len) {
		array_ensure_capacity(array, index + 1);
		array->len = index + 1;
	}
	array->buf[index] = (void *)v;
}

void
array_sort(struct Array *array, struct CompareTrait *compare)
{
	sort(array->buf, array->len, array->value_size, compare);
}

void
array_truncate(struct Array *array)
{
	array->len = 0;
}

void
array_truncate_at(struct Array *array, size_t len)
{
	if (len < array->len) {
		array->len = len;
	}
}

struct ArrayIterator *
array_iterator(struct Array *array, ssize_t a, ssize_t b)
{
	struct ArrayIterator *iter = xmalloc(sizeof(struct ArrayIterator));
	iter->buf = array->buf;
	slice_to_range(array->len, a, b, &iter->i, &iter->len);
	return iter;
}

void
array_iterator_cleanup(struct ArrayIterator **iter_)
{
	struct ArrayIterator *iter = *iter_;
	if (iter != NULL) {
		free(iter);
		*iter_ = NULL;
	}
}

bool
array_iterator_next(struct ArrayIterator **iter_, size_t *index, void **key, void **value)
{
	struct ArrayIterator *iter = *iter_;
	if (iter->i < iter->len) {
		void *v = iter->buf[iter->i];
		*index = iter->i++;
		*key = v;
		*value = v;
		return true;
	} else {
		array_iterator_cleanup(iter_);
		*iter_ = NULL;
		return false;
	}
}
