/* Shared memory block utility code V1.00 30/10/03
   See smalloc.h for docs
   Copyright 2008 Jeffrey Lee
   This file is part of WOUM.
   WOUM is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.
   WOUM is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
   You should have received a copy of the GNU General Public License
   along with WOUM.  If not, see <http://www.gnu.org/licenses/>.
*/

#ifndef _SMALLOC_C
#define _SMALLOC_C

#include <stdlib.h>
#include "smalloc.h"

typedef struct {
	int ref; /* Reference count */
	int data[0]; /* Variable size data block */
} smblock;

void *smalloc(size_t size)
{
	smblock *b;
	b = malloc(size+sizeof(smblock));
	if (b == NULL)
		return NULL;
	b->ref = 1;
	return (void *) b->data;
}

void smref(void *b)
{
	smblock *bb;
	bb = b-sizeof(smblock);
	bb->ref++;
}

int smfree(void *b)
{
	smblock *bb;
	bb = b-sizeof(smblock);
	if (--bb->ref <= 0)
	{
		free(bb);
		return 1;
	}
	return 0;
}

#endif
