snprintf.c

Go to the documentation of this file.
00001 /*
00002  * NOTE: If you change this file, please merge it into rsync, samba, etc.
00003  */
00004 
00005 /*
00006  * Copyright Patrick Powell 1995
00007  * This code is based on code written by Patrick Powell (papowell@astart.com)
00008  * It may be used for any purpose as long as this notice remains intact
00009  * on all source code distributions
00010  */
00011 
00012 /**************************************************************
00013  * Original:
00014  * Patrick Powell Tue Apr 11 09:48:21 PDT 1995
00015  * A bombproof version of doprnt (dopr) included.
00016  * Sigh.  This sort of thing is always nasty do deal with.  Note that
00017  * the version here does not include floating point...
00018  *
00019  * snprintf() is used instead of sprintf() as it does limit checks
00020  * for string length.  This covers a nasty loophole.
00021  *
00022  * The other functions are there to prevent NULL pointers from
00023  * causing nast effects.
00024  *
00025  * More Recently:
00026  *  Brandon Long <blong@fiction.net> 9/15/96 for mutt 0.43
00027  *  This was ugly.  It is still ugly.  I opted out of floating point
00028  *  numbers, but the formatter understands just about everything
00029  *  from the normal C string format, at least as far as I can tell from
00030  *  the Solaris 2.5 printf(3S) man page.
00031  *
00032  *  Brandon Long <blong@fiction.net> 10/22/97 for mutt 0.87.1
00033  *    Ok, added some minimal floating point support, which means this
00034  *    probably requires libm on most operating systems.  Don't yet
00035  *    support the exponent (e,E) and sigfig (g,G).  Also, fmtint()
00036  *    was pretty badly broken, it just wasn't being exercised in ways
00037  *    which showed it, so that's been fixed.  Also, formated the code
00038  *    to mutt conventions, and removed dead code left over from the
00039  *    original.  Also, there is now a builtin-test, just compile with:
00040  *           gcc -DTEST_SNPRINTF -o snprintf snprintf.c -lm
00041  *    and run snprintf for results.
00042  * 
00043  *  Thomas Roessler <roessler@guug.de> 01/27/98 for mutt 0.89i
00044  *    The PGP code was using unsigned hexadecimal formats. 
00045  *    Unfortunately, unsigned formats simply didn't work.
00046  *
00047  *  Michael Elkins <me@cs.hmc.edu> 03/05/98 for mutt 0.90.8
00048  *    The original code assumed that both snprintf() and vsnprintf() were
00049  *    missing.  Some systems only have snprintf() but not vsnprintf(), so
00050  *    the code is now broken down under HAVE_SNPRINTF and HAVE_VSNPRINTF.
00051  *
00052  *  Andrew Tridgell (tridge@samba.org) Oct 1998
00053  *    fixed handling of %.0f
00054  *    added test for HAVE_LONG_DOUBLE
00055  *
00056  * tridge@samba.org, idra@samba.org, April 2001
00057  *    got rid of fcvt code (twas buggy and made testing harder)
00058  *    added C99 semantics
00059  *
00060  * date: 2002/12/19 19:56:31;  author: herb;  state: Exp;  lines: +2 -0
00061  * actually print args for %g and %e
00062  * 
00063  * date: 2002/06/03 13:37:52;  author: jmcd;  state: Exp;  lines: +8 -0
00064  * Since includes.h isn't included here, VA_COPY has to be defined here.  I don't
00065  * see any include file that is guaranteed to be here, so I'm defining it
00066  * locally.  Fixes AIX and Solaris builds.
00067  * 
00068  * date: 2002/06/03 03:07:24;  author: tridge;  state: Exp;  lines: +5 -13
00069  * put the ifdef for HAVE_VA_COPY in one place rather than in lots of
00070  * functions
00071  * 
00072  * date: 2002/05/17 14:51:22;  author: jmcd;  state: Exp;  lines: +21 -4
00073  * Fix usage of va_list passed as an arg.  Use __va_copy before using it
00074  * when it exists.
00075  * 
00076  * date: 2002/04/16 22:38:04;  author: idra;  state: Exp;  lines: +20 -14
00077  * Fix incorrect zpadlen handling in fmtfp.
00078  * Thanks to Ollie Oldham <ollie.oldham@metro-optix.com> for spotting it.
00079  * few mods to make it easier to compile the tests.
00080  * addedd the "Ollie" test to the floating point ones.
00081  *
00082  * Martin Pool (mbp@samba.org) April 2003
00083  *    Remove NO_CONFIG_H so that the test case can be built within a source
00084  *    tree with less trouble.
00085  *    Remove unnecessary SAFE_FREE() definition.
00086  *
00087  * Martin Pool (mbp@samba.org) May 2003
00088  *    Put in a prototype for dummy_snprintf() to quiet compiler warnings.
00089  *
00090  *    Move #endif to make sure VA_COPY, LDOUBLE, etc are defined even
00091  *    if the C library has some snprintf functions already.
00092  **************************************************************/
00093 
00094 #define NULL 0
00095 
00096 #ifdef TEST_SNPRINTF /* need math library headers for testing */
00097 
00098 /* In test mode, we pretend that this system doesn't have any snprintf
00099  * functions, regardless of what config.h says. */
00100 #  undef HAVE_SNPRINTF
00101 #  undef HAVE_VSNPRINTF
00102 #  undef HAVE_C99_VSNPRINTF
00103 #  undef HAVE_ASPRINTF
00104 #  undef HAVE_VASPRINTF
00105 #  include <math.h>
00106 #endif /* TEST_SNPRINTF */
00107 
00108 #include <stddef.h>
00109 #include <string.h>
00110 #include <sys/types.h>
00111 #include <stdarg.h>
00112 #include <stdlib.h>
00113 #include <ctype.h>
00114 
00115 #if defined(HAVE_SNPRINTF) && defined(HAVE_VSNPRINTF)
00116 /* only include stdio.h if we are not re-defining snprintf or vsnprintf */
00117 #include <stdio.h>
00118  /* make the compiler happy with an empty file */
00119  void dummy_snprintf(void);
00120  void dummy_snprintf(void) {} 
00121 #endif /* HAVE_SNPRINTF, etc */
00122 
00123 #ifdef HAVE_LONG_DOUBLE
00124 #define LDOUBLE long double
00125 #else
00126 #define LDOUBLE double
00127 #endif
00128 
00129 #ifdef HAVE_LONG_LONG
00130 #define LLONG long long
00131 #else
00132 #define LLONG long
00133 #endif
00134 
00135 #ifndef VA_COPY
00136 #ifdef HAVE_VA_COPY
00137 #define VA_COPY(dest, src) va_copy(dest, src)
00138 #else
00139 #ifdef HAVE___VA_COPY
00140 #define VA_COPY(dest, src) __va_copy(dest, src)
00141 #else
00142 #define VA_COPY(dest, src) (dest) = (src)
00143 #endif
00144 #endif
00145 
00146 /*
00147  * dopr(): poor man's version of doprintf
00148  */
00149 
00150 /* format read states */
00151 #define DP_S_DEFAULT 0
00152 #define DP_S_FLAGS   1
00153 #define DP_S_MIN     2
00154 #define DP_S_DOT     3
00155 #define DP_S_MAX     4
00156 #define DP_S_MOD     5
00157 #define DP_S_CONV    6
00158 #define DP_S_DONE    7
00159 
00160 /* format flags - Bits */
00161 #define DP_F_MINUS      (1 << 0)
00162 #define DP_F_PLUS       (1 << 1)
00163 #define DP_F_SPACE      (1 << 2)
00164 #define DP_F_NUM        (1 << 3)
00165 #define DP_F_ZERO       (1 << 4)
00166 #define DP_F_UP         (1 << 5)
00167 #define DP_F_UNSIGNED   (1 << 6)
00168 
00169 /* Conversion Flags */
00170 #define DP_C_SHORT   1
00171 #define DP_C_LONG    2
00172 #define DP_C_LDOUBLE 3
00173 #define DP_C_LLONG   4
00174 
00175 #define char_to_int(p) ((p)- '0')
00176 #ifndef MAX
00177 #define MAX(p,q) (((p) >= (q)) ? (p) : (q))
00178 #endif
00179 
00180 /* yes this really must be a ||. Don't muck with this (tridge) */
00181 #if !defined(HAVE_VSNPRINTF)
00182 
00183 static size_t dopr(char *buffer, size_t maxlen, const char *format, 
00184                    va_list args_in);
00185 static void fmtstr(char *buffer, size_t *currlen, size_t maxlen,
00186                     char *value, int flags, int min, int max);
00187 static void fmtint(char *buffer, size_t *currlen, size_t maxlen,
00188                     long value, int base, int min, int max, int flags);
00189 static void fmtfp(char *buffer, size_t *currlen, size_t maxlen,
00190                    LDOUBLE fvalue, int min, int max, int flags);
00191 static void dopr_outch(char *buffer, size_t *currlen, size_t maxlen, char c);
00192 
00193 static size_t dopr(char *buffer, size_t maxlen, const char *format, va_list args_in)
00194 {
00195         char ch;
00196         LLONG value;
00197         LDOUBLE fvalue;
00198         char *strvalue;
00199         int min;
00200         int max;
00201         int state;
00202         int flags;
00203         int cflags;
00204         size_t currlen;
00205         va_list args;
00206 
00207         VA_COPY(args, args_in);
00208         
00209         state = DP_S_DEFAULT;
00210         currlen = flags = cflags = min = 0;
00211         max = -1;
00212         ch = *format++;
00213         
00214         while (state != DP_S_DONE) {
00215                 if (ch == '\0') 
00216                         state = DP_S_DONE;
00217 
00218                 switch(state) {
00219                 case DP_S_DEFAULT:
00220                         if (ch == '%') 
00221                                 state = DP_S_FLAGS;
00222                         else 
00223                                 dopr_outch (buffer, &currlen, maxlen, ch);
00224                         ch = *format++;
00225                         break;
00226                 case DP_S_FLAGS:
00227                         switch (ch) {
00228                         case '-':
00229                                 flags |= DP_F_MINUS;
00230                                 ch = *format++;
00231                                 break;
00232                         case '+':
00233                                 flags |= DP_F_PLUS;
00234                                 ch = *format++;
00235                                 break;
00236                         case ' ':
00237                                 flags |= DP_F_SPACE;
00238                                 ch = *format++;
00239                                 break;
00240                         case '#':
00241                                 flags |= DP_F_NUM;
00242                                 ch = *format++;
00243                                 break;
00244                         case '0':
00245                                 flags |= DP_F_ZERO;
00246                                 ch = *format++;
00247                                 break;
00248                         default:
00249                                 state = DP_S_MIN;
00250                                 break;
00251                         }
00252                         break;
00253                 case DP_S_MIN:
00254                         if (isdigit((unsigned char)ch)) {
00255                                 min = 10*min + char_to_int (ch);
00256                                 ch = *format++;
00257                         } else if (ch == '*') {
00258                                 min = va_arg (args, int);
00259                                 ch = *format++;
00260                                 state = DP_S_DOT;
00261                         } else {
00262                                 state = DP_S_DOT;
00263                         }
00264                         break;
00265                 case DP_S_DOT:
00266                         if (ch == '.') {
00267                                 state = DP_S_MAX;
00268                                 ch = *format++;
00269                         } else { 
00270                                 state = DP_S_MOD;
00271                         }
00272                         break;
00273                 case DP_S_MAX:
00274                         if (isdigit((unsigned char)ch)) {
00275                                 if (max < 0)
00276                                         max = 0;
00277                                 max = 10*max + char_to_int (ch);
00278                                 ch = *format++;
00279                         } else if (ch == '*') {
00280                                 max = va_arg (args, int);
00281                                 ch = *format++;
00282                                 state = DP_S_MOD;
00283                         } else {
00284                                 state = DP_S_MOD;
00285                         }
00286                         break;
00287                 case DP_S_MOD:
00288                         switch (ch) {
00289                         case 'h':
00290                                 cflags = DP_C_SHORT;
00291                                 ch = *format++;
00292                                 break;
00293                         case 'l':
00294                                 cflags = DP_C_LONG;
00295                                 ch = *format++;
00296                                 if (ch == 'l') {        /* It's a long long */
00297                                         cflags = DP_C_LLONG;
00298                                         ch = *format++;
00299                                 }
00300                                 break;
00301                         case 'L':
00302                                 cflags = DP_C_LDOUBLE;
00303                                 ch = *format++;
00304                                 break;
00305                         default:
00306                                 break;
00307                         }
00308                         state = DP_S_CONV;
00309                         break;
00310                 case DP_S_CONV:
00311                         switch (ch) {
00312                         case 'd':
00313                         case 'i':
00314                                 if (cflags == DP_C_SHORT) 
00315                                         value = va_arg (args, int);
00316                                 else if (cflags == DP_C_LONG)
00317                                         value = va_arg (args, long int);
00318                                 else if (cflags == DP_C_LLONG)
00319                                         value = va_arg (args, LLONG);
00320                                 else
00321                                         value = va_arg (args, int);
00322                                 fmtint (buffer, &currlen, maxlen, value, 10, min, max, flags);
00323                                 break;
00324                         case 'o':
00325                                 flags |= DP_F_UNSIGNED;
00326                                 if (cflags == DP_C_SHORT)
00327                                         value = va_arg (args, unsigned int);
00328                                 else if (cflags == DP_C_LONG)
00329                                         value = (long)va_arg (args, unsigned long int);
00330                                 else if (cflags == DP_C_LLONG)
00331                                         value = (long)va_arg (args, unsigned LLONG);
00332                                 else
00333                                         value = (long)va_arg (args, unsigned int);
00334                                 fmtint (buffer, &currlen, maxlen, value, 8, min, max, flags);
00335                                 break;
00336                         case 'u':
00337                                 flags |= DP_F_UNSIGNED;
00338                                 if (cflags == DP_C_SHORT)
00339                                         value = va_arg (args, unsigned int);
00340                                 else if (cflags == DP_C_LONG)
00341                                         value = (long)va_arg (args, unsigned long int);
00342                                 else if (cflags == DP_C_LLONG)
00343                                         value = (LLONG)va_arg (args, unsigned LLONG);
00344                                 else
00345                                         value = (long)va_arg (args, unsigned int);
00346                                 fmtint (buffer, &currlen, maxlen, value, 10, min, max, flags);
00347                                 break;
00348                         case 'X':
00349                                 flags |= DP_F_UP;
00350                         case 'x':
00351                                 flags |= DP_F_UNSIGNED;
00352                                 if (cflags == DP_C_SHORT)
00353                                         value = va_arg (args, unsigned int);
00354                                 else if (cflags == DP_C_LONG)
00355                                         value = (long)va_arg (args, unsigned long int);
00356                                 else if (cflags == DP_C_LLONG)
00357                                         value = (LLONG)va_arg (args, unsigned LLONG);
00358                                 else
00359                                         value = (long)va_arg (args, unsigned int);
00360                                 fmtint (buffer, &currlen, maxlen, value, 16, min, max, flags);
00361                                 break;
00362                         case 'f':
00363                                 if (cflags == DP_C_LDOUBLE)
00364                                         fvalue = va_arg (args, LDOUBLE);
00365                                 else
00366                                         fvalue = va_arg (args, double);
00367                                 /* um, floating point? */
00368                                 fmtfp (buffer, &currlen, maxlen, fvalue, min, max, flags);
00369                                 break;
00370                         case 'E':
00371                                 flags |= DP_F_UP;
00372                         case 'e':
00373                                 if (cflags == DP_C_LDOUBLE)
00374                                         fvalue = va_arg (args, LDOUBLE);
00375                                 else
00376                                         fvalue = va_arg (args, double);
00377                                 fmtfp (buffer, &currlen, maxlen, fvalue, min, max, flags);
00378                                 break;
00379                         case 'G':
00380                                 flags |= DP_F_UP;
00381                         case 'g':
00382                                 if (cflags == DP_C_LDOUBLE)
00383                                         fvalue = va_arg (args, LDOUBLE);
00384                                 else
00385                                         fvalue = va_arg (args, double);
00386                                 fmtfp (buffer, &currlen, maxlen, fvalue, min, max, flags);
00387                                 break;
00388                         case 'c':
00389                                 dopr_outch (buffer, &currlen, maxlen, va_arg (args, int));
00390                                 break;
00391                         case 's':
00392                                 strvalue = va_arg (args, char *);
00393                                 if (!strvalue) strvalue = "(NULL)";
00394                                 if (max == -1) {
00395                                         max = (int) strlen(strvalue);
00396                                 }
00397                                 if (min > 0 && max >= 0 && min > max) max = min;
00398                                 fmtstr (buffer, &currlen, maxlen, strvalue, flags, min, max);
00399                                 break;
00400                         case 'p':
00401                                 strvalue = va_arg (args, void *);
00402                                 fmtint (buffer, &currlen, maxlen, (long) strvalue, 16, min, max, flags);
00403                                 break;
00404                         case 'n':
00405                                 if (cflags == DP_C_SHORT) {
00406                                         short int *num;
00407                                         num = va_arg (args, short int *);
00408                                         *num = (short int) currlen;
00409                                 } else if (cflags == DP_C_LONG) {
00410                                         long int *num;
00411                                         num = va_arg (args, long int *);
00412                                         *num = (long int)currlen;
00413                                 } else if (cflags == DP_C_LLONG) {
00414                                         LLONG *num;
00415                                         num = va_arg (args, LLONG *);
00416                                         *num = (LLONG)currlen;
00417                                 } else {
00418                                         int *num;
00419                                         num = va_arg (args, int *);
00420                                         *num = (int) currlen;
00421                                 }
00422                                 break;
00423                         case '%':
00424                                 dopr_outch (buffer, &currlen, maxlen, ch);
00425                                 break;
00426                         case 'w':
00427                                 /* not supported yet, treat as next char */
00428                                 ch = *format++;
00429                                 break;
00430                         default:
00431                                 /* Unknown, skip */
00432                                 break;
00433                         }
00434                         ch = *format++;
00435                         state = DP_S_DEFAULT;
00436                         flags = cflags = min = 0;
00437                         max = -1;
00438                         break;
00439                 case DP_S_DONE:
00440                         break;
00441                 default:
00442                         /* hmm? */
00443                         break; /* some picky compilers need this */
00444                 }
00445         }
00446         if (maxlen != 0) {
00447                 if (currlen < maxlen - 1) 
00448                         buffer[currlen] = '\0';
00449                 else if (maxlen > 0) 
00450                         buffer[maxlen - 1] = '\0';
00451         }
00452         
00453         return currlen;
00454 }
00455 
00456 static void fmtstr(char *buffer, size_t *currlen, size_t maxlen,
00457                     char *value, int flags, int min, int max)
00458 {
00459         int padlen, strln;     /* amount to pad */
00460         int cnt = 0;
00461 
00462 #ifdef DEBUG_SNPRINTF
00463         printf("fmtstr min=%d max=%d s=[%s]\n", min, max, value);
00464 #endif
00465         if (value == 0) {
00466                 value = "<NULL>";
00467         }
00468 
00469         for (strln = 0; value[strln]; ++strln); /* strlen */
00470         padlen = min - strln;
00471         if (padlen < 0) 
00472                 padlen = 0;
00473         if (flags & DP_F_MINUS) 
00474                 padlen = -padlen; /* Left Justify */
00475         
00476         while ((padlen > 0) && (cnt < max)) {
00477                 dopr_outch (buffer, currlen, maxlen, ' ');
00478                 --padlen;
00479                 ++cnt;
00480         }
00481         while (*value && (cnt < max)) {
00482                 dopr_outch (buffer, currlen, maxlen, *value++);
00483                 ++cnt;
00484         }
00485         while ((padlen < 0) && (cnt < max)) {
00486                 dopr_outch (buffer, currlen, maxlen, ' ');
00487                 ++padlen;
00488                 ++cnt;
00489         }
00490 }
00491 
00492 /* Have to handle DP_F_NUM (ie 0x and 0 alternates) */
00493 
00494 static void fmtint(char *buffer, size_t *currlen, size_t maxlen,
00495                     long value, int base, int min, int max, int flags)
00496 {
00497         int signvalue = 0;
00498         unsigned long uvalue;
00499         char convert[20];
00500         int place = 0;
00501         int spadlen = 0; /* amount to space pad */
00502         int zpadlen = 0; /* amount to zero pad */
00503         int caps = 0;
00504         
00505         if (max < 0)
00506                 max = 0;
00507         
00508         uvalue = value;
00509         
00510         if(!(flags & DP_F_UNSIGNED)) {
00511                 if( value < 0 ) {
00512                         signvalue = '-';
00513                         uvalue = -value;
00514                 } else {
00515                         if (flags & DP_F_PLUS)  /* Do a sign (+/i) */
00516                                 signvalue = '+';
00517                         else if (flags & DP_F_SPACE)
00518                                 signvalue = ' ';
00519                 }
00520         }
00521   
00522         if (flags & DP_F_UP) caps = 1; /* Should characters be upper case? */
00523 
00524         do {
00525                 convert[place++] =
00526                         (caps? "0123456789ABCDEF":"0123456789abcdef")
00527                         [uvalue % (unsigned)base  ];
00528                 uvalue = (uvalue / (unsigned)base );
00529         } while(uvalue && (place < 20));
00530         if (place == 20) place--;
00531         convert[place] = 0;
00532 
00533         zpadlen = max - place;
00534         spadlen = min - MAX (max, place) - (signvalue ? 1 : 0);
00535         if (zpadlen < 0) zpadlen = 0;
00536         if (spadlen < 0) spadlen = 0;
00537         if (flags & DP_F_ZERO) {
00538                 zpadlen = MAX(zpadlen, spadlen);
00539                 spadlen = 0;
00540         }
00541         if (flags & DP_F_MINUS) 
00542                 spadlen = -spadlen; /* Left Justifty */
00543 
00544 #ifdef DEBUG_SNPRINTF
00545         printf("zpad: %d, spad: %d, min: %d, max: %d, place: %d\n",
00546                zpadlen, spadlen, min, max, place);
00547 #endif
00548 
00549         /* Spaces */
00550         while (spadlen > 0) {
00551                 dopr_outch (buffer, currlen, maxlen, ' ');
00552                 --spadlen;
00553         }
00554 
00555         /* Sign */
00556         if (signvalue) 
00557                 dopr_outch (buffer, currlen, maxlen, signvalue);
00558 
00559         /* Zeros */
00560         if (zpadlen > 0) {
00561                 while (zpadlen > 0) {
00562                         dopr_outch (buffer, currlen, maxlen, '0');
00563                         --zpadlen;
00564                 }
00565         }
00566 
00567         /* Digits */
00568         while (place > 0) 
00569                 dopr_outch (buffer, currlen, maxlen, convert[--place]);
00570   
00571         /* Left Justified spaces */
00572         while (spadlen < 0) {
00573                 dopr_outch (buffer, currlen, maxlen, ' ');
00574                 ++spadlen;
00575         }
00576 }
00577 
00578 static LDOUBLE abs_val(LDOUBLE value)
00579 {
00580         LDOUBLE result = value;
00581 
00582         if (value < 0)
00583                 result = -value;
00584         
00585         return result;
00586 }
00587 
00588 static LDOUBLE POW10(int exp)
00589 {
00590         LDOUBLE result = 1;
00591         
00592         while (exp) {
00593                 result *= 10;
00594                 exp--;
00595         }
00596   
00597         return result;
00598 }
00599 
00600 static LLONG ROUND(LDOUBLE value)
00601 {
00602         LLONG intpart;
00603 
00604         intpart = (LLONG)value;
00605         value = value - intpart;
00606         if (value >= 0.5) intpart++;
00607         
00608         return intpart;
00609 }
00610 
00611 /* a replacement for modf that doesn't need the math library. Should
00612    be portable, but slow */
00613 static double my_modf(double x0, double *iptr)
00614 {
00615         int i;
00616         long l;
00617         double x = x0;
00618         double f = 1.0;
00619 
00620         for (i=0;i<100;i++) {
00621                 l = (long)x;
00622                 if (l <= (x+1) && l >= (x-1)) break;
00623                 x *= 0.1;
00624                 f *= 10.0;
00625         }
00626 
00627         if (i == 100) {
00628                 /* yikes! the number is beyond what we can handle. What do we do? */
00629                 (*iptr) = 0;
00630                 return 0;
00631         }
00632 
00633         if (i != 0) {
00634                 double i2;
00635                 double ret;
00636 
00637                 ret = my_modf(x0-l*f, &i2);
00638                 (*iptr) = l*f + i2;
00639                 return ret;
00640         } 
00641 
00642         (*iptr) = l;
00643         return x - (*iptr);
00644 }
00645 
00646 
00647 static void fmtfp (char *buffer, size_t *currlen, size_t maxlen,
00648                    LDOUBLE fvalue, int min, int max, int flags)
00649 {
00650         int signvalue = 0;
00651         double ufvalue;
00652         char iconvert[311];
00653         char fconvert[311];
00654         int iplace = 0;
00655         int fplace = 0;
00656         int padlen = 0; /* amount to pad */
00657         int zpadlen = 0; 
00658         int caps = 0;
00659         int idx;
00660         double intpart;
00661         double fracpart;
00662         double temp;
00663   
00664         /* 
00665          * AIX manpage says the default is 0, but Solaris says the default
00666          * is 6, and sprintf on AIX defaults to 6
00667          */
00668         if (max < 0)
00669                 max = 6;
00670 
00671         ufvalue = abs_val (fvalue);
00672 
00673         if (fvalue < 0) {
00674                 signvalue = '-';
00675         } else {
00676                 if (flags & DP_F_PLUS) { /* Do a sign (+/i) */
00677                         signvalue = '+';
00678                 } else {
00679                         if (flags & DP_F_SPACE)
00680                                 signvalue = ' ';
00681                 }
00682         }
00683 
00684 #if 0
00685         if (flags & DP_F_UP) caps = 1; /* Should characters be upper case? */
00686 #endif
00687 
00688 #if 0
00689          if (max == 0) ufvalue += 0.5; /* if max = 0 we must round */
00690 #endif
00691 
00692         /* 
00693          * Sorry, we only support 16 digits past the decimal because of our 
00694          * conversion method
00695          */
00696         if (max > 16)
00697                 max = 16;
00698 
00699         /* We "cheat" by converting the fractional part to integer by
00700          * multiplying by a factor of 10
00701          */
00702 
00703         temp = ufvalue;
00704         my_modf(temp, &intpart);
00705 
00706         fracpart = ROUND((POW10(max)) * (ufvalue - intpart));
00707         
00708         if (fracpart >= POW10(max)) {
00709                 intpart++;
00710                 fracpart -= POW10(max);
00711         }
00712 
00713 
00714         /* Convert integer part */
00715         do {
00716                 temp = intpart*0.1;
00717                 my_modf(temp, &intpart);
00718                 idx = (int) ((temp -intpart +0.05)* 10.0);
00719                 /* idx = (int) (((double)(temp*0.1) -intpart +0.05) *10.0); */
00720                 /* printf ("%llf, %f, %x\n", temp, intpart, idx); */
00721                 iconvert[iplace++] =
00722                         (caps? "0123456789ABCDEF":"0123456789abcdef")[idx];
00723         } while (intpart && (iplace < 311));
00724         if (iplace == 311) iplace--;
00725         iconvert[iplace] = 0;
00726 
00727         /* Convert fractional part */
00728         if (fracpart)
00729         {
00730                 do {
00731                         temp = fracpart*0.1;
00732                         my_modf(temp, &fracpart);
00733                         idx = (int) ((temp -fracpart +0.05)* 10.0);
00734                         /* idx = (int) ((((temp/10) -fracpart) +0.05) *10); */
00735                         /* printf ("%lf, %lf, %ld\n", temp, fracpart, idx ); */
00736                         fconvert[fplace++] =
00737                         (caps? "0123456789ABCDEF":"0123456789abcdef")[idx];
00738                 } while(fracpart && (fplace < 311));
00739                 if (fplace == 311) fplace--;
00740         }
00741         fconvert[fplace] = 0;
00742   
00743         /* -1 for decimal point, another -1 if we are printing a sign */
00744         padlen = min - iplace - max - 1 - ((signvalue) ? 1 : 0); 
00745         zpadlen = max - fplace;
00746         if (zpadlen < 0) zpadlen = 0;
00747         if (padlen < 0) 
00748                 padlen = 0;
00749         if (flags & DP_F_MINUS) 
00750                 padlen = -padlen; /* Left Justifty */
00751         
00752         if ((flags & DP_F_ZERO) && (padlen > 0)) {
00753                 if (signvalue) {
00754                         dopr_outch (buffer, currlen, maxlen, signvalue);
00755                         --padlen;
00756                         signvalue = 0;
00757                 }
00758                 while (padlen > 0) {
00759                         dopr_outch (buffer, currlen, maxlen, '0');
00760                         --padlen;
00761                 }
00762         }
00763         while (padlen > 0) {
00764                 dopr_outch (buffer, currlen, maxlen, ' ');
00765                 --padlen;
00766         }
00767         if (signvalue) 
00768                 dopr_outch (buffer, currlen, maxlen, signvalue);
00769         
00770         while (iplace > 0) 
00771                 dopr_outch (buffer, currlen, maxlen, iconvert[--iplace]);
00772 
00773 #ifdef DEBUG_SNPRINTF
00774         printf("fmtfp: fplace=%d zpadlen=%d\n", fplace, zpadlen);
00775 #endif
00776 
00777         /*
00778          * Decimal point.  This should probably use locale to find the correct
00779          * char to print out.
00780          */
00781         if (max > 0) {
00782                 dopr_outch (buffer, currlen, maxlen, '.');
00783                 
00784                 while (zpadlen > 0) {
00785                         dopr_outch (buffer, currlen, maxlen, '0');
00786                         --zpadlen;
00787                 }
00788 
00789                 while (fplace > 0) 
00790                         dopr_outch (buffer, currlen, maxlen, fconvert[--fplace]);
00791         }
00792 
00793         while (padlen < 0) {
00794                 dopr_outch (buffer, currlen, maxlen, ' ');
00795                 ++padlen;
00796         }
00797 }
00798 
00799 static void dopr_outch(char *buffer, size_t *currlen, size_t maxlen, char c)
00800 {
00801         if (*currlen < maxlen) {
00802                 buffer[(*currlen)] = c;
00803         }
00804         (*currlen)++;
00805 }
00806 
00807  int smb_vsnprintf (char *str, size_t count, const char *fmt, va_list args)
00808 {
00809         return (int) dopr(str, count, fmt, args);
00810 }
00811 #define vsnprintf smb_vsnprintf
00812 #endif
00813 
00814 /* yes this really must be a ||. Don't muck with this (tridge)
00815  *
00816  * The logic for these two is that we need our own definition if the
00817  * OS *either* has no definition of *sprintf, or if it does have one
00818  * that doesn't work properly according to the autoconf test.
00819  */
00820 #if !defined(HAVE_SNPRINTF)
00821 int smb_snprintf(char *str,size_t count,const char *fmt,...)
00822 {
00823         size_t ret;
00824         va_list ap;
00825     
00826         va_start(ap, fmt);
00827         ret = vsnprintf(str, count, fmt, ap);
00828         va_end(ap);
00829         return (int) ret;
00830 }
00831 #define snprintf smb_snprintf
00832 #endif
00833 
00834 #endif 
00835 
00836 #ifndef HAVE_VASPRINTF
00837  int vasprintf(char **ptr, const char *format, va_list ap)
00838 {
00839         int ret;
00840         va_list ap2;
00841 
00842         VA_COPY(ap2, ap);
00843         
00844         ret = vsnprintf(NULL, 0, format, ap2);
00845         if (ret <= 0) return ret;
00846 
00847         (*ptr) = (char *)malloc(ret+1);
00848         if (!*ptr) return -1;
00849 
00850         VA_COPY(ap2, ap);
00851 
00852         ret = vsnprintf(*ptr, ret+1, format, ap2);
00853 
00854         return ret;
00855 }
00856 #endif
00857 
00858 
00859 #ifndef HAVE_ASPRINTF
00860  int asprintf(char **ptr, const char *format, ...)
00861 {
00862         va_list ap;
00863         int ret;
00864         
00865         *ptr = NULL;
00866         va_start(ap, format);
00867         ret = vasprintf(ptr, format, ap);
00868         va_end(ap);
00869 
00870         return ret;
00871 }
00872 #endif
00873 
00874 #ifdef TEST_SNPRINTF
00875 
00876  int sprintf(char *str,const char *fmt,...);
00877 
00878  int main (void)
00879 {
00880         char buf1[1024];
00881         char buf2[1024];
00882         char *fp_fmt[] = {
00883                 "%1.1f",
00884                 "%-1.5f",
00885                 "%1.5f",
00886                 "%123.9f",
00887                 "%10.5f",
00888                 "% 10.5f",
00889                 "%+22.9f",
00890                 "%+4.9f",
00891                 "%01.3f",
00892                 "%4f",
00893                 "%3.1f",
00894                 "%3.2f",
00895                 "%.0f",
00896                 "%f",
00897                 "-16.16f",
00898                 NULL
00899         };
00900         double fp_nums[] = { 6442452944.1234, -1.5, 134.21, 91340.2, 341.1234, 203.9, 0.96, 0.996, 
00901                              0.9996, 1.996, 4.136, 5.030201, 0.00205,
00902                              /* END LIST */ 0};
00903         char *int_fmt[] = {
00904                 "%-1.5d",
00905                 "%1.5d",
00906                 "%123.9d",
00907                 "%5.5d",
00908                 "%10.5d",
00909                 "% 10.5d",
00910                 "%+22.33d",
00911                 "%01.3d",
00912                 "%4d",
00913                 "%d",
00914                 NULL
00915         };
00916         long int_nums[] = { -1, 134, 91340, 341, 0203, 0};
00917         char *str_fmt[] = {
00918                 "10.5s",
00919                 "5.10s",
00920                 "10.1s",
00921                 "0.10s",
00922                 "10.0s",
00923                 "1.10s",
00924                 "%s",
00925                 "%.1s",
00926                 "%.10s",
00927                 "%10s",
00928                 NULL
00929         };
00930         char *str_vals[] = {"hello", "a", "", "a longer string", NULL};
00931         int x, y;
00932         int fail = 0;
00933         int num = 0;
00934 
00935         printf ("Testing snprintf format codes against system sprintf...\n");
00936 
00937         for (x = 0; fp_fmt[x] ; x++) {
00938                 for (y = 0; fp_nums[y] != 0 ; y++) {
00939                         int l1 = snprintf(NULL, 0, fp_fmt[x], fp_nums[y]);
00940                         int l2 = snprintf(buf1, sizeof(buf1), fp_fmt[x], fp_nums[y]);
00941                         sprintf (buf2, fp_fmt[x], fp_nums[y]);
00942                         if (strcmp (buf1, buf2)) {
00943                                 printf("snprintf doesn't match Format: %s\n\tsnprintf = [%s]\n\t sprintf = [%s]\n", 
00944                                        fp_fmt[x], buf1, buf2);
00945                                 fail++;
00946                         }
00947                         if (l1 != l2) {
00948                                 printf("snprintf l1 != l2 (%d %d) %s\n", l1, l2, fp_fmt[x]);
00949                                 fail++;
00950                         }
00951                         num++;
00952                 }
00953         }
00954 
00955         for (x = 0; int_fmt[x] ; x++) {
00956                 for (y = 0; int_nums[y] != 0 ; y++) {
00957                         int l1 = snprintf(NULL, 0, int_fmt[x], int_nums[y]);
00958                         int l2 = snprintf(buf1, sizeof(buf1), int_fmt[x], int_nums[y]);
00959                         sprintf (buf2, int_fmt[x], int_nums[y]);
00960                         if (strcmp (buf1, buf2)) {
00961                                 printf("snprintf doesn't match Format: %s\n\tsnprintf = [%s]\n\t sprintf = [%s]\n", 
00962                                        int_fmt[x], buf1, buf2);
00963                                 fail++;
00964                         }
00965                         if (l1 != l2) {
00966                                 printf("snprintf l1 != l2 (%d %d) %s\n", l1, l2, int_fmt[x]);
00967                                 fail++;
00968                         }
00969                         num++;
00970                 }
00971         }
00972 
00973         for (x = 0; str_fmt[x] ; x++) {
00974                 for (y = 0; str_vals[y] != 0 ; y++) {
00975                         int l1 = snprintf(NULL, 0, str_fmt[x], str_vals[y]);
00976                         int l2 = snprintf(buf1, sizeof(buf1), str_fmt[x], str_vals[y]);
00977                         sprintf (buf2, str_fmt[x], str_vals[y]);
00978                         if (strcmp (buf1, buf2)) {
00979                                 printf("snprintf doesn't match Format: %s\n\tsnprintf = [%s]\n\t sprintf = [%s]\n", 
00980                                        str_fmt[x], buf1, buf2);
00981                                 fail++;
00982                         }
00983                         if (l1 != l2) {
00984                                 printf("snprintf l1 != l2 (%d %d) %s\n", l1, l2, str_fmt[x]);
00985                                 fail++;
00986                         }
00987                         num++;
00988                 }
00989         }
00990 
00991         printf ("%d tests failed out of %d.\n", fail, num);
00992 
00993         printf("seeing how many digits we support\n");
00994         {
00995                 double v0 = 0.12345678901234567890123456789012345678901;
00996                 for (x=0; x<100; x++) {
00997                         double p = pow(10, x); 
00998                         double r = v0*p;
00999                         snprintf(buf1, sizeof(buf1), "%1.1f", r);
01000                         sprintf(buf2,                "%1.1f", r);
01001                         if (strcmp(buf1, buf2)) {
01002                                 printf("we seem to support %d digits\n", x-1);
01003                                 break;
01004                         }
01005                 }
01006         }
01007 
01008         return 0;
01009 }
01010 #endif /* TEST_SNPRINTF */

Generated on Mon Feb 16 15:14:49 2009 for Scorched3D by  doxygen 1.5.3