3419cc721fc62e6bfaa14c445596814dea93ab28
[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                 sprintf_puts:
254                         if(!p)  p = "(null)";
255                         //_SysDebug("vsnprintf: p = '%s'", p);
256                         if(precision >= 0)
257                                 len = strnlen(p, precision);
258                         else
259                                 len = strlen(p);
260                         if(!bJustifyLeft)
261                                 while(minSize > len++)  _addchar(' ');
262                         while( *p ) {
263                                 if(precision >= 0 && precision -- == 0)
264                                         break;
265                                 _addchar(*p++);
266                         }
267                         if(bJustifyLeft)
268                                 while(minSize > len++)  _addchar(' ');
269                         break;
270
271                 // Unknown, just treat it as a character
272                 default:
273                         arg = va_arg(args, uint32_t);
274                         _addchar(arg);
275                         break;
276                 }
277         }
278         #undef _addchar
279         
280         return pos;
281 }
282
283 struct s_sprintf_info {
284         char    *dest;
285         size_t  ofs;
286         size_t  maxlen;
287 };
288
289 void _vsnprintf_putch(void *h, char ch)
290 {
291         struct s_sprintf_info   *info = h;
292         if(info->ofs < info->maxlen)
293                 info->dest[info->ofs++] = ch;
294 }
295
296 EXPORT int vsnprintf(char *__s, size_t __maxlen, const char *__format, va_list __args)
297 {
298         struct s_sprintf_info   info = {__s, 0, __maxlen};
299         int ret;
300         ret = _vcprintf_int(_vsnprintf_putch, &info, __format, __args);
301         _vsnprintf_putch(&info, '\0');
302         return ret;
303 }
304
305 EXPORT int snprintf(char *buf, size_t maxlen, const char *format, ...)
306 {
307          int    ret;
308         va_list args;
309         va_start(args, format);
310         ret = vsnprintf((char*)buf, maxlen, (char*)format, args);
311         va_end(args);
312         return ret;
313 }
314
315
316 EXPORT int vsprintf(char * __s, const char *__format, va_list __args)
317 {
318         return vsnprintf(__s, 0x7FFFFFFF, __format, __args);
319 }
320 EXPORT int sprintf(char *buf, const char *format, ...)
321 {
322          int    ret;
323         va_list args;
324         va_start(args, format);
325         ret = vsprintf((char*)buf, (char*)format, args);
326         va_end(args);
327         return ret;
328 }
329
330 void _vfprintf_putch(void *h, char ch)
331 {
332         fputc(ch, h);
333 }
334
335 EXPORT int vfprintf(FILE *__fp, const char *__format, va_list __args)
336 {
337         return _vcprintf_int(_vfprintf_putch, __fp, __format, __args);
338 }
339
340 EXPORT int fprintf(FILE *fp, const char *format, ...)
341 {
342         va_list args;
343          int    ret;
344         
345         // Get Size
346         va_start(args, format);
347         ret = vfprintf(fp, (char*)format, args);
348         va_end(args);
349         
350         return ret;
351 }
352
353 EXPORT int vprintf(const char *__format, va_list __args)
354 {
355         return vfprintf(stdout, __format, __args);
356 }
357
358 EXPORT int printf(const char *format, ...)
359 {
360         va_list args;
361          int    ret;
362         
363         // Get final size
364         va_start(args, format);
365         ret = vprintf(format, args);
366         va_end(args);
367         
368         // Return
369         return ret;
370 }
371
372 void itoa(char *buf, uint64_t num, size_t base, int minLength, char pad, int bSigned)
373 {
374         struct s_sprintf_info   info = {buf, 0, 1024};
375         if(!buf)        return;
376         _printf_itoa(_vsnprintf_putch, &info, num, base, FALSE, bSigned, '\0', 0, minLength, pad, FALSE);
377         buf[info.ofs] = '\0';
378 }
379
380 const char cDIGITS[] = "0123456789abcdef";
381 const char cUDIGITS[] = "0123456789ABCDEF";
382 /**
383  * \brief Convert an integer into a character string
384  * \param buf   Destination Buffer
385  * \param num   Number to convert
386  * \param base  Base-n number output
387  * \param minLength     Minimum length of output
388  * \param pad   Padding used to ensure minLength
389  * \param bSigned       Signed number output?
390  */
391 size_t _printf_itoa(printf_putch_t putch_cb, void *putch_h, uint64_t num,
392         size_t base, int bUpper,
393         int bSigned, char SignChar, int Precision,
394         int PadLength, char PadChar, int bPadRight)
395 {
396         char    tmpBuf[64];
397          int    pos = 0;
398         size_t  ret = 0;
399          int    sign_is_neg = 0;
400         const char *map = bUpper ? cUDIGITS : cDIGITS;
401
402         if(base > 16 || base < 2) {
403                 return 0;
404         }
405         
406         if(bSigned && (int64_t)num < 0)
407         {
408                 num = -(int64_t)num;
409                 sign_is_neg = 1;
410         }
411         
412         // Encode into reversed string
413         while(num > base-1) {
414                 tmpBuf[pos++] = map[ num % base ];
415                 num = (uint64_t) num / (uint64_t)base;          // Shift {number} right 1 digit
416         }
417
418         tmpBuf[pos++] = map[ num % base ];              // Last digit of {number}
419         
420         // length of number, minus the sign character
421         PadLength -= pos - sign_is_neg - (SignChar != '\0');
422         if( !bPadRight )
423         {
424                 while(PadLength-- > 0)
425                         putch_cb(putch_h, PadChar), ret ++;
426         }
427         
428         if(sign_is_neg)
429                 putch_cb(putch_h, '-'), ret++;  // Negative sign character
430         else if(SignChar)
431                 putch_cb(putch_h, SignChar), ret++;     // positive sign character
432         else {
433         }
434         
435         while( Precision-- > 0 )
436                 putch_cb(putch_h, '0'), ret++;
437         while(pos--)
438                 putch_cb(putch_h, tmpBuf[pos]), ret++;  // Reverse the order of characters
439
440         if( bPadRight )
441         {
442                 while(PadLength-- > 0)
443                         putch_cb(putch_h, PadChar), ret ++;
444         }
445         
446         return ret;
447 }
448
449 int expand_double(double num, uint64_t *Significand, int16_t *Exponent, int *SignIsNeg)
450 {
451         // IEEE 754 binary64
452         #if 0
453         {
454                 uint64_t test_exp = 0xC000000000000000;
455                 double test_value = -2.0f;
456                 assert( *((uint64_t*)&test_value) == test_exp );
457         }
458         #endif
459         
460         const uint64_t  *bit_rep = (void*)&num;
461         
462         *SignIsNeg = *bit_rep >> 63;
463         *Exponent = ((*bit_rep >> 52) & 0x7FF) - 1023;
464         *Significand = (*bit_rep & ((1ULL << 52)-1)) << (64-52);
465
466 //      printf("%llx %i %i %llx\n", *bit_rep, (int)*SignIsNeg, (int)*Exponent, *Significand);
467
468         // Subnormals
469         if( *Exponent == -1023 && *Significand != 0 )
470                 return 1;
471         // Infinity
472         if( *Exponent == 0x800 && *Significand == 0)
473                 return 2;
474         // NaNs
475         if( *Exponent == 0x800 && *Significand != 0)
476                 return 3;
477
478         return 0;
479 }
480
481 /**
482  * Internal function
483  * \return Remainder
484  */
485 double _longdiv(double num, double den, int *quot)
486 {
487         assert(num >= 0);
488         assert(den > 0);
489 //      printf("%llu / %llu\n", (long long int)num, (long long int)den);
490         
491         *quot = 0;
492         assert(num < den*10);
493         while(num >= den)
494         {
495                 num -= den;
496                 (*quot) ++;
497                 assert( *quot < 10 );
498         }
499 //      printf(" %i\n", *quot);
500         return num;
501 }
502
503 size_t _printf_ftoa_hex(printf_putch_t putch_cb, void *putch_h, long double num, int Precision, int bForcePoint, int bForceSign, int bCapitals)
504 {
505         uint64_t        significand;
506         int16_t exponent;
507          int    signisneg;
508          int    rv;
509         size_t  ret = 0;
510
511         #define _putch(_ch) do{\
512                 if(bCapitals)\
513                         putch_cb(putch_h, toupper(_ch));\
514                 else\
515                         putch_cb(putch_h, _ch);\
516                 ret ++;\
517         }while(0)
518
519         if( Precision == -1 )
520                 Precision = (64-4)/4;
521
522         rv = expand_double(num, &significand, &exponent, &signisneg);
523         switch(rv)
524         {
525         // 0: No errors, nothing special
526         case 0:
527                 break;
528         // 1: Subnormals
529         case 1:
530                 // TODO: Subnormal = 0?
531                 break;
532         // 2: Infinity
533         case 2:
534                 _putch('i');
535                 _putch('n');
536                 _putch('f');
537                 return 3;
538         case 3:
539                 _putch('N');
540                 _putch('a');
541                 _putch('N');
542                 return 3;
543         }
544         
545         // int  exp_ofs = exponent % 4;
546         // int  exp_16 = exponent - exp_ofs;
547         //uint8_t       whole = (1 << exp_ofs) | ((significand >> (64-3)) >> exp_ofs);
548         //significand <<= 3 - exp_ofs;
549         uint8_t whole = (rv != 1) ? 1 : 0;
550         
551         if( signisneg )
552                 _putch('-');
553         else if( bForceSign )
554                 _putch('+');
555         else {
556         }
557         _putch('0');
558         _putch('x');
559         _putch(cDIGITS[whole]);
560         if( significand || bForcePoint )
561                 _putch('.');
562         // Fractional
563         while( significand && Precision -- )
564         {
565                 uint8_t val = significand >> (64-4);
566                 _putch(cDIGITS[val]);
567                 significand <<= 4;
568         }
569         _putch('p');
570         //ret += _printf_itoa(putch_cb, putch_h, exp_16, 16, bCapitals, TRUE, '+', 0, 0, '\0', 0);
571         ret += _printf_itoa(putch_cb, putch_h, exponent, 10, bCapitals, TRUE, '+', 0, 0, '\0', 0);
572         
573         #undef _putch
574         return ret;
575 }
576
577 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)
578 {
579         uint64_t        significand;
580         int16_t exponent;
581          int    signisneg;
582          int    rv;
583         size_t  ret = 0;
584
585         #define _putch(_ch) do{\
586                 if(bCapitals)\
587                         putch_cb(putch_h, toupper(_ch));\
588                 else\
589                         putch_cb(putch_h, _ch);\
590                 ret ++;\
591         }while(0)
592
593         if( Base <= 1 || Base > 16 )
594                 return 0;
595
596         rv = expand_double(num, &significand, &exponent, &signisneg);
597         switch(rv)
598         {
599         // 0: No errors, nothing special
600         case 0:
601                 break;
602         // 1: Subnormals
603         case 1:
604                 // TODO: Subnormal = 0?
605                 break;
606         // 2: Infinity
607         case 2:
608                 _putch('i');
609                 _putch('n');
610                 _putch('f');
611                 return 3;
612         case 3:
613                 _putch('N');
614                 _putch('a');
615                 _putch('N');
616                 return 3;
617         }
618
619         // - Used as 0/1 bools in arithmatic later on
620         bForcePoint = !!bForcePoint;
621         bForceSign = !!bForceSign;
622
623         // Apply default to precision
624         if( Precision == -1 )
625                 Precision = 6;
626
627         if( num < 0 )
628                 num = -num;
629
630         // Select optimum type
631         if( Notation == FPN_SHORTEST )
632         {
633                 //TODO:
634                 //int   first_set_sig = BSL(significand);
635         //      TODO: if( num > pos(Base, 2+Precision+2+log_base(exponent) )
636                 Notation = FPN_SCI;
637         }
638
639         double precision_max = 1;
640         while(Precision--)
641                 precision_max /= Base;
642
643         // Determine scientific's exponent and starting denominator
644         double den = 1;
645          int    sci_exponent = 0;
646         if( Notation == FPN_SCI )
647         {
648                 if( num < 1 )
649                 {
650                         while(num < 1)
651                         {
652                                 num *= Base;
653                                 sci_exponent ++;
654                         }
655                 }
656                 else if( num >= Base )
657                 {
658                         while(num >= Base)
659                         {
660                                 num /= Base;
661                                 sci_exponent ++;
662                         }
663                 }
664                 else
665                 {
666                         // no exponent
667                 }
668                 den = 1;
669         }
670         else
671         {
672                 while( den < num )
673                         den *= Base;
674                 den /= Base;
675         }
676
677         // Leading sign
678         if( signisneg )
679                 _putch('-');
680         else if( bForceSign )
681                 _putch('+');
682         else {
683         }
684
685          int    value;
686         // Whole section
687         do
688         {
689                 num = _longdiv(num, den, &value);
690                 _putch(cDIGITS[value]);
691                 den /= Base;
692         } while( den >= 1 );
693
694         // Decimal point (if needed/forced)     
695         if( den >= precision_max || bForcePoint )
696                 _putch('.');
697         // Decimal section
698         while( den >= precision_max )
699         {
700                 num = _longdiv(num, den, &value);
701                 _putch(cDIGITS[value]);
702                 den /= Base;
703         }
704
705         if( Notation == FPN_SCI )
706         {
707                 if( Base == 16 )
708                         _putch('p');
709                 else
710                         _putch('e');
711                 ret += _printf_itoa(putch_cb, putch_h, sci_exponent, Base, FALSE, TRUE, '+', 0, 0, '\0', FALSE);
712         }       
713
714         #undef _putch
715
716         return ret;
717 }

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