uc-sdk
 All Classes Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
xprintf.c
Go to the documentation of this file.
1 /*
2 ** It turns out that the printf functions in the stock MIT pthread library
3 ** is busted. It isn't thread safe. If two threads try to do a printf
4 ** of a floating point value at the same time, a core-dump might result.
5 ** So this code is substituted.
6 */
7 /*
8 ** NAME: $Source: /open/anoncvs/cvs/src/lib/libpthread/stdio/Attic/xprintf.c,v $
9 ** VERSION: $Revision: 1.1 $
10 ** DATE: $Date: 1998/07/21 13:22:19 $
11 **
12 ** ONELINER: A replacement for formatted printing programs.
13 **
14 ** COPYRIGHT:
15 ** Copyright (c) 1990 by D. Richard Hipp. This code is an original
16 ** work and has been prepared without reference to any prior
17 ** implementations of similar functions. No part of this code is
18 ** subject to licensing restrictions of any telephone company or
19 ** university.
20 **
21 ** This copyright was released and the code placed in the public domain
22 ** by the author, D. Richard Hipp, on October 3, 1996.
23 **
24 ** DESCRIPTION:
25 ** This program is an enhanced replacement for the "printf" programs
26 ** found in the standard library. The following enhancements are
27 ** supported:
28 **
29 ** + Additional functions. The standard set of "printf" functions
30 ** includes printf, fprintf, sprintf, vprintf, vfprintf, and
31 ** vsprintf. This module adds the following:
32 **
33 ** * snprintf -- Works like sprintf, but has an extra argument
34 ** which is the size of the buffer written to.
35 **
36 ** * mprintf -- Similar to sprintf. Writes output to memory
37 ** obtained from mem_alloc.
38 **
39 ** * xprintf -- Calls a function to dispose of output.
40 **
41 ** * nprintf -- No output, but returns the number of characters
42 ** that would have been output by printf.
43 **
44 ** * A v- version (ex: vsnprintf) of every function is also
45 ** supplied.
46 **
47 ** + A few extensions to the formatting notation are supported:
48 **
49 ** * The "=" flag (similar to "-") causes the output to be
50 ** be centered in the appropriately sized field.
51 **
52 ** * The %b field outputs an integer in binary notation.
53 **
54 ** * The %c field now accepts a precision. The character output
55 ** is repeated by the number of times the precision specifies.
56 **
57 ** * The %' field works like %c, but takes as its character the
58 ** next character of the format string, instead of the next
59 ** argument. For example, printf("%.78'-") prints 78 minus
60 ** signs, the same as printf("%.78c",'-').
61 **
62 ** + When compiled using GCC on a SPARC, this version of printf is
63 ** faster than the library printf for SUN OS 4.1.
64 **
65 ** + All functions are fully reentrant.
66 **
67 */
68 /*
69 ** Undefine COMPATIBILITY to make some slight changes in the way things
70 ** work. I think the changes are an improvement, but they are not
71 ** backwards compatible.
72 */
73 /* #define COMPATIBILITY / * Compatible with SUN OS 4.1 */
74 #include "stdio.h"
75 #include <stdarg.h>
76 #include "ctype.h"
77 #include <math.h>
78 #include "stdlib.h"
79 #include "string.h"
80 /*
81 ** The maximum number of digits of accuracy in a floating-point conversion.
82 */
83 #define MAXDIG 20
84 
85 /*
86 ** Conversion types fall into various categories as defined by the
87 ** following enumeration.
88 */
89 enum e_type { /* The type of the format field */
90  RADIX, /* Integer types. %d, %x, %o, and so forth */
91  FLOAT, /* Floating point. %f */
92  EXP, /* Exponentional notation. %e and %E */
93  GENERIC, /* Floating or exponential, depending on exponent. %g */
94  SIZE, /* Return number of characters processed so far. %n */
95  STRING, /* Strings. %s */
96  PERCENT, /* Percent symbol. %% */
97  CHAR, /* Characters. %c */
98  ERROR, /* Used to indicate no such conversion type */
99 /* The rest are extensions, not normally found in printf() */
100  CHARLIT, /* Literal characters. %' */
101  SEEIT, /* Strings with visible control characters. %S */
102  MEM_STRING, /* A string which should be deleted after use. %z */
103  ORDINAL, /* 1st, 2nd, 3rd and so forth */
104 };
105 
106 /*
107 ** Each builtin conversion character (ex: the 'd' in "%d") is described
108 ** by an instance of the following structure
109 */
110 typedef struct s_info { /* Information about each format field */
111  int fmttype; /* The format field code letter */
112  int base; /* The base for radix conversion */
113  char *charset; /* The character set for conversion */
114  int flag_signed; /* Is the quantity signed? */
115  char *prefix; /* Prefix on non-zero values in alt format */
116  enum e_type type; /* Conversion paradigm */
117 } info;
118 
119 /*
120 ** The following table is searched linearly, so it is good to put the
121 ** most frequently used conversion types first.
122 */
123 static const info fmtinfo[] = {
124  { 'd', 10, "0123456789", 1, 0, RADIX, },
125  { 's', 0, 0, 0, 0, STRING, },
126  { 'S', 0, 0, 0, 0, SEEIT, },
127  { 'z', 0, 0, 0, 0, MEM_STRING, },
128  { 'c', 0, 0, 0, 0, CHAR, },
129  { 'o', 8, "01234567", 0, "0", RADIX, },
130  { 'u', 10, "0123456789", 0, 0, RADIX, },
131  { 'x', 16, "0123456789abcdef", 0, "x0", RADIX, },
132  { 'X', 16, "0123456789ABCDEF", 0, "X0", RADIX, },
133  { 'r', 10, "0123456789", 0, 0, ORDINAL, },
134  { 'f', 0, 0, 1, 0, FLOAT, },
135  { 'e', 0, "e", 1, 0, EXP, },
136  { 'E', 0, "E", 1, 0, EXP, },
137  { 'g', 0, "e", 1, 0, GENERIC, },
138  { 'G', 0, "E", 1, 0, GENERIC, },
139  { 'i', 10, "0123456789", 1, 0, RADIX, },
140  { 'n', 0, 0, 0, 0, SIZE, },
141  { 'S', 0, 0, 0, 0, SEEIT, },
142  { '%', 0, 0, 0, 0, PERCENT, },
143  { 'b', 2, "01", 0, "b0", RADIX, }, /* Binary notation */
144  { 'p', 16, "0123456789abcdef", 0, "x0", RADIX, }, /* Pointers */
145  { '\'', 0, 0, 0, 0, CHARLIT, }, /* Literal char */
146 };
147 #define NINFO (sizeof(fmtinfo)/sizeof(info)) /* Size of the fmtinfo table */
148 
149 /*
150 ** If NOFLOATINGPOINT is defined, then none of the floating point
151 ** conversions will work.
152 */
153 #ifndef NOFLOATINGPOINT
154 /*
155 ** "*val" is a double such that 0.1 <= *val < 10.0
156 ** Return the ascii code for the leading digit of *val, then
157 ** multiply "*val" by 10.0 to renormalize.
158 **
159 ** Example:
160 ** input: *val = 3.14159
161 ** output: *val = 1.4159 function return = '3'
162 **
163 ** The counter *cnt is incremented each time. After counter exceeds
164 ** 16 (the number of significant digits in a 64-bit float) '0' is
165 ** always returned.
166 */
167 static int getdigit(long double *val, int *cnt){
168  int digit;
169  long double d;
170  if( (*cnt)++ >= MAXDIG ) return '0';
171  digit = (int)*val;
172  d = digit;
173  digit += '0';
174  *val = (*val - d)*10.0;
175  return digit;
176 }
177 #endif
178 
179 /*
180 ** Setting the size of the BUFFER involves trade-offs. No %d or %f
181 ** conversion can have more than BUFSIZE characters. If the field
182 ** width is larger than BUFSIZE, it is silently shortened. On the
183 ** other hand, this routine consumes more stack space with larger
184 ** BUFSIZEs. If you have some threads for which you want to minimize
185 ** stack space, you should keep BUFSIZE small.
186 */
187 #define BUFSIZE 100 /* Size of the output buffer */
188 
189 /*
190 ** The root program. All variations call this core.
191 **
192 ** INPUTS:
193 ** func This is a pointer to a function taking three arguments
194 ** 1. A pointer to the list of characters to be output
195 ** (Note, this list is NOT null terminated.)
196 ** 2. An integer number of characters to be output.
197 ** (Note: This number might be zero.)
198 ** 3. A pointer to anything. Same as the "arg" parameter.
199 **
200 ** arg This is the pointer to anything which will be passed as the
201 ** third argument to "func". Use it for whatever you like.
202 **
203 ** fmt This is the format string, as in the usual print.
204 **
205 ** ap This is a pointer to a list of arguments. Same as in
206 ** vfprint.
207 **
208 ** OUTPUTS:
209 ** The return value is the total number of characters sent to
210 ** the function "func". Returns -1 on a error.
211 **
212 ** Note that the order in which automatic variables are declared below
213 ** seems to make a big difference in determining how fast this beast
214 ** will run.
215 */
216 int vxprintf(func,arg,format,ap)
217  void (*func)(const char*,int,void*);
218  void *arg;
219  const char *format;
220  va_list ap;
221 {
222  register const char *fmt; /* The format string. */
223  register int c; /* Next character in the format string */
224  register char *bufpt; /* Pointer to the conversion buffer */
225  register int precision; /* Precision of the current field */
226  register int length; /* Length of the field */
227  register int idx; /* A general purpose loop counter */
228  int count; /* Total number of characters output */
229  int width; /* Width of the current field */
230  int flag_leftjustify; /* True if "-" flag is present */
231  int flag_plussign; /* True if "+" flag is present */
232  int flag_blanksign; /* True if " " flag is present */
233  int flag_alternateform; /* True if "#" flag is present */
234  int flag_zeropad; /* True if field width constant starts with zero */
235  int flag_long; /* True if "l" flag is present */
236  int flag_center; /* True if "=" flag is present */
237  unsigned long longvalue; /* Value for integer types */
238  long double realvalue; /* Value for real types */
239  const info *infop; /* Pointer to the appropriate info structure */
240  char buf[BUFSIZE]; /* Conversion buffer */
241  char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */
242  int errorflag = 0; /* True if an error is encountered */
243  enum e_type xtype; /* Conversion paradigm */
244  char *zMem = NULL; /* String to be freed */
245  static const char spaces[] =
246  " ";
247 #define SPACESIZE (sizeof(spaces)-1)
248 #ifndef NOFLOATINGPOINT
249  int exp; /* exponent of real numbers */
250  long double rounder; /* Used for rounding floating point values */
251  int flag_dp; /* True if decimal point should be shown */
252  int flag_rtz; /* True if trailing zeros should be removed */
253  int flag_exp; /* True to force display of the exponent */
254  int nsd; /* Number of significant digits returned */
255 #endif
256 
257  fmt = format; /* Put in a register for speed */
258  count = length = 0;
259  bufpt = 0;
260  for(; (c=(*fmt))!=0; ++fmt){
261  if( c!='%' ){
262  register int amt;
263  bufpt = (char *)fmt;
264  amt = 1;
265  while( (c=(*++fmt))!='%' && c!=0 ) amt++;
266  (*func)(bufpt,amt,arg);
267  count += amt;
268  if( c==0 ) break;
269  }
270  if( (c=(*++fmt))==0 ){
271  errorflag = 1;
272  (*func)("%",1,arg);
273  count++;
274  break;
275  }
276  /* Find out what flags are present */
277  flag_leftjustify = flag_plussign = flag_blanksign =
278  flag_alternateform = flag_zeropad = flag_center = 0;
279  do{
280  switch( c ){
281  case '-': flag_leftjustify = 1; c = 0; break;
282  case '+': flag_plussign = 1; c = 0; break;
283  case ' ': flag_blanksign = 1; c = 0; break;
284  case '#': flag_alternateform = 1; c = 0; break;
285  case '0': flag_zeropad = 1; c = 0; break;
286  case '=': flag_center = 1; c = 0; break;
287  default: break;
288  }
289  }while( c==0 && (c=(*++fmt))!=0 );
290  if( flag_center ) flag_leftjustify = 0;
291  /* Get the field width */
292  width = 0;
293  if( c=='*' ){
294  width = va_arg(ap,int);
295  if( width<0 ){
296  flag_leftjustify = 1;
297  width = -width;
298  }
299  c = *++fmt;
300  }else{
301  while( isdigit(c) ){
302  width = width*10 + c - '0';
303  c = *++fmt;
304  }
305  }
306  if( width > BUFSIZE-10 ){
307  width = BUFSIZE-10;
308  }
309  /* Get the precision */
310  if( c=='.' ){
311  precision = 0;
312  c = *++fmt;
313  if( c=='*' ){
314  precision = va_arg(ap,int);
315 #ifndef COMPATIBILITY
316  /* This is sensible, but SUN OS 4.1 doesn't do it. */
317  if( precision<0 ) precision = -precision;
318 #endif
319  c = *++fmt;
320  }else{
321  while( isdigit(c) ){
322  precision = precision*10 + c - '0';
323  c = *++fmt;
324  }
325  }
326  /* Limit the precision to prevent overflowing buf[] during conversion */
327  if( precision>BUFSIZE-40 ) precision = BUFSIZE-40;
328  }else{
329  precision = -1;
330  }
331  /* Get the conversion type modifier */
332  if( c=='l' ){
333  flag_long = 1;
334  c = *++fmt;
335  }else{
336  flag_long = 0;
337  }
338  /* Fetch the info entry for the field */
339  infop = 0;
340  for(idx=0; idx<NINFO; idx++){
341  if( c==fmtinfo[idx].fmttype ){
342  infop = &fmtinfo[idx];
343  break;
344  }
345  }
346  /* No info entry found. It must be an error. */
347  if( infop==0 ){
348  xtype = ERROR;
349  }else{
350  xtype = infop->type;
351  if( c=='p' ){
352  flag_alternateform = 1;
353  width = sizeof(uintptr_t)*2;
354  }
355  }
356 
357  /*
358  ** At this point, variables are initialized as follows:
359  **
360  ** flag_alternateform TRUE if a '#' is present.
361  ** flag_plussign TRUE if a '+' is present.
362  ** flag_leftjustify TRUE if a '-' is present or if the
363  ** field width was negative.
364  ** flag_zeropad TRUE if the width began with 0.
365  ** flag_long TRUE if the letter 'l' (ell) prefixed
366  ** the conversion character.
367  ** flag_blanksign TRUE if a ' ' is present.
368  ** width The specified field width. This is
369  ** always non-negative. Zero is the default.
370  ** precision The specified precision. The default
371  ** is -1.
372  ** xtype The class of the conversion.
373  ** infop Pointer to the appropriate info struct.
374  */
375  switch( xtype ){
376  case ORDINAL:
377  case RADIX:
378  if( flag_long ) longvalue = va_arg(ap,long);
379  else longvalue = va_arg(ap,int);
380 #ifdef COMPATIBILITY
381  /* For the format %#x, the value zero is printed "0" not "0x0".
382  ** I think this is stupid. */
383  if( longvalue==0 ) flag_alternateform = 0;
384 #else
385  /* More sensible: turn off the prefix for octal (to prevent "00"),
386  ** but leave the prefix for hex. */
387  if( longvalue==0 && infop->base==8 ) flag_alternateform = 0;
388 #endif
389  if( infop->flag_signed ){
390  if( *(long*)&longvalue<0 ){
391  longvalue = -*(long*)&longvalue;
392  prefix = '-';
393  }else if( flag_plussign ) prefix = '+';
394  else if( flag_blanksign ) prefix = ' ';
395  else prefix = 0;
396  }else prefix = 0;
397  if( flag_zeropad && precision<width-(prefix!=0) ){
398  precision = width-(prefix!=0);
399  }
400  bufpt = &buf[BUFSIZE];
401  if( xtype==ORDINAL ){
402  long a,b;
403  a = longvalue%10;
404  b = longvalue%100;
405  bufpt -= 2;
406  if( a==0 || a>3 || (b>10 && b<14) ){
407  bufpt[0] = 't';
408  bufpt[1] = 'h';
409  }else if( a==1 ){
410  bufpt[0] = 's';
411  bufpt[1] = 't';
412  }else if( a==2 ){
413  bufpt[0] = 'n';
414  bufpt[1] = 'd';
415  }else if( a==3 ){
416  bufpt[0] = 'r';
417  bufpt[1] = 'd';
418  }
419  }
420  {
421  register char *cset; /* Use registers for speed */
422  register int base;
423  cset = infop->charset;
424  base = infop->base;
425  do{ /* Convert to ascii */
426  *(--bufpt) = cset[longvalue%base];
427  longvalue = longvalue/base;
428  }while( longvalue>0 );
429  }
430  length = (int)(&buf[BUFSIZE]-bufpt);
431  for(idx=precision-length; idx>0; idx--){
432  *(--bufpt) = '0'; /* Zero pad */
433  }
434  if( prefix ) *(--bufpt) = prefix; /* Add sign */
435  if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */
436  char *pre, x;
437  pre = infop->prefix;
438  if( *bufpt!=pre[0] ){
439  for(pre=infop->prefix; (x=(*pre))!=0; pre++) *(--bufpt) = x;
440  }
441  }
442  length = (int)(&buf[BUFSIZE]-bufpt);
443  break;
444  case FLOAT:
445  case EXP:
446  case GENERIC:
447  realvalue = va_arg(ap,double);
448 #ifndef NOFLOATINGPOINT
449  if( precision<0 ) precision = 6; /* Set default precision */
450  if( precision>BUFSIZE-10 ) precision = BUFSIZE-10;
451  if( realvalue<0.0 ){
452  realvalue = -realvalue;
453  prefix = '-';
454  }else{
455  if( flag_plussign ) prefix = '+';
456  else if( flag_blanksign ) prefix = ' ';
457  else prefix = 0;
458  }
459  if( infop->type==GENERIC && precision>0 ) precision--;
460  rounder = 0.0;
461 #ifdef COMPATIBILITY
462  /* Rounding works like BSD when the constant 0.4999 is used. Wierd! */
463  for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
464 #else
465  /* It makes more sense to use 0.5 */
466  if( precision>MAXDIG-1 ) idx = MAXDIG-1;
467  else idx = precision;
468  for(rounder=0.5; idx>0; idx--, rounder*=0.1);
469 #endif
470  if( infop->type==FLOAT ) realvalue += rounder;
471  /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
472  exp = 0;
473  if( realvalue>0.0 ){
474  int k = 0;
475  while( realvalue>=1e8 && k++<100 ){ realvalue *= 1e-8; exp+=8; }
476  while( realvalue>=10.0 && k++<100 ){ realvalue *= 0.1; exp++; }
477  while( realvalue<1e-8 && k++<100 ){ realvalue *= 1e8; exp-=8; }
478  while( realvalue<1.0 && k++<100 ){ realvalue *= 10.0; exp--; }
479  if( k>=100 ){
480  bufpt = "NaN";
481  length = 3;
482  break;
483  }
484  }
485  bufpt = buf;
486  /*
487  ** If the field type is GENERIC, then convert to either EXP
488  ** or FLOAT, as appropriate.
489  */
490  flag_exp = xtype==EXP;
491  if( xtype!=FLOAT ){
492  realvalue += rounder;
493  if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
494  }
495  if( xtype==GENERIC ){
496  flag_rtz = !flag_alternateform;
497  if( exp<-4 || exp>precision ){
498  xtype = EXP;
499  }else{
500  precision = precision - exp;
501  xtype = FLOAT;
502  }
503  }else{
504  flag_rtz = 0;
505  }
506  /*
507  ** The "exp+precision" test causes output to be of type EXP if
508  ** the precision is too large to fit in buf[].
509  */
510  nsd = 0;
511  if( xtype==FLOAT && exp+precision<BUFSIZE-30 ){
512  flag_dp = (precision>0 || flag_alternateform);
513  if( prefix ) *(bufpt++) = prefix; /* Sign */
514  if( exp<0 ) *(bufpt++) = '0'; /* Digits before "." */
515  else for(; exp>=0; exp--) *(bufpt++) = getdigit(&realvalue,&nsd);
516  if( flag_dp ) *(bufpt++) = '.'; /* The decimal point */
517  for(exp++; exp<0 && precision>0; precision--, exp++){
518  *(bufpt++) = '0';
519  }
520  while( (precision--)>0 ) *(bufpt++) = getdigit(&realvalue,&nsd);
521  *(bufpt--) = 0; /* Null terminate */
522  if( flag_rtz && flag_dp ){ /* Remove trailing zeros and "." */
523  while( bufpt>=buf && *bufpt=='0' ) *(bufpt--) = 0;
524  if( bufpt>=buf && *bufpt=='.' ) *(bufpt--) = 0;
525  }
526  bufpt++; /* point to next free slot */
527  }else{ /* EXP or GENERIC */
528  flag_dp = (precision>0 || flag_alternateform);
529  if( prefix ) *(bufpt++) = prefix; /* Sign */
530  *(bufpt++) = getdigit(&realvalue,&nsd); /* First digit */
531  if( flag_dp ) *(bufpt++) = '.'; /* Decimal point */
532  while( (precision--)>0 ) *(bufpt++) = getdigit(&realvalue,&nsd);
533  bufpt--; /* point to last digit */
534  if( flag_rtz && flag_dp ){ /* Remove tail zeros */
535  while( bufpt>=buf && *bufpt=='0' ) *(bufpt--) = 0;
536  if( bufpt>=buf && *bufpt=='.' ) *(bufpt--) = 0;
537  }
538  bufpt++; /* point to next free slot */
539  if( exp || flag_exp ){
540  *(bufpt++) = infop->charset[0];
541  if( exp<0 ){ *(bufpt++) = '-'; exp = -exp; } /* sign of exp */
542  else { *(bufpt++) = '+'; }
543  if( exp>=100 ){
544  *(bufpt++) = (exp/100)+'0'; /* 100's digit */
545  exp %= 100;
546  }
547  *(bufpt++) = exp/10+'0'; /* 10's digit */
548  *(bufpt++) = exp%10+'0'; /* 1's digit */
549  }
550  }
551  /* The converted number is in buf[] and zero terminated. Output it.
552  ** Note that the number is in the usual order, not reversed as with
553  ** integer conversions. */
554  length = (int)(bufpt-buf);
555  bufpt = buf;
556 
557  /* Special case: Add leading zeros if the flag_zeropad flag is
558  ** set and we are not left justified */
559  if( flag_zeropad && !flag_leftjustify && length < width){
560  int i;
561  int nPad = width - length;
562  for(i=width; i>=nPad; i--){
563  bufpt[i] = bufpt[i-nPad];
564  }
565  i = prefix!=0;
566  while( nPad-- ) bufpt[i++] = '0';
567  length = width;
568  }
569 #endif
570  break;
571  case SIZE:
572  *(va_arg(ap,int*)) = count;
573  length = width = 0;
574  break;
575  case PERCENT:
576  buf[0] = '%';
577  bufpt = buf;
578  length = 1;
579  break;
580  case CHARLIT:
581  case CHAR:
582  c = buf[0] = (xtype==CHAR ? va_arg(ap,int) : *++fmt);
583  if( precision>=0 ){
584  for(idx=1; idx<precision; idx++) buf[idx] = c;
585  length = precision;
586  }else{
587  length =1;
588  }
589  bufpt = buf;
590  break;
591  case STRING:
592  case MEM_STRING:
593  zMem = bufpt = va_arg(ap,char*);
594  if( bufpt==0 ) bufpt = "(null)";
595  length = strlen(bufpt);
596  if( precision>=0 && precision<length ) length = precision;
597  break;
598  case SEEIT:
599  {
600  int i;
601  int c;
602  char *arg = va_arg(ap,char*);
603  for(i=0; i<BUFSIZE-1 && (c = *arg++)!=0; i++){
604  if( c<0x20 || c>=0x7f ){
605  buf[i++] = '^';
606  buf[i] = (c&0x1f)+0x40;
607  }else{
608  buf[i] = c;
609  }
610  }
611  bufpt = buf;
612  length = i;
613  if( precision>=0 && precision<length ) length = precision;
614  }
615  break;
616  case ERROR:
617  buf[0] = '%';
618  buf[1] = c;
619  errorflag = 0;
620  idx = 1+(c!=0);
621  (*func)("%",idx,arg);
622  count += idx;
623  if( c==0 ) fmt--;
624  break;
625  }/* End switch over the format type */
626  /*
627  ** The text of the conversion is pointed to by "bufpt" and is
628  ** "length" characters long. The field width is "width". Do
629  ** the output.
630  */
631  if( !flag_leftjustify ){
632  register int nspace;
633  nspace = width-length;
634  if( nspace>0 ){
635  if( flag_center ){
636  nspace = nspace/2;
637  width -= nspace;
638  flag_leftjustify = 1;
639  }
640  count += nspace;
641  while( nspace>=SPACESIZE ){
642  (*func)(spaces,SPACESIZE,arg);
643  nspace -= SPACESIZE;
644  }
645  if( nspace>0 ) (*func)(spaces,nspace,arg);
646  }
647  }
648  if( length>0 ){
649  (*func)(bufpt,length,arg);
650  count += length;
651  }
652  if( xtype==MEM_STRING && zMem ){
653  free(zMem);
654  }
655  if( flag_leftjustify ){
656  register int nspace;
657  nspace = width-length;
658  if( nspace>0 ){
659  count += nspace;
660  while( nspace>=SPACESIZE ){
661  (*func)(spaces,SPACESIZE,arg);
662  nspace -= SPACESIZE;
663  }
664  if( nspace>0 ) (*func)(spaces,nspace,arg);
665  }
666  }
667  }/* End for loop over the format string */
668  return errorflag ? -1 : count;
669 } /* End of function */
670 
671 /*
672 ** Now for string-print, also as found in any standard library.
673 ** Add to this the snprint function which stops added characters
674 ** to the string at a given length.
675 **
676 ** Note that snprint returns the length of the string as it would
677 ** be if there were no limit on the output.
678 */
679 struct s_strargument { /* Describes the string being written to */
680  char *next; /* Next free slot in the string */
681  char *last; /* Last available slot in the string */
682 };
683 
684 static void sout(txt,amt,arg)
685  char *txt;
686  int amt;
687  void *arg;
688 {
689  register char *head;
690  register const char *t;
691  register int a;
692  register char *tail;
693  a = amt;
694  t = txt;
695  head = ((struct s_strargument*)arg)->next;
696  tail = ((struct s_strargument*)arg)->last;
697  if( tail ){
698  while( a-- >0 && head<tail ) *(head++) = *(t++);
699  }else{
700  while( a-- >0 ) *(head++) = *(t++);
701  }
702  *head = 0;
703  ((struct s_strargument*)arg)->next = head;
704 }
705 
706 int vsprintf(char *buf,const char *fmt,va_list ap){
707  struct s_strargument arg;
708  arg.next = buf;
709  arg.last = 0;
710  *buf = 0;
711  return vxprintf(sout,&arg,fmt,ap);
712 }
713 int vsnprintf(char *buf, size_t n, const char *fmt, va_list ap){
714  struct s_strargument arg;
715  arg.next = buf;
716  arg.last = &buf[n-1];
717  *buf = 0;
718  return vxprintf(sout,&arg,fmt,ap);
719 }
720 
721 /*
722 ** The following section of code handles the mprintf routine, that
723 ** writes to memory obtained from malloc().
724 */
725 
726 /* This structure is used to store state information about the
727 ** write in progress
728 */
729 struct sgMprintf {
730  char *zBase; /* A base allocation */
731  char *zText; /* The string collected so far */
732  int nChar; /* Length of the string so far */
733  int nAlloc; /* Amount of space allocated in zText */
734 };
735 
736 /* The xprintf callback function. */
737 static void mout(zNewText,nNewChar,arg)
738  char *zNewText;
739  int nNewChar;
740  void *arg;
741 {
742  struct sgMprintf *pM = (struct sgMprintf*)arg;
743  if( pM->nChar + nNewChar + 1 > pM->nAlloc ){
744  pM->nAlloc = pM->nChar + nNewChar*2 + 1;
745  if( pM->zText==pM->zBase ){
746  pM->zText = malloc(pM->nAlloc);
747  if( pM->zText && pM->nChar ) memcpy(pM->zText,pM->zBase,pM->nChar);
748  }else{
749  pM->zText = realloc(pM->zText, pM->nAlloc);
750  }
751  }
752  if( pM->zText ){
753  memcpy(&pM->zText[pM->nChar], zNewText, nNewChar);
754  pM->nChar += nNewChar;
755  pM->zText[pM->nChar] = 0;
756  }
757 }
758 
759 /*
760 ** mprintf() works like printf(), but allocations memory to hold the
761 ** resulting string and returns a pointer to the allocated memory.
762 **
763 ** We changed the name to TclMPrint() to conform with the Tcl private
764 ** routine naming conventions.
765 */
766 
767 /* This is the varargs version of mprintf.
768 **
769 ** The name is changed to TclVMPrintf() to conform with Tcl naming
770 ** conventions.
771 */
772 int vasprintf(char ** out, const char *zFormat,va_list ap){
773  struct sgMprintf sMprintf;
774  char zBuf[200];
775  int r;
776  sMprintf.nChar = 0;
777  sMprintf.zText = zBuf;
778  sMprintf.nAlloc = sizeof(zBuf);
779  sMprintf.zBase = zBuf;
780  r = vxprintf(mout,&sMprintf,zFormat,ap);
781  if( sMprintf.zText==sMprintf.zBase ){
782  sMprintf.zText = malloc( strlen(zBuf)+1 );
783  if( sMprintf.zText ) strcpy(sMprintf.zText,zBuf);
784  }else{
785  sMprintf.zText = realloc(sMprintf.zText,sMprintf.nChar+1);
786  }
787  *out = sMprintf.zText;
788  return r;
789 }
790 
791 /*
792 ** The following section of code handles the standard fprintf routines
793 ** for pthreads.
794 */
795 
796 /* The xprintf callback function. */
797 static void fout(zNewText,nNewChar,arg)
798  char *zNewText;
799  int nNewChar;
800  void *arg;
801 {
802  write(*(int*)arg,zNewText,nNewChar);
803 }
804 
805 /* The public interface routines */
806 int vdprintf(int fd, const char *zFormat, va_list ap){
807  return vxprintf(fout,&fd,zFormat,ap);
808 }