]> mj.ucw.cz Git - libucw.git/blobdiff - lib/stkstring.c
Fixed compilation rules for Perl modules to avoid unnecessary rebuilds.
[libucw.git] / lib / stkstring.c
index ccc689da64ba04e10f656631a1895f457520ba32..b583b24b870e4cf82482695fea874c57d89ad444 100644 (file)
@@ -13,7 +13,7 @@ stk_array_len(char **s, uns cnt)
 }
 
 void
-stk_array_copy(char *x, char **s, uns cnt)
+stk_array_join(char *x, char **s, uns cnt, uns sep)
 {
   while (cnt--)
     {
@@ -21,38 +21,54 @@ stk_array_copy(char *x, char **s, uns cnt)
       memcpy(x, *s, l);
       x += l;
       s++;
+      if (sep && cnt)
+       *x++ = sep;
     }
   *x = 0;
 }
 
-char *stk_printf_buf;
-static int stk_printf_len;
-
 uns
-stk_printf_internal(char *fmt, ...)
+stk_printf_internal(const char *fmt, ...)
 {
+  uns len = 256;
+  char *buf = alloca(len);
   va_list args, args2;
   va_start(args, fmt);
-  if (!stk_printf_buf)
+  for (;;)
     {
-      stk_printf_buf = xmalloc(256);
-      stk_printf_len = 256;
+      va_copy(args2, args);
+      int l = vsnprintf(buf, len, fmt, args2);
+      va_end(args2);
+      if (l < 0)
+       len *= 2;
+      else
+       {
+         va_end(args);
+         return l+1;
+       }
+      buf = alloca(len);
     }
+}
+
+uns
+stk_vprintf_internal(const char *fmt, va_list args)
+{
+  uns len = 256;
+  char *buf = alloca(len);
+  va_list args2;
   for (;;)
     {
       va_copy(args2, args);
-      int l = vsnprintf(stk_printf_buf, stk_printf_len, fmt, args2);
+      int l = vsnprintf(buf, len, fmt, args2);
       va_end(args2);
       if (l < 0)
-       stk_printf_len *= 2;
-      else if (l < stk_printf_len)
+       len *= 2;
+      else
        {
          va_end(args);
          return l+1;
        }
-      else
-       stk_printf_len = MAX(stk_printf_len*2, l+1);
-      stk_printf_buf = xrealloc(stk_printf_buf, stk_printf_len);
+      buf = alloca(len);
     }
 }
 
@@ -68,6 +84,27 @@ stk_hexdump_internal(char *dst, byte *src, uns n)
   *dst = 0;
 }
 
+void
+stk_fsize_internal(char *buf, u64 x)
+{
+  if (x < 1<<10)
+    sprintf(buf, "%dB", (int)x);
+  else if (x < 10<<10)
+    sprintf(buf, "%.1fK", (double)x/(1<<10));
+  else if (x < 1<<20)
+    sprintf(buf, "%dK", (int)(x/(1<<10)));
+  else if (x < 10<<20)
+    sprintf(buf, "%.1fM", (double)x/(1<<20));
+  else if (x < 1<<30)
+    sprintf(buf, "%dM", (int)(x/(1<<20)));
+  else if (x < (u64)10<<30)
+    sprintf(buf, "%.1fG", (double)x/(1<<30));
+  else if (x != ~(u64)0)
+    sprintf(buf, "%dG", (int)(x/(1<<30)));
+  else
+    strcpy(buf, "unknown");
+}
+
 #ifdef TEST
 
 int main(void)
@@ -80,6 +117,9 @@ int main(void)
   a = stk_printf("Bew%s!", a);
   puts(a);
   puts(stk_hexdump(a, 3));
+  char *ary[] = { "The", "jaws", "that", "bite" };
+  puts(stk_strjoin(ary, 4, ' '));
+  puts(stk_fsize(1234567));
   return 0;
 }