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 ANY 11 * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY 12 * OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE. 13 */ 14 #include "lib9.h" 15 #include "fmtdef.h" 16 17 static int 18 fmtStrFlush(Fmt *f) 19 { 20 char *s; 21 int n; 22 23 n = (int)f->farg; 24 n += 256; 25 f->farg = (void*)n; 26 s = f->start; 27 f->start = realloc(s, n); 28 if(f->start == nil){ 29 free(s); 30 f->to = nil; 31 f->stop = nil; 32 return 0; 33 } 34 f->to = (char*)f->start + ((char*)f->to - s); 35 f->stop = (char*)f->start + n - 1; 36 return 1; 37 } 38 39 int 40 fmtstrinit(Fmt *f) 41 { 42 int n; 43 44 f->runes = 0; 45 n = 32; 46 f->start = malloc(n); 47 if(f->start == nil) 48 return -1; 49 f->to = f->start; 50 f->stop = (char*)f->start + n - 1; 51 f->flush = fmtStrFlush; 52 f->farg = (void*)n; 53 f->nfmt = 0; 54 return 0; 55 } 56 57 /* 58 * print into an allocated string buffer 59 */ 60 char* 61 vsmprint(char *fmt, va_list args) 62 { 63 Fmt f; 64 int n; 65 66 if(fmtstrinit(&f) < 0) 67 return nil; 68 f.args = args; 69 n = dofmt(&f, fmt); 70 if(n < 0) 71 return nil; 72 *(char*)f.to = '\0'; 73 return f.start; 74 } 75