xref: /plan9-contrib/sys/src/cmd/unix/drawterm/libc/runevsmprint.c (revision 8ccd4a6360d974db7bd7bbd4f37e7018419ea908)
1 #include <u.h>
2 #include <libc.h>
3 #include "fmtdef.h"
4 
5 static int
6 runeFmtStrFlush(Fmt *f)
7 {
8 	Rune *s;
9 	int n;
10 
11 	if(f->start == nil)
12 		return 0;
13 	n = (int)f->farg;
14 	n *= 2;
15 	s = f->start;
16 	f->start = realloc(s, sizeof(Rune)*n);
17 	if(f->start == nil){
18 		f->farg = nil;
19 		f->to = nil;
20 		f->stop = nil;
21 		free(s);
22 		return 0;
23 	}
24 	f->farg = (void*)n;
25 	f->to = (Rune*)f->start + ((Rune*)f->to - s);
26 	f->stop = (Rune*)f->start + n - 1;
27 	return 1;
28 }
29 
30 int
31 runefmtstrinit(Fmt *f)
32 {
33 	int n;
34 
35 	memset(f, 0, sizeof *f);
36 	f->runes = 1;
37 	n = 32;
38 	f->start = malloc(sizeof(Rune)*n);
39 	if(f->start == nil)
40 		return -1;
41 	f->to = f->start;
42 	f->stop = (Rune*)f->start + n - 1;
43 	f->flush = runeFmtStrFlush;
44 	f->farg = (void*)n;
45 	f->nfmt = 0;
46 	return 0;
47 }
48 
49 /*
50  * print into an allocated string buffer
51  */
52 Rune*
53 runevsmprint(char *fmt, va_list args)
54 {
55 	Fmt f;
56 	int n;
57 
58 	if(runefmtstrinit(&f) < 0)
59 		return nil;
60 	f.args = args;
61 	n = dofmt(&f, fmt);
62 	if(f.start == nil)
63 		return nil;
64 	if(n < 0){
65 		free(f.start);
66 		return nil;
67 	}
68 	*(Rune*)f.to = '\0';
69 	return f.start;
70 }
71