/* accept_buf.c */

#include <pthread.h>
#include <stdio.h>
#include "accept_buf.h"

int accept_buf_next;
int accept_buf_count;
struct accept_buf * accept_buf_ptr = NULL;
pthread_cond_t accept_buf_cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t accept_buf_mutex = PTHREAD_MUTEX_INITIALIZER;

int accept_buf_init(int count)
{
	if (count <= 0) {
		printf("Not a valid count %d\n", count);
		return(-1);
	}
	if ((accept_buf_ptr = malloc(sizeof(struct accept_buf) * count)) == NULL) {
		printf("Not enough memory to init %d buffers\n", count);
		return(-1);
	}
	accept_buf_next = 0;
	accept_buf_count = count;
	for (count = 0; count < accept_buf_count; count++) {
		accept_buf_ptr[count].fd = count++;
	}
	accept_buf_ptr[count].fd = -1;
}

struct accept_buf * accept_buf_malloc()
{
	struct accept_buf * buf;
	pthread_mutex_lock(&accept_buf_mutex);

	while (accept_buf_next == -1) {
		pthread_cond_wait(&accept_buf_cond, &accept_buf_mutex);
	}
	buf = accept_buf_ptr + accept_buf_next;
	accept_buf_next = buf->fd;

	pthread_mutex_unlock(&accept_buf_mutex);
	return(buf);
}
	
void accept_buf_free(struct accept_buf * buf)
{
	pthread_mutex_lock(&accept_buf_mutex);

	if ((buf->fd =  accept_buf_next) == -1) {
		pthread_cond_signal(&accept_buf_cond);
	}
	accept_buf_next = buf - accept_buf_ptr;
	
	pthread_mutex_unlock(&accept_buf_mutex);
}

