xref: /plan9-contrib/sys/src/cmd/unix/drawterm/libc/vsmprint.c (revision 0d601874851962e88c6c60fdd2e637bba04e13c2)
1 /*
2  * The authors of this software are Rob Pike and Ken Thompson.
3  *              Copyright (c) 2002 by Lucent Technologies.
4  * Permission to use, copy, modify, and distribute this software for any
5  * purpose without fee is hereby granted, provided that this entire notice
6  * is included in all copies of any software which is or includes a copy
7  * or modification of this software and in all copies of the supporting
8  * documentation for such software.
9  * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
10  * WARRANTY.  IN PARTICULAR, NEITHER THE AUTHORS NOR LUCENT TECHNOLOGIES MAKE
11  * ANY REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
12  * OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
13  */
14 
15 #include <u.h>
16 #include <libc.h>
17 #include "fmtdef.h"
18 
19 static int
20 fmtStrFlush(Fmt *f)
21 {
22 	char *s;
23 	int n;
24 
25 	if(f->start == nil)
26 		return 0;
27 	n = (uintptr)f->farg;
28 	n *= 2;
29 	s = (char*)f->start;
30 	f->start = realloc(s, n);
31 	if(f->start == nil){
32 		f->farg = nil;
33 		f->to = nil;
34 		f->stop = nil;
35 		free(s);
36 		return 0;
37 	}
38 	f->farg = (void*)(uintptr)n;
39 	f->to = (char*)f->start + ((char*)f->to - s);
40 	f->stop = (char*)f->start + n - 1;
41 	return 1;
42 }
43 
44 int
45 fmtstrinit(Fmt *f)
46 {
47 	int n;
48 
49 	memset(f, 0, sizeof *f);
50 	f->runes = 0;
51 	n = 32;
52 	f->start = malloc(n);
53 	if(f->start == nil)
54 		return -1;
55 	f->to = f->start;
56 	f->stop = (char*)f->start + n - 1;
57 	f->flush = fmtStrFlush;
58 	f->farg = (void*)(uintptr)n;
59 	f->nfmt = 0;
60 	return 0;
61 }
62 
63 /*
64  * print into an allocated string buffer
65  */
66 char*
67 vsmprint(char *fmt, va_list args)
68 {
69 	Fmt f;
70 	int n;
71 
72 	if(fmtstrinit(&f) < 0)
73 		return nil;
74 	VA_COPY(f.args,args);
75 	n = dofmt(&f, fmt);
76 	VA_END(f.args);
77 	if(n < 0){
78 		free(f.start);
79 		return nil;
80 	}
81 	return fmtstrflush(&f);
82 }
83