/*
    c99tree - grow "/" separated paths in memory buffers (for web3)
    Copyright (C) 2010  Tibor Palinkas

    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.,
    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/

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

pathgrow_t *pathgrow_alloc(char sep)
{
	pathgrow_t *p;
	p = malloc(sizeof(pathgrow_t));
	p->path = NULL;
	p->alloced = 0;
	p->used = 0;
	p->separator = sep;
	return p;
}

void pathgrow_free(pathgrow_t *p)
{
	if (p->path != NULL)
		free(p->path);
	free(p);
}


void pathgrow_append(pathgrow_t *p, const char *item)
{
	int l;

	l = strlen(item);

	/* grow if no room to append; +2 is for the separator and \0 */
	if ((p->used + l + 2) >= p->alloced) {
		p->alloced = p->used + l + 2 + PATHGROW_GROW;
		p->path = realloc(p->path, p->alloced);
	}

	/* append separator and item */
	p->path[p->used] = p->separator;
	memcpy(p->path + p->used + 1, item, l);
	p->used += l+1;

	/* make sure we have a valid C string */
	p->path[p->used] = '\0';
}

void pathgrow_truncate(pathgrow_t *p)
{
	char *s;

	if (p->path != NULL) {
		s = strrchr(p->path, p->separator);
		if (s != NULL) {
			*s = '\0';
			p->used = s - p->path;
		}
	}
}

