1/*
2 *  This file is part of aMule.
3 *
4 *  This program is free software; you can redistribute it and/or modify
5 *  it under the terms of the GNU General Public License as published by
6 *  the Free Software Foundation; either version 2 of the License, or
7 *  (at your option) any later version.
8 *
9 *  This program is distributed in the hope that it will be useful,
10 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
11 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 *  GNU General Public License for more details.
13 *
14 *  You should have received a copy of the GNU General Public License
15 *  along with this program; if not, write to the
16 *  Free Software Foundation, Inc.,
17 *  51 Franklin St, Fifth Floor, Boston, MA  02110-1301, USA
18 */
19
20#include <stdio.h>
21#include <stdlib.h>
22#include <stdarg.h>
23#include <string.h>
24
25#include "lines.h"
26
27void CreateLine(char *lines[], int line, const char *format, ...)
28{
29	/* Guess we need no more than 80 bytes. */
30	int n, size = 100;
31	char *p;
32	va_list ap;
33	if ((p = malloc(size)) == NULL) {
34		lines[line] = NULL;
35		return;
36	}
37	while (1) {
38		/* Try to print in the allocated space. */
39		va_start(ap, format);
40		n = vsnprintf(p, size, format, ap);
41		va_end(ap);
42		/* If that worked, set the line. */
43		if (n > -1 && n < size) {
44			lines[line] = p;
45			return;
46		}
47		/* Else try again with more space. */
48		if (n > -1)	/* glibc 2.1 */
49			size = n+1;	/* precisely what is needed */
50		else		/* glibc 2.0 */
51			size *= 2;	/* twice the old size */
52		if ((p = realloc(p, size)) == NULL) {
53			lines[line] = NULL;
54			return;
55		}
56	}
57}
58
59void AppendToLine(char *lines[], int line, const char *text)
60{
61	/* Are we trying to append to an empty line? */
62	if (lines[line] == NULL)
63		CreateLine(lines, line, text);
64	else {
65		/* Calculate the new required size... */
66		int size = strlen(lines[line]) + strlen(text) + 1;
67		if ((lines[line] = realloc(lines[line], size)) == NULL)
68			return;
69		/* ... and append the new text. */
70		strcat(lines[line], text);
71	}
72}
73