Subversion Repositories Kolibri OS

Rev

Blame | Last modification | View Log | Download | RSS feed

  1. /*
  2.         function for format output to the string. much lighter than standard sprintf
  3.         because of lesser formats supported
  4. */
  5.  
  6.  
  7. #include <string.h>
  8. //#include <stdio.h>
  9. #include <ctype.h>
  10. #include <stdarg.h>
  11.  
  12. char* __itoa(int n,char* s);
  13. char* itoab(unsigned int n, char* s, int  b);
  14.  
  15. int tiny_vsnprintf (char * s, size_t n, const char * format, va_list args )
  16. // support %c, %s, %d, %x, %u, %% for 32-bit values only. no width specs, left align
  17. // always zero-ended
  18. {
  19.     char *fmt, *dest, buf[32];
  20.     fmt = (char*)format;
  21.     dest = s; dest[n - 1] = '\0';
  22.     int     arg, len;
  23.     while (*fmt && (dest - s < n - 1))
  24.     {
  25.         if (*fmt != '%')
  26.         {
  27.             *dest++ = *fmt++;
  28.             continue;
  29.         }
  30.         if (fmt[1] == '%') // %%
  31.         {
  32.             *dest++ = '%';
  33.             fmt += 2;
  34.             continue;
  35.         }
  36.         arg = va_arg(args, int);
  37.         len = n - 1 - (dest - s);
  38.         switch (*++fmt)
  39.         {
  40.         case 'c':
  41.             *dest++ = (char)arg;
  42.             break;
  43.         case 's':
  44.             strncpy(dest, (char*)arg, len);
  45.             dest = strchr(dest, 0);
  46.             break;
  47.         case 'd':
  48.             __itoa(arg, buf);
  49.             strncpy(dest, buf, len);
  50.             dest = strchr(dest, 0);
  51.             break;
  52.         case 'x':
  53.             itoab((unsigned)arg, buf, 16);
  54.             strncpy(dest, buf, len);
  55.             dest = strchr(dest, 0);
  56.             break;
  57.         case 'u':
  58.             itoab((unsigned)arg, buf, 10);
  59.             strncpy(dest, buf, len);
  60.             dest = strchr(dest, 0);
  61.             break;
  62.         default:
  63.             *dest++ = *fmt;
  64.         }
  65.         fmt++;
  66.     }
  67.     *dest = '\0';
  68.     return dest - s;
  69. }
  70.  
  71.  
  72. int tiny_snprintf (char * s, size_t n, const char * format, ... )
  73. {
  74.    va_list      arg;
  75.    int  rc;
  76.    va_start(arg, format);
  77.  
  78.    rc = tiny_vsnprintf(s, n, format, arg);
  79.  
  80.    va_end(arg);
  81.    return rc;
  82. }
  83.  
  84. int tiny_sprintf (char * s, const char * format, ... )
  85. {
  86.    va_list      arg;
  87.    int  rc;
  88.    va_start(arg, format);
  89.  
  90.    rc = tiny_vsnprintf(s, 4096, format, arg);
  91.  
  92.    va_end(arg);
  93.    return rc;
  94. }
  95.  
  96.  
  97.  
  98.