Blob


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 * Plan 9 port version must include libc.h in order to
16 * get Plan 9 debugging malloc, which sometimes returns
17 * different pointers than the standard malloc.
18 */
19 #ifdef PLAN9PORT
20 #include <u.h>
21 #include <libc.h>
22 #include "fmtdef.h"
23 #else
24 #include <stdlib.h>
25 #include "plan9.h"
26 #include "fmt.h"
27 #include "fmtdef.h"
28 #endif
30 static int
31 runeFmtStrFlush(Fmt *f)
32 {
33 Rune *s;
34 int n;
36 if(f->start == nil)
37 return 0;
38 n = (int)f->farg;
39 n *= 2;
40 s = (Rune*)f->start;
41 f->start = realloc(s, sizeof(Rune)*n);
42 if(f->start == nil){
43 f->farg = nil;
44 f->to = nil;
45 f->stop = nil;
46 free(s);
47 return 0;
48 }
49 f->farg = (void*)n;
50 f->to = (Rune*)f->start + ((Rune*)f->to - s);
51 f->stop = (Rune*)f->start + n - 1;
52 return 1;
53 }
55 int
56 runefmtstrinit(Fmt *f)
57 {
58 int n;
60 memset(f, 0, sizeof *f);
61 f->runes = 1;
62 n = 32;
63 f->start = malloc(sizeof(Rune)*n);
64 if(f->start == nil)
65 return -1;
66 f->to = f->start;
67 f->stop = (Rune*)f->start + n - 1;
68 f->flush = runeFmtStrFlush;
69 f->farg = (void*)n;
70 f->nfmt = 0;
71 return 0;
72 }
74 /*
75 * print into an allocated string buffer
76 */
77 Rune*
78 runevsmprint(char *fmt, va_list args)
79 {
80 Fmt f;
81 int n;
83 if(runefmtstrinit(&f) < 0)
84 return nil;
85 VA_COPY(f.args,args);
86 n = dofmt(&f, fmt);
87 VA_END(f.args);
88 if(f.start == nil)
89 return nil;
90 if(n < 0){
91 free(f.start);
92 return nil;
93 }
94 *(Rune*)f.to = '\0';
95 return (Rune*)f.start;
96 }