/*
 * Copyright (c) 2019 Andri Yngvason
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
 * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
 * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
 * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
 * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
 * PERFORMANCE OF THIS SOFTWARE.
 */

#include "vec.h"

#include <stdlib.h>
#include <string.h>

int wv_vec_init(struct wv_vec* vec, size_t cap)
{
	memset(vec, 0, sizeof(*vec));
	return wv_vec_reserve(vec, cap);
}

void wv_vec_destroy(struct wv_vec* vec)
{
	free(vec->data);
}

int wv_vec_reserve(struct wv_vec* vec, size_t size)
{
	if (size <= vec->cap)
		return 0;

	void* data = realloc(vec->data, size);
	if (!data)
		return -1;

	vec->cap = size;
	vec->data = data;

	return 0;
}

static int wv_vec__grow(struct wv_vec* vec, size_t size)
{
	if (vec->len + size < vec->cap)
		return 0;

	return wv_vec_reserve(vec, 2 * (vec->len + size));
}

int wv_vec_assign(struct wv_vec* vec, const void* data, size_t size)
{
	vec->len = 0;

	if (wv_vec_reserve(vec, size) < 0)
		return -1;

	vec->len = size;
	memcpy(vec->data, data, size);

	return 0;
}

int wv_vec_append(struct wv_vec* vec, const void* data, size_t size)
{
	if (wv_vec__grow(vec, size) < 0)
		return -1;

	char* p = vec->data;
	memcpy(&p[vec->len], data, size);
	vec->len += size;

	return 0;
}

void* wv_vec_append_zero(struct wv_vec* vec, size_t size)
{
	if (wv_vec__grow(vec, size) < 0)
		return NULL;

	char* p = vec->data;
	void* r = &p[vec->len];
	memset(r, 0, size);
	vec->len += size;

	return r;
}

void wv_vec_bzero(struct wv_vec* vec)
{
	memset(vec->data, 0, vec->cap);
}
