/* 
   Unix SMB/Netbios implementation.
   Version 1.9.
   Samba utility functions
   Copyright (C) Andrew Tridgell              1992-1999
   Copyright (C) Luke Kenneth Casson Leighton 1996-1999
   
   This program 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 2 of the License, or
   (at your option) any later version.
   
   This program 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 this program; if not, write to the Free Software
   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include "includes.h"

void free_void_array(uint32 num_entries, void **entries,
		void(free_item)(void*))
{
	uint32 i;
	if (entries != NULL)
	{
		for (i = 0; i < num_entries; i++)
		{
			if (entries[i] != NULL)
			{
				free_item(entries[i]);
			}
		}
		free(entries);
	}
}

void* add_item_to_array(uint32 *len, void ***array, const void *item,
	void*(item_dup)(const void*), BOOL alloc_anyway)
{
	if (len == NULL || array == NULL || item_dup == NULL)
	{
		return NULL;
	}

	(*array) = (void**)Realloc((*array), ((*len)+1)*sizeof((*array)[0]));

	if ((*array) != NULL)
	{
		void* copy = NULL;
		if (item != NULL || alloc_anyway)
		{
			copy = item_dup(item);
		}
		(*array)[(*len)] = copy;
		(*len)++;
		return copy;
	}
	return NULL;
}

void free_char_array(uint32 num_entries, char **entries)
{
	void(*fn)(void*) = (void(*)(void*))&free;
	free_void_array(num_entries, (void**)entries, *fn);
}

char* add_chars_to_array(uint32 *len, char ***array, const char *name)
{
	void*(*fn)(const void*) = (void*(*)(const void*))&strdup;
	return (char*)add_item_to_array(len,
	                     (void***)array, (const void*)name, *fn, False);
				
}

void free_unistr_array(uint32 num_entries, UNISTR2 **entries)
{
	void(*fn)(void*) = (void(*)(void*))&unistr2_free;
	free_void_array(num_entries, (void**)entries, *fn);
}

UNISTR2* add_unistr_to_array(uint32 *len, UNISTR2 ***array, UNISTR2 *name)
{
	void*(*fn)(const void*) = (void*(*)(const void*))&unistr2_dup;
	return (UNISTR2*)add_item_to_array(len,
	                   (void***)array, (const void*)name, *fn, False);
}

void free_sid_array(uint32 num_entries, DOM_SID **entries)
{
	void(*fn)(void*) = (void(*)(void*))&free;
	free_void_array(num_entries, (void**)entries, *fn);
}

DOM_SID* add_sid_to_array(uint32 *len, DOM_SID ***array, const DOM_SID *sid)
{
	void*(*fn)(const void*) = (void*(*)(const void*))&sid_dup;
	return (DOM_SID*)add_item_to_array(len,
	                  (void***)array, (const void*)sid, *fn, False);
}

