/* cStringBuffer: a file-like string buffer.
   Copyright (C) 2004 Mooneer Salem <mooneer@translator.cx>

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.

   This library 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
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with this library; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

/* Include necessary includes. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <assert.h>
#include <unistd.h>
#include "config.h"

#ifdef HAVE_PTHREAD_H
#include <pthread.h>
#endif

#include "csb_private.h"
#include "csb.h"

/* csb_netstring_fromfile(): Reads a "netstring" from a file.
   Parameters:
     fptr: The file to read it from.
   Returns: csb_buf* with the string, or NULL on failure.
*/
/*@null@*/ csb_buf *csb_netstring_fromfile(FILE *fptr) {
	/* Declare variables. */
	unsigned long length;
	int retval;
	csb_buf *buf;

	/* Read length from file. */
	retval = fscanf(fptr, "%9lu", &length);
	if (retval < 1) {
		return (NULL);
	}

	/* If colon (:) does not follow it, return NULL also. */
	if (fgetc(fptr) != (int)':') {
		return (NULL);
	}

	/* Allocate buffer and read the rest in. */
	buf = csb_new();
	if (buf == NULL) {
		return (NULL);
	}

	(void)csb_prealloc(buf, length);
	if (fread(buf->string, (size_t)1, length, fptr) < length) {
		csb_destroy(buf);
		return (NULL);
	}
	buf->stringsize = length;

	/* Check for terminating comma. */
	if (fgetc(fptr) != (int)',') {
		csb_destroy(buf);
		return (NULL);
	}

	/* We got the string, return it. */
	return (buf);
}

/* csb_netstring_tofile(): Writes a buffer to a file as a "netstring".
   Parameters:
     buf: the buffer to write.
     fptr: The file to write to.
   Returns: true on success, false otherwise.
*/
int csb_netstring_tofile(csb_buf *buf, FILE *fptr) {
	/* Perform sanity checks to make sure we have a valid buffer. */
	assert(buf != NULL && buf->string != NULL);

	/* Write length to file. */
	fprintf(fptr, "%lu:", (unsigned long)buf->stringsize);

	/* Write contents and terminating comma. */
	(void)fwrite(buf->string, (size_t)1, buf->stringsize, fptr);
	(void)fputc(',', fptr);

	/* Return true, it was successful. */
	return (TRUE);
}


syntax highlighted by Code2HTML, v. 0.9.1