1 /*****************************************************************************/
5 /* Replacement sprintf function */
9 /* (C) 2000-2004 Ullrich von Bassewitz */
10 /* Römerstrasse 52 */
11 /* D-70794 Filderstadt */
12 /* EMail: uz@cc65.org */
15 /* This software is provided 'as-is', without any expressed or implied */
16 /* warranty. In no event will the authors be held liable for any damages */
17 /* arising from the use of this software. */
19 /* Permission is granted to anyone to use this software for any purpose, */
20 /* including commercial applications, and to alter it and redistribute it */
21 /* freely, subject to the following restrictions: */
23 /* 1. The origin of this software must not be misrepresented; you must not */
24 /* claim that you wrote the original software. If you use this software */
25 /* in a product, an acknowledgment in the product documentation would be */
26 /* appreciated but is not required. */
27 /* 2. Altered source versions must be plainly marked as such, and must not */
28 /* be misrepresented as being the original software. */
29 /* 3. This notice may not be removed or altered from any source */
32 /*****************************************************************************/
46 /*****************************************************************************/
48 /*****************************************************************************/
52 /* The following is a very basic vsnprintf like function called xvsnprintf. It
53 * features only the basic format specifiers (especially the floating point
54 * stuff is missing), but may be extended if required. Reason for supplying
55 * my own implementation is that vsnprintf is standard but not implemented by
56 * older compilers, and some that implement it in some way or the other, don't
57 * adhere to the standard (for example Microsoft with its _vsnprintf).
62 /* Variable argument list pointer */
70 /* Argument string buffer and string buffer pointer. The string buffer
71 * must be big enough to hold a converted integer of the largest type
72 * including an optional sign and terminating zero.
91 /* Conversion base and table */
93 const char* CharTable;
101 /* Length modifier */
111 /* Unsupported modifiers */
115 /* Default length is integer */
123 static void AddChar (PrintfCtrl* P, char C)
124 /* Store one character in the output buffer if there's enough room. */
126 if (++P->BufFill <= P->BufSize) {
133 static void AddPadding (PrintfCtrl* P, char C, unsigned Count)
134 /* Add some amount of padding */
143 static long NextIVal (PrintfCtrl*P)
144 /* Read the next integer value from the variable argument list */
146 switch (P->LengthMod) {
147 case lmChar: return (char) va_arg (P->ap, int);
148 case lmShort: return (short) va_arg (P->ap, int);
149 case lmInt: return (int) va_arg (P->ap, int);
150 case lmLong: return (long) va_arg (P->ap, long);
151 case lmSizeT: return (unsigned long) va_arg (P->ap, size_t);
152 case lmPtrDiffT: return (long) va_arg (P->ap, ptrdiff_t);
153 default: FAIL ("Invalid type size in NextIVal");
159 static unsigned long NextUVal (PrintfCtrl*P)
160 /* Read the next unsigned integer value from the variable argument list */
162 switch (P->LengthMod) {
163 case lmChar: return (unsigned char) va_arg (P->ap, unsigned);
164 case lmShort: return (unsigned short) va_arg (P->ap, unsigned);
165 case lmInt: return (unsigned int) va_arg (P->ap, unsigned int);
166 case lmLong: return va_arg (P->ap, unsigned long);
167 case lmSizeT: return (unsigned long) va_arg (P->ap, size_t);
168 case lmPtrDiffT: return (long) va_arg (P->ap, ptrdiff_t);
169 default: FAIL ("Invalid type size in NextUVal");
175 static void ToStr (PrintfCtrl* P, unsigned long Val)
176 /* Convert the given value to a (reversed) string */
180 *S++ = P->CharTable[Val % P->Base];
183 P->ArgLen = S - P->ArgBuf;
188 static void FormatInt (PrintfCtrl* P, unsigned long Val)
189 /* Convert the integer value */
192 unsigned LeadCount = 0;
193 unsigned PrecPadding;
194 unsigned WidthPadding;
198 /* Determine the translation table */
199 P->CharTable = (P->Flags & fUpcase)? "0123456789ABCDEF" : "0123456789abcedf";
201 /* Check if the value is negative */
202 if ((P->Flags & fUnsigned) == 0 && ((long) Val) < 0) {
204 Lead[LeadCount++] = '-';
205 } else if ((P->Flags & fPlus) != 0) {
206 Lead[LeadCount++] = '+';
207 } else if ((P->Flags & fSpace) != 0) {
208 Lead[LeadCount++] = ' ';
211 /* Convert the value into a (reversed string). */
214 /* The default precision for all integer conversions is one. This means
215 * that the fPrec flag is always set and does not need to be checked
218 if ((P->Flags & fPrec) == 0) {
223 /* Determine the leaders for alternative forms */
224 if ((P->Flags & fHash) != 0) {
227 Lead[LeadCount++] = '0';
228 Lead[LeadCount++] = (P->Flags & fUpcase)? 'X' : 'x';
229 } else if (P->Base == 8) {
230 /* Alternative form for 'o': always add a leading zero. */
231 if (P->Prec <= P->ArgLen) {
232 Lead[LeadCount++] = '0';
237 /* Determine the amount of precision padding needed */
238 if (P->ArgLen < P->Prec) {
239 PrecPadding = P->Prec - P->ArgLen;
244 /* Determine the width padding needed */
245 if ((P->Flags & fWidth) != 0) {
246 int CurWidth = LeadCount + PrecPadding + P->ArgLen;
247 if (CurWidth < P->Width) {
248 WidthPadding = P->Width - CurWidth;
256 /* Output left space padding if any */
257 if ((P->Flags & (fMinus | fZero)) == 0 && WidthPadding > 0) {
258 AddPadding (P, ' ', WidthPadding);
263 for (I = 0; I < LeadCount; ++I) {
264 AddChar (P, Lead[I]);
267 /* Left zero padding if any */
268 if ((P->Flags & fZero) != 0 && WidthPadding > 0) {
269 AddPadding (P, '0', WidthPadding);
273 /* Precision padding */
274 if (PrecPadding > 0) {
275 AddPadding (P, '0', PrecPadding);
278 /* The number itself. Beware: It's reversed! */
279 while (P->ArgLen > 0) {
280 AddChar (P, P->ArgBuf[--P->ArgLen]);
283 /* Right width padding if any */
284 if (WidthPadding > 0) {
285 AddPadding (P, ' ', WidthPadding);
291 static void FormatStr (PrintfCtrl* P, const char* Val)
292 /* Convert the string */
294 unsigned WidthPadding;
296 /* Get the string length limited to the precision. Beware: We cannot use
297 * strlen here, because if a precision is given, the string may not be
301 if ((P->Flags & fPrec) != 0) {
302 const char* S = memchr (Val, '\0', P->Prec);
304 /* Not zero terminated */
307 /* Terminating zero found */
314 /* Determine the width padding needed */
315 if ((P->Flags & fWidth) != 0 && P->Width > Len) {
316 WidthPadding = P->Width - Len;
321 /* Output left padding */
322 if ((P->Flags & fMinus) != 0 && WidthPadding > 0) {
323 AddPadding (P, ' ', WidthPadding);
327 /* Output the string */
332 /* Output right padding if any */
333 if (WidthPadding > 0) {
334 AddPadding (P, ' ', WidthPadding);
340 int xvsnprintf (char* Buf, size_t Size, const char* Format, va_list ap)
341 /* A basic vsnprintf implementation. Does currently only support integer
352 /* Initialize the control structure */
358 /* Parse the format string */
359 while ((F = *Format++) != '\0') {
362 /* Not a format specifier, just copy */
368 if (*Format == '%') {
374 /* It's a format specifier. Check for flags. */
378 while (F != '\0' && !Done) {
380 case '-': P.Flags |= fMinus; F = *Format++; break;
381 case '+': P.Flags |= fPlus; F = *Format++; break;
382 case ' ': P.Flags |= fSpace; F = *Format++; break;
383 case '#': P.Flags |= fHash; F = *Format++; break;
384 case '0': P.Flags |= fZero; F = *Format++; break;
385 default: Done = 1; break;
388 /* Optional field width */
390 P.Width = va_arg (P.ap, int);
391 /* A negative field width argument is taken as a - flag followed
392 * by a positive field width.
400 } else if (IsDigit (F)) {
407 P.Width = P.Width * 10 + (F - '0');
412 /* Optional precision */
417 P.Prec = va_arg (P.ap, int);
418 /* A negative precision argument is taken as if the precision
424 F = *Format++; /* Skip the '*' */
425 } else if (IsDigit (F)) {
432 P.Prec = P.Prec * 10 + (F - '0');
434 } else if (F == '-') {
435 /* A negative precision argument is taken as if the precision
438 F = *Format++; /* Skip the minus */
439 while (IsDigit (F = *Format++)) ;
446 /* Optional length modifier */
447 P.LengthMod = lmDefault;
454 P.LengthMod = lmChar;
456 P.LengthMod = lmShort;
464 P.LengthMod = lmLongLong;
466 P.LengthMod = lmLong;
471 P.LengthMod = lmIntMax;
476 P.LengthMod = lmSizeT;
481 P.LengthMod = lmPtrDiffT;
486 P.LengthMod = lmLongDouble;
492 /* If the space and + flags both appear, the space flag is ignored */
493 if ((P.Flags & (fSpace | fPlus)) == (fSpace | fPlus)) {
496 /* If the 0 and - flags both appear, the 0 flag is ignored */
497 if ((P.Flags & (fZero | fMinus)) == (fZero | fMinus)) {
500 /* If a precision is specified, the 0 flag is ignored */
501 if (P.Flags & fPrec) {
505 /* Conversion specifier */
511 FormatInt (&P, NextIVal (&P));
515 P.Flags |= fUnsigned;
517 FormatInt (&P, NextUVal (&P));
521 P.Flags |= fUnsigned;
523 FormatInt (&P, NextUVal (&P));
527 P.Flags |= (fUnsigned | fUpcase);
531 FormatInt (&P, NextUVal (&P));
535 SBuf[0] = (char) va_arg (P.ap, int);
537 FormatStr (&P, SBuf);
541 SPtr = va_arg (P.ap, const char*);
543 FormatStr (&P, SPtr);
547 /* Invalid format spec */
548 FAIL ("Invalid format specifier in xvsnprintf");
553 /* Terminate the output string and return the number of chars that had
554 * been written if the buffer was large enough.
555 * Beware: The terminating zero is not counted for the function result!
558 return P.BufFill - 1;
563 int xsnprintf (char* Buf, size_t Size, const char* Format, ...)
564 /* A basic snprintf implementation. Does currently only support integer
571 va_start (ap, Format);
572 Res = xvsnprintf (Buf, Size, Format, ap);
580 /*****************************************************************************/
582 /*****************************************************************************/
586 int xsprintf (char* Buf, size_t BufSize, const char* Format, ...)
587 /* Replacement function for sprintf */
592 va_start (ap, Format);
593 Res = xvsprintf (Buf, BufSize, Format, ap);
601 int xvsprintf (char* Buf, size_t BufSize, const char* Format, va_list ap)
602 /* Replacement function for sprintf */
604 int Res = xvsnprintf (Buf, BufSize, Format, ap);
605 CHECK (Res >= 0 && (unsigned) (Res+1) < BufSize);