Usermode/libc - Fixed compilation issues in printf
[tpg/acess2.git] / Usermode / Libraries / libc.so_src / printf.c
1 /*
2  * Acess2 C Library
3  * - By John Hodge (thePowersGang)
4  *
5  * scanf.c
6  * - *scanf family of functions
7  */
8 #include "lib.h"
9 #include <stdio.h>
10 #include <stdarg.h>
11 #include <string.h>
12 #include <ctype.h>      // toupper
13 #include <assert.h>     // assert() 
14
15 // Quick booleans
16 typedef char    BOOL;
17 #define TRUE    1
18 #define FALSE   0
19
20 // === TYPES ===
21 typedef void    (*printf_putch_t)(void *h, char ch);
22 enum eFPN {
23         FPN_STD,
24         FPN_SCI,
25         FPN_SHORTEST,
26 };
27
28 // === PROTOTYPES ===
29 void    itoa(char *buf, uint64_t num, size_t base, int minLength, char pad, int bSigned);
30 size_t  _printf_itoa(printf_putch_t putch_cb, void *putch_h, uint64_t num,
31         size_t base, int bUpper,
32         int bSigned, char SignChar, int Precision,
33         int PadLength, char PadChar, int bPadRight);
34 size_t  _printf_ftoa_hex(printf_putch_t putch_cb, void *putch_h, long double num, int Precision, int bForcePoint, int bForceSign, int bCapitals);
35 size_t  _printf_ftoa(printf_putch_t putch_cb, void *putch_h, long double num, size_t Base, enum eFPN Notation, int Precision, int bForcePoint, int bForceSign, int bCapitals);
36
37 // === CODE ===
38 /**
39  * \fn EXPORT void vsnprintf(char *buf, const char *format, va_list args)
40  * \brief Prints a formatted string to a buffer
41  * \param buf   Pointer - Destination Buffer
42  * \param format        String - Format String
43  * \param args  VarArgs List - Arguments
44  */
45 EXPORT int _vcprintf_int(printf_putch_t putch_cb, void *putch_h, const char *format, va_list args)
46 {
47         char    tmp[65];
48          int    c, minSize, precision, len;
49         size_t  pos = 0;
50         char    *p;
51         uint64_t        arg;
52         long double     arg_f;
53 //      char    cPositiveChar;
54         BOOL    bLongLong, bLong, bJustifyLeft, bAltForm;
55         char    cNumPad, cPlus;
56
57         #define _addchar(ch) do { \
58                 putch_cb(putch_h, ch); \
59                 pos ++; \
60         } while(0)
61
62         tmp[32] = '\0';
63         
64         while((c = *format++) != 0)
65         {
66                 // Non-control character
67                 if (c != '%') {
68                         _addchar(c);
69                         continue;
70                 }
71                 
72                 // Control Character
73                 c = *format++;
74                 if(c == '%') {  // Literal %
75                         _addchar('%');
76                         continue;
77                 }
78                 
79                 bAltForm = 0;
80                 cNumPad = ' ';
81                 bJustifyLeft = 0;
82                 cPlus = '\0';
83                 bLong = 0;
84                 bLongLong = 0;
85                 minSize = 0;
86                 precision = -1;
87                 
88                 // - Flags
89                 do
90                 {
91                         // Alternate form (0<oct>, 0x<hex>, 123.)
92                         if(c == '#') {
93                                 bAltForm = 1;
94                         }
95                         // Padding with '0'
96                         else if(c == '0') {
97                                 cNumPad = '0';
98                         }
99                         // Pad on left
100                         else if(c == '-') {
101                                 bJustifyLeft = 1;
102                         }
103                         // Include space for positive sign
104                         else if(c == ' ') {
105                                 cPlus = ' ';
106                         }
107                         // Always include sign
108                         else if(c == '+') {
109                                 cPlus = '+';
110                         }
111                         else
112                                 break;
113                 }
114                 while( (c = *format++) );
115                 
116                 // Padding length
117                 if( c == '*' ) {
118                         // Variable length
119                         minSize = va_arg(args, size_t);
120                         c = *format++;
121                 }
122                 else if('1' <= c && c <= '9')
123                 {
124                         minSize = 0;
125                         while('0' <= c && c <= '9')
126                         {
127                                 minSize *= 10;
128                                 minSize += c - '0';
129                                 c = *format++;
130                         }
131                 }
132
133                 // Precision
134                 if(c == '.') {
135                         c = *format++;
136                         if(c == '*') {
137                                 precision = va_arg(args, size_t);
138                                 c = *format++;
139                         }
140                         else if('1' <= c && c <= '9')
141                         {
142                                 precision = 0;
143                                 while('0' <= c && c <= '9')
144                                 {
145                                         precision *= 10;
146                                         precision += c - '0';
147                                         c = *format++;
148                                 }
149                         }
150                 }
151         
152                 // Check for long long
153                 if(c == 'l')
154                 {
155                         bLong = 1;
156                         c = *format++;
157                         if(c == 'l') {
158                                 bLongLong = 1;
159                                 c = *format++;
160                         }
161                 }
162                 
163                 // Just help things along later
164                 p = tmp;
165                 
166                 // Get Type
167                 switch( c )
168                 {
169                 // Signed Integer
170                 case 'd':
171                 case 'i':
172                         // Get Argument
173                         arg = bLongLong ? va_arg(args, int64_t) : va_arg(args, int32_t);
174                         if( arg == 0 && precision == 0 )
175                                 break;
176                         pos += _printf_itoa(putch_cb, putch_h, arg, 10, FALSE,
177                                 TRUE, cPlus, precision, minSize, cNumPad, bJustifyLeft);
178                         break;
179                 
180                 // Unsigned Integer
181                 case 'u':
182                         arg = bLongLong ? va_arg(args, int64_t) : va_arg(args, int32_t);
183                         pos += _printf_itoa(putch_cb, putch_h, arg, 10, FALSE,
184                                 FALSE, '\0', precision, minSize, cNumPad, bJustifyLeft);
185                         break;
186                 
187                 // Pointer
188                 case 'p':
189                         _addchar('*');
190                         _addchar('0');
191                         _addchar('x');
192                         arg = va_arg(args, intptr_t);
193                         pos += _printf_itoa(putch_cb, putch_h, arg, 16, FALSE,
194                                 FALSE, '\0', sizeof(intptr_t)*2, 0,'\0',FALSE);
195                         break;
196                 // Unsigned Hexadecimal
197                 case 'X':
198                 case 'x':
199                         if(bAltForm) {
200                                 _addchar('0');
201                                 _addchar(c);
202                         }
203                         arg = bLongLong ? va_arg(args, int64_t) : va_arg(args, int32_t);
204                         pos += _printf_itoa(putch_cb, putch_h, arg, 16, c=='X',
205                                 FALSE, '\0', precision, minSize,cNumPad,bJustifyLeft);
206                         break;
207                 
208                 // Unsigned Octal
209                 case 'o':
210                         if(bAltForm) {
211                                 _addchar('0');
212                         }
213                         arg = bLongLong ? va_arg(args, int64_t) : va_arg(args, int32_t);
214                         pos += _printf_itoa(putch_cb, putch_h, arg, 8, FALSE,
215                                 FALSE, '\0', precision, minSize,cNumPad,bJustifyLeft);
216                         break;
217                 
218                 // Unsigned binary
219                 case 'b':
220                         if(bAltForm) {
221                                 _addchar('0');
222                                 _addchar('b');
223                         }
224                         arg = bLongLong ? va_arg(args, int64_t) : va_arg(args, int32_t);
225                         pos += _printf_itoa(putch_cb, putch_h, arg, 2, FALSE,
226                                 FALSE, '\0', precision, minSize,cNumPad,bJustifyLeft);
227                         break;
228
229                 // Standard float
230                 case 'f':
231                 case 'F':
232                         arg_f = bLong ? va_arg(args, long double) : va_arg(args, double);
233                         pos += _printf_ftoa(putch_cb, putch_h, arg_f, 10, FPN_STD,
234                                 precision, 0, bJustifyLeft, c == 'F');
235                         break;
236                 // Scientific Float
237                 case 'e':
238                 case 'E':
239                         arg_f = bLong ? va_arg(args, long double) : va_arg(args, double);
240                         pos += _printf_ftoa(putch_cb, putch_h, arg_f, 10, FPN_SCI,
241                                 precision, 0, bJustifyLeft, c == 'E');
242                         break;
243                 // Hexadecimal Scientific
244                 case 'a':
245                 case 'A':
246                         arg_f = bLong ? va_arg(args, long double) : va_arg(args, double);
247                         pos += _printf_ftoa_hex(putch_cb, putch_h, arg_f, precision, 0, bJustifyLeft, c == 'A');
248                         break;
249
250                 // String
251                 case 's':
252                         p = va_arg(args, char*);
253                         if(!p)  p = "(null)";
254                         //_SysDebug("vsnprintf: p = '%s'", p);
255                         if(precision >= 0)
256                                 len = strnlen(p, precision);
257                         else
258                                 len = strlen(p);
259                         if(!bJustifyLeft)
260                                 while(minSize > len++)  _addchar(' ');
261                         while( *p ) {
262                                 if(precision >= 0 && precision -- == 0)
263                                         break;
264                                 _addchar(*p++);
265                         }
266                         if(bJustifyLeft)
267                                 while(minSize > len++)  _addchar(' ');
268                         break;
269
270                 // Unknown, just treat it as a character
271                 default:
272                         arg = va_arg(args, uint32_t);
273                         _addchar(arg);
274                         break;
275                 }
276         }
277         #undef _addchar
278         
279         return pos;
280 }
281
282 struct s_sprintf_info {
283         char    *dest;
284         size_t  ofs;
285         size_t  maxlen;
286 };
287
288 void _vsnprintf_putch(void *h, char ch)
289 {
290         struct s_sprintf_info   *info = h;
291         if(info->ofs < info->maxlen)
292                 info->dest[info->ofs++] = ch;
293 }
294
295 EXPORT int vsnprintf(char *__s, size_t __maxlen, const char *__format, va_list __args)
296 {
297         struct s_sprintf_info   info = {__s, 0, __maxlen};
298         int ret;
299         ret = _vcprintf_int(_vsnprintf_putch, &info, __format, __args);
300         _vsnprintf_putch(&info, '\0');
301         return ret;
302 }
303
304 EXPORT int snprintf(char *buf, size_t maxlen, const char *format, ...)
305 {
306          int    ret;
307         va_list args;
308         va_start(args, format);
309         ret = vsnprintf((char*)buf, maxlen, (char*)format, args);
310         va_end(args);
311         return ret;
312 }
313
314
315 EXPORT int vsprintf(char * __s, const char *__format, va_list __args)
316 {
317         return vsnprintf(__s, 0x7FFFFFFF, __format, __args);
318 }
319 EXPORT int sprintf(char *buf, const char *format, ...)
320 {
321          int    ret;
322         va_list args;
323         va_start(args, format);
324         ret = vsprintf((char*)buf, (char*)format, args);
325         va_end(args);
326         return ret;
327 }
328
329 void _vfprintf_putch(void *h, char ch)
330 {
331         fputc(ch, h);
332 }
333
334 EXPORT int vfprintf(FILE *__fp, const char *__format, va_list __args)
335 {
336         return _vcprintf_int(_vfprintf_putch, __fp, __format, __args);
337 }
338
339 EXPORT int fprintf(FILE *fp, const char *format, ...)
340 {
341         va_list args;
342          int    ret;
343         
344         // Get Size
345         va_start(args, format);
346         ret = vfprintf(fp, (char*)format, args);
347         va_end(args);
348         
349         return ret;
350 }
351
352 EXPORT int vprintf(const char *__format, va_list __args)
353 {
354         return vfprintf(stdout, __format, __args);
355 }
356
357 EXPORT int printf(const char *format, ...)
358 {
359         va_list args;
360          int    ret;
361         
362         // Get final size
363         va_start(args, format);
364         ret = vprintf(format, args);
365         va_end(args);
366         
367         // Return
368         return ret;
369 }
370
371 void itoa(char *buf, uint64_t num, size_t base, int minLength, char pad, int bSigned)
372 {
373         struct s_sprintf_info   info = {buf, 0, 1024};
374         if(!buf)        return;
375         _printf_itoa(_vsnprintf_putch, &info, num, base, FALSE, bSigned, '\0', 0, minLength, pad, FALSE);
376         buf[info.ofs] = '\0';
377 }
378
379 const char cDIGITS[] = "0123456789abcdef";
380 const char cUDIGITS[] = "0123456789ABCDEF";
381 /**
382  * \brief Convert an integer into a character string
383  * \param buf   Destination Buffer
384  * \param num   Number to convert
385  * \param base  Base-n number output
386  * \param minLength     Minimum length of output
387  * \param pad   Padding used to ensure minLength
388  * \param bSigned       Signed number output?
389  */
390 size_t _printf_itoa(printf_putch_t putch_cb, void *putch_h, uint64_t num,
391         size_t base, int bUpper,
392         int bSigned, char SignChar, int Precision,
393         int PadLength, char PadChar, int bPadRight)
394 {
395         char    tmpBuf[64];
396          int    pos = 0;
397         size_t  ret = 0;
398          int    sign_is_neg = 0;
399         const char *map = bUpper ? cUDIGITS : cDIGITS;
400
401         if(base > 16 || base < 2) {
402                 return 0;
403         }
404         
405         if(bSigned && (int64_t)num < 0)
406         {
407                 num = -(int64_t)num;
408                 sign_is_neg = 1;
409         }
410         
411         // Encode into reversed string
412         while(num > base-1) {
413                 tmpBuf[pos++] = map[ num % base ];
414                 num = (uint64_t) num / (uint64_t)base;          // Shift {number} right 1 digit
415         }
416
417         tmpBuf[pos++] = map[ num % base ];              // Last digit of {number}
418         
419         // length of number, minus the sign character
420         PadLength -= pos - sign_is_neg - (SignChar != '\0');
421         if( !bPadRight )
422         {
423                 while(PadLength-- > 0)
424                         putch_cb(putch_h, PadChar), ret ++;
425         }
426         
427         if(sign_is_neg)
428                 putch_cb(putch_h, '-'), ret++;  // Negative sign character
429         else if(SignChar)
430                 putch_cb(putch_h, SignChar), ret++;     // positive sign character
431         else {
432         }
433         
434         while( Precision-- > 0 )
435                 putch_cb(putch_h, '0'), ret++;
436         while(pos--)
437                 putch_cb(putch_h, tmpBuf[pos]), ret++;  // Reverse the order of characters
438
439         if( bPadRight )
440         {
441                 while(PadLength-- > 0)
442                         putch_cb(putch_h, PadChar), ret ++;
443         }
444         
445         return ret;
446 }
447
448 int expand_double(double num, uint64_t *Significand, int16_t *Exponent, int *SignIsNeg)
449 {
450         // IEEE 754 binary64
451         #if 0
452         {
453                 uint64_t test_exp = 0xC000000000000000;
454                 double test_value = -2.0f;
455                 assert( *((uint64_t*)&test_value) == test_exp );
456         }
457         #endif
458         
459         const uint64_t  *bit_rep = (void*)&num;
460         
461         *SignIsNeg = *bit_rep >> 63;
462         *Exponent = ((*bit_rep >> 52) & 0x7FF) - 1023;
463         *Significand = (*bit_rep & ((1ULL << 52)-1)) << (64-52);
464
465 //      printf("%llx %i %i %llx\n", *bit_rep, (int)*SignIsNeg, (int)*Exponent, *Significand);
466
467         // Subnormals
468         if( *Exponent == -1023 && *Significand != 0 )
469                 return 1;
470         // Infinity
471         if( *Exponent == 0x800 && *Significand == 0)
472                 return 2;
473         // NaNs
474         if( *Exponent == 0x800 && *Significand != 0)
475                 return 3;
476
477         return 0;
478 }
479
480 /**
481  * Internal function
482  * \return Remainder
483  */
484 double _longdiv(double num, double den, int *quot)
485 {
486         assert(num >= 0);
487         assert(den > 0);
488 //      printf("%llu / %llu\n", (long long int)num, (long long int)den);
489         
490         *quot = 0;
491         assert(num < den*10);
492         while(num >= den)
493         {
494                 num -= den;
495                 (*quot) ++;
496                 assert( *quot < 10 );
497         }
498 //      printf(" %i\n", *quot);
499         return num;
500 }
501
502 size_t _printf_ftoa_hex(printf_putch_t putch_cb, void *putch_h, long double num, int Precision, int bForcePoint, int bForceSign, int bCapitals)
503 {
504         uint64_t        significand;
505         int16_t exponent;
506          int    signisneg;
507          int    rv;
508         size_t  ret = 0;
509
510         #define _putch(_ch) do{\
511                 if(bCapitals)\
512                         putch_cb(putch_h, toupper(_ch));\
513                 else\
514                         putch_cb(putch_h, _ch);\
515                 ret ++;\
516         }while(0)
517
518         if( Precision == -1 )
519                 Precision = (64-4)/4;
520
521         rv = expand_double(num, &significand, &exponent, &signisneg);
522         switch(rv)
523         {
524         // 0: No errors, nothing special
525         case 0:
526                 break;
527         // 1: Subnormals
528         case 1:
529                 // TODO: Subnormal = 0?
530                 break;
531         // 2: Infinity
532         case 2:
533                 _putch('i');
534                 _putch('n');
535                 _putch('f');
536                 return 3;
537         case 3:
538                 _putch('N');
539                 _putch('a');
540                 _putch('N');
541                 return 3;
542         }
543         
544         // int  exp_ofs = exponent % 4;
545         // int  exp_16 = exponent - exp_ofs;
546         //uint8_t       whole = (1 << exp_ofs) | ((significand >> (64-3)) >> exp_ofs);
547         //significand <<= 3 - exp_ofs;
548         uint8_t whole = (rv != 1) ? 1 : 0;
549         
550         if( signisneg )
551                 _putch('-');
552         else if( bForceSign )
553                 _putch('+');
554         else {
555         }
556         _putch('0');
557         _putch('x');
558         _putch(cDIGITS[whole]);
559         if( significand || bForcePoint )
560                 _putch('.');
561         // Fractional
562         while( significand && Precision -- )
563         {
564                 uint8_t val = significand >> (64-4);
565                 _putch(cDIGITS[val]);
566                 significand <<= 4;
567         }
568         _putch('p');
569         //ret += _printf_itoa(putch_cb, putch_h, exp_16, 16, bCapitals, TRUE, '+', 0, 0, '\0', 0);
570         ret += _printf_itoa(putch_cb, putch_h, exponent, 10, bCapitals, TRUE, '+', 0, 0, '\0', 0);
571         
572         #undef _putch
573         return ret;
574 }
575
576 size_t _printf_ftoa(printf_putch_t putch_cb, void *putch_h, long double num, size_t Base, enum eFPN Notation, int Precision, int bForcePoint, int bForceSign, int bCapitals)
577 {
578         uint64_t        significand;
579         int16_t exponent;
580          int    signisneg;
581          int    rv;
582         size_t  ret = 0;
583
584         #define _putch(_ch) do{\
585                 if(bCapitals)\
586                         putch_cb(putch_h, toupper(_ch));\
587                 else\
588                         putch_cb(putch_h, _ch);\
589                 ret ++;\
590         }while(0)
591
592         if( Base <= 1 || Base > 16 )
593                 return 0;
594
595         rv = expand_double(num, &significand, &exponent, &signisneg);
596         switch(rv)
597         {
598         // 0: No errors, nothing special
599         case 0:
600                 break;
601         // 1: Subnormals
602         case 1:
603                 // TODO: Subnormal = 0?
604                 break;
605         // 2: Infinity
606         case 2:
607                 _putch('i');
608                 _putch('n');
609                 _putch('f');
610                 return 3;
611         case 3:
612                 _putch('N');
613                 _putch('a');
614                 _putch('N');
615                 return 3;
616         }
617
618         // - Used as 0/1 bools in arithmatic later on
619         bForcePoint = !!bForcePoint;
620         bForceSign = !!bForceSign;
621
622         // Apply default to precision
623         if( Precision == -1 )
624                 Precision = 6;
625
626         if( num < 0 )
627                 num = -num;
628
629         // Select optimum type
630         if( Notation == FPN_SHORTEST )
631         {
632                 //TODO:
633                 //int   first_set_sig = BSL(significand);
634         //      TODO: if( num > pos(Base, 2+Precision+2+log_base(exponent) )
635                 Notation = FPN_SCI;
636         }
637
638         double precision_max = 1;
639         while(Precision--)
640                 precision_max /= Base;
641
642         // Determine scientific's exponent and starting denominator
643         double den = 1;
644          int    sci_exponent = 0;
645         if( Notation == FPN_SCI )
646         {
647                 if( num < 1 )
648                 {
649                         while(num < 1)
650                         {
651                                 num *= Base;
652                                 sci_exponent ++;
653                         }
654                 }
655                 else if( num >= Base )
656                 {
657                         while(num >= Base)
658                         {
659                                 num /= Base;
660                                 sci_exponent ++;
661                         }
662                 }
663                 else
664                 {
665                         // no exponent
666                 }
667                 den = 1;
668         }
669         else
670         {
671                 while( den < num )
672                         den *= Base;
673                 den /= Base;
674         }
675
676         // Leading sign
677         if( signisneg )
678                 _putch('-');
679         else if( bForceSign )
680                 _putch('+');
681         else {
682         }
683
684          int    value;
685         // Whole section
686         do
687         {
688                 num = _longdiv(num, den, &value);
689                 _putch(cDIGITS[value]);
690                 den /= Base;
691         } while( den >= 1 );
692
693         // Decimal point (if needed/forced)     
694         if( den >= precision_max || bForcePoint )
695                 _putch('.');
696         // Decimal section
697         while( den >= precision_max )
698         {
699                 num = _longdiv(num, den, &value);
700                 _putch(cDIGITS[value]);
701                 den /= Base;
702         }
703
704         if( Notation == FPN_SCI )
705         {
706                 if( Base == 16 )
707                         _putch('p');
708                 else
709                         _putch('e');
710                 ret += _printf_itoa(putch_cb, putch_h, sci_exponent, Base, FALSE, TRUE, '+', 0, 0, '\0', FALSE);
711         }       
712
713         #undef _putch
714
715         return ret;
716 }

UCC git Repository :: git.ucc.asn.au