1 /*****************************************************************************/
5 /* Replacement sprintf function */
9 /* (C) 2000-2004 Ullrich von Bassewitz */
10 /* Roemerstrasse 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 /*****************************************************************************/
51 /*****************************************************************************/
53 /*****************************************************************************/
57 /* The following is a very basic vsnprintf like function called xvsnprintf. It
58 ** features only the basic format specifiers (especially the floating point
59 ** stuff is missing), but may be extended if required. Reason for supplying
60 ** my own implementation is that vsnprintf is standard but not implemented by
61 ** older compilers, and some that implement it, don't adhere to the standard
62 ** (for example Microsoft with its _vsnprintf).
67 /* Variable argument list pointer */
75 /* Argument string buffer and string buffer pointer. The string buffer
76 ** must be big enough to hold a converted integer of the largest type
77 ** including an optional sign and terminating zero.
96 /* Conversion base and table */
98 const char* CharTable;
106 /* Length modifier */
117 /* Unsupported modifiers */
120 /* Default length is integer */
128 static void AddChar (PrintfCtrl* P, char C)
129 /* Store one character in the output buffer if there's enough room. */
131 if (++P->BufFill <= P->BufSize) {
138 static void AddPadding (PrintfCtrl* P, char C, unsigned Count)
139 /* Add some amount of padding */
148 static intmax_t NextIVal (PrintfCtrl*P)
149 /* Read the next integer value from the variable argument list */
151 switch (P->LengthMod) {
152 case lmChar: return (char) va_arg (P->ap, int);
153 case lmShort: return (short) va_arg (P->ap, int);
154 case lmInt: return (int) va_arg (P->ap, int);
155 case lmLong: return (long) va_arg (P->ap, long);
156 case lmIntMax: return va_arg (P->ap, intmax_t);
157 case lmSizeT: return (uintmax_t) va_arg (P->ap, size_t);
158 case lmPtrDiffT: return (long) va_arg (P->ap, ptrdiff_t);
160 FAIL ("Invalid type size in NextIVal");
167 static uintmax_t NextUVal (PrintfCtrl*P)
168 /* Read the next unsigned integer value from the variable argument list */
170 switch (P->LengthMod) {
171 case lmChar: return (unsigned char) va_arg (P->ap, unsigned);
172 case lmShort: return (unsigned short) va_arg (P->ap, unsigned);
173 case lmInt: return (unsigned int) va_arg (P->ap, unsigned int);
174 case lmLong: return (unsigned long) va_arg (P->ap, unsigned long);
175 case lmIntMax: return va_arg (P->ap, uintmax_t);
176 case lmSizeT: return va_arg (P->ap, size_t);
177 case lmPtrDiffT: return (intmax_t) va_arg (P->ap, ptrdiff_t);
179 FAIL ("Invalid type size in NextUVal");
186 static void ToStr (PrintfCtrl* P, uintmax_t Val)
187 /* Convert the given value to a (reversed) string */
191 *S++ = P->CharTable[Val % P->Base];
194 P->ArgLen = S - P->ArgBuf;
199 static void FormatInt (PrintfCtrl* P, uintmax_t Val)
200 /* Convert the integer value */
203 unsigned LeadCount = 0;
204 unsigned PrecPadding;
205 unsigned WidthPadding;
209 /* Determine the translation table */
210 P->CharTable = (P->Flags & fUpcase)? "0123456789ABCDEF" : "0123456789abcdef";
212 /* Check if the value is negative */
213 if ((P->Flags & fUnsigned) == 0 && ((intmax_t) Val) < 0) {
214 Val = -((intmax_t) Val);
215 Lead[LeadCount++] = '-';
216 } else if ((P->Flags & fPlus) != 0) {
217 Lead[LeadCount++] = '+';
218 } else if ((P->Flags & fSpace) != 0) {
219 Lead[LeadCount++] = ' ';
222 /* Convert the value into a (reversed string). */
225 /* The default precision for all integer conversions is one. This means
226 ** that the fPrec flag is always set and does not need to be checked
229 if ((P->Flags & fPrec) == 0) {
234 /* Determine the leaders for alternative forms */
235 if ((P->Flags & fHash) != 0) {
238 Lead[LeadCount++] = '0';
239 Lead[LeadCount++] = (P->Flags & fUpcase)? 'X' : 'x';
240 } else if (P->Base == 8) {
241 /* Alternative form for 'o': always add a leading zero. */
242 if (P->Prec <= P->ArgLen) {
243 Lead[LeadCount++] = '0';
248 /* Determine the amount of precision padding needed */
249 if (P->ArgLen < P->Prec) {
250 PrecPadding = P->Prec - P->ArgLen;
255 /* Determine the width padding needed */
256 if ((P->Flags & fWidth) != 0) {
257 int CurWidth = LeadCount + PrecPadding + P->ArgLen;
258 if (CurWidth < P->Width) {
259 WidthPadding = P->Width - CurWidth;
267 /* Output left space padding if any */
268 if ((P->Flags & (fMinus | fZero)) == 0 && WidthPadding > 0) {
269 AddPadding (P, ' ', WidthPadding);
274 for (I = 0; I < LeadCount; ++I) {
275 AddChar (P, Lead[I]);
278 /* Left zero padding if any */
279 if ((P->Flags & fZero) != 0 && WidthPadding > 0) {
280 AddPadding (P, '0', WidthPadding);
284 /* Precision padding */
285 if (PrecPadding > 0) {
286 AddPadding (P, '0', PrecPadding);
289 /* The number itself. Beware: It's reversed! */
290 while (P->ArgLen > 0) {
291 AddChar (P, P->ArgBuf[--P->ArgLen]);
294 /* Right width padding if any */
295 if (WidthPadding > 0) {
296 AddPadding (P, ' ', WidthPadding);
302 static void FormatStr (PrintfCtrl* P, const char* Val)
303 /* Convert the string */
305 unsigned WidthPadding;
307 /* Get the string length limited to the precision. Beware: We cannot use
308 ** strlen here, because if a precision is given, the string may not be
312 if ((P->Flags & fPrec) != 0) {
313 const char* S = memchr (Val, '\0', P->Prec);
315 /* Not zero terminated */
318 /* Terminating zero found */
325 /* Determine the width padding needed */
326 if ((P->Flags & fWidth) != 0 && P->Width > Len) {
327 WidthPadding = P->Width - Len;
332 /* Output left padding */
333 if ((P->Flags & fMinus) != 0 && WidthPadding > 0) {
334 AddPadding (P, ' ', WidthPadding);
338 /* Output the string */
343 /* Output right padding if any */
344 if (WidthPadding > 0) {
345 AddPadding (P, ' ', WidthPadding);
351 static void StoreOffset (PrintfCtrl* P)
352 /* Store the current output offset (%n format spec) */
354 switch (P->LengthMod) {
355 case lmChar: *va_arg (P->ap, int*) = P->BufFill;
356 case lmShort: *va_arg (P->ap, int*) = P->BufFill;
357 case lmInt: *va_arg (P->ap, int*) = P->BufFill;
358 case lmLong: *va_arg (P->ap, long*) = P->BufFill;
359 case lmIntMax: *va_arg (P->ap, intmax_t*) = P->BufFill;
360 case lmSizeT: *va_arg (P->ap, size_t*) = P->BufFill;
361 case lmPtrDiffT: *va_arg (P->ap, ptrdiff_t*) = P->BufFill;
362 default: FAIL ("Invalid size modifier for %n format spec in xvsnprintf");
368 int xvsnprintf (char* Buf, size_t Size, const char* Format, va_list ap)
369 /* A basic vsnprintf implementation. Does currently only support integer
381 /* Initialize the control structure */
387 /* Parse the format string */
388 while ((F = *Format++) != '\0') {
391 /* Not a format specifier, just copy */
397 if (*Format == '%') {
403 /* It's a format specifier. Check for flags. */
407 while (F != '\0' && !Done) {
409 case '-': P.Flags |= fMinus; F = *Format++; break;
410 case '+': P.Flags |= fPlus; F = *Format++; break;
411 case ' ': P.Flags |= fSpace; F = *Format++; break;
412 case '#': P.Flags |= fHash; F = *Format++; break;
413 case '0': P.Flags |= fZero; F = *Format++; break;
414 default: Done = 1; break;
417 /* Optional field width */
419 P.Width = va_arg (P.ap, int);
420 /* A negative field width argument is taken as a - flag followed
421 ** by a positive field width.
429 } else if (IsDigit (F)) {
436 P.Width = P.Width * 10 + (F - '0');
441 /* Optional precision */
446 P.Prec = va_arg (P.ap, int);
447 /* A negative precision argument is taken as if the precision
453 F = *Format++; /* Skip the '*' */
454 } else if (IsDigit (F)) {
461 P.Prec = P.Prec * 10 + (F - '0');
463 } else if (F == '-') {
464 /* A negative precision argument is taken as if the precision
467 F = *Format++; /* Skip the minus */
468 while (IsDigit (F = *Format++)) ;
475 /* Optional length modifier */
476 P.LengthMod = lmDefault;
483 P.LengthMod = lmChar;
485 P.LengthMod = lmShort;
493 P.LengthMod = lmLongLong;
495 P.LengthMod = lmLong;
500 P.LengthMod = lmIntMax;
505 P.LengthMod = lmSizeT;
510 P.LengthMod = lmPtrDiffT;
515 P.LengthMod = lmLongDouble;
521 /* If the space and + flags both appear, the space flag is ignored */
522 if ((P.Flags & (fSpace | fPlus)) == (fSpace | fPlus)) {
525 /* If the 0 and - flags both appear, the 0 flag is ignored */
526 if ((P.Flags & (fZero | fMinus)) == (fZero | fMinus)) {
529 /* If a precision is specified, the 0 flag is ignored */
530 if (P.Flags & fPrec) {
534 /* Conversion specifier */
540 FormatInt (&P, NextIVal (&P));
544 P.Flags |= fUnsigned;
546 FormatInt (&P, NextUVal (&P));
550 P.Flags |= fUnsigned;
552 FormatInt (&P, NextUVal (&P));
556 P.Flags |= (fUnsigned | fUpcase);
560 FormatInt (&P, NextUVal (&P));
564 SBuf[0] = (char) va_arg (P.ap, int);
566 FormatStr (&P, SBuf);
570 SPtr = va_arg (P.ap, const char*);
572 FormatStr (&P, SPtr);
576 /* See comment at top of header file */
578 /* Argument is StrBuf */
579 const StrBuf* S = va_arg (P.ap, const StrBuf*);
581 /* Handle the length by using a precision */
582 if ((P.Flags & fPrec) != 0) {
583 /* Precision already specified, use length of string
586 if ((unsigned) P.Prec > SB_GetLen (S)) {
587 P.Prec = SB_GetLen (S);
590 /* No precision, add it */
592 P.Prec = SB_GetLen (S);
594 FormatStr (&P, SB_GetConstBuf (S));
595 UseStrBuf = 0; /* Reset flag */
597 /* Use hex format for pointers */
598 P.Flags |= (fUnsigned | fPrec);
599 P.Prec = ((sizeof (void*) * CHAR_BIT) + 3) / 4;
601 FormatInt (&P, (uintptr_t) va_arg (P.ap, void*));
606 /* See comment at top of header file */
615 /* Invalid format spec */
616 FAIL ("Invalid format specifier in xvsnprintf");
621 /* We don't need P.ap any longer */
624 /* Terminate the output string and return the number of chars that had
625 ** been written if the buffer was large enough.
626 ** Beware: The terminating zero is not counted for the function result!
629 return P.BufFill - 1;
634 int xsnprintf (char* Buf, size_t Size, const char* Format, ...)
635 /* A basic snprintf implementation. Does currently only support integer
642 va_start (ap, Format);
643 Res = xvsnprintf (Buf, Size, Format, ap);
651 /*****************************************************************************/
653 /*****************************************************************************/
657 int xsprintf (char* Buf, size_t BufSize, const char* Format, ...)
658 /* Replacement function for sprintf */
663 va_start (ap, Format);
664 Res = xvsprintf (Buf, BufSize, Format, ap);
672 int xvsprintf (char* Buf, size_t BufSize, const char* Format, va_list ap)
673 /* Replacement function for sprintf */
675 int Res = xvsnprintf (Buf, BufSize, Format, ap);
676 CHECK (Res >= 0 && (unsigned) (Res+1) < BufSize);