]> mj.ucw.cz Git - libucw.git/blob - lib/stkstring.c
4fa5ab14ed551f5a7d5eebb87de49e78ed8ea1df
[libucw.git] / lib / stkstring.c
1 #include "lib/lib.h"
2 #include "lib/stkstring.h"
3
4 #include <stdio.h>
5
6 uns
7 stk_array_len(char **s, uns cnt)
8 {
9   uns l = 1;
10   while (cnt--)
11     l += strlen(*s++);
12   return l;
13 }
14
15 void
16 stk_array_join(char *x, char **s, uns cnt, uns sep)
17 {
18   while (cnt--)
19     {
20       uns l = strlen(*s);
21       memcpy(x, *s, l);
22       x += l;
23       s++;
24       if (sep && cnt)
25         *x++ = sep;
26     }
27   *x = 0;
28 }
29
30 uns
31 stk_printf_internal(char *fmt, ...)
32 {
33   uns len = 256;
34   char *buf = alloca(len);
35   va_list args, args2;
36   va_start(args, fmt);
37   for (;;)
38     {
39       va_copy(args2, args);
40       int l = vsnprintf(buf, len, fmt, args2);
41       va_end(args2);
42       if (l < 0)
43         len *= 2;
44       else
45         {
46           va_end(args);
47           return l+1;
48         }
49       buf = alloca(len);
50     }
51 }
52
53 void
54 stk_hexdump_internal(char *dst, byte *src, uns n)
55 {
56   for (uns i=0; i<n; i++)
57     {
58       if (i)
59         *dst++ = ' ';
60       dst += sprintf(dst, "%02x", *src++);
61     }
62   *dst = 0;
63 }
64
65 void
66 stk_fsize_internal(char *buf, u64 x)
67 {
68   if (x < 1<<10)
69     sprintf(buf, "%dB", (int)x);
70   else if (x < 10<<10)
71     sprintf(buf, "%.1fK", (double)x/(1<<10));
72   else if (x < 1<<20)
73     sprintf(buf, "%dK", (int)(x/(1<<10)));
74   else if (x < 10<<20)
75     sprintf(buf, "%.1fM", (double)x/(1<<20));
76   else if (x < 1<<30)
77     sprintf(buf, "%dM", (int)(x/(1<<20)));
78   else if (x < (u64)10<<30)
79     sprintf(buf, "%.1fG", (double)x/(1<<30));
80   else if (x != ~(u64)0)
81     sprintf(buf, "%dG", (int)(x/(1<<30)));
82   else
83     strcpy(buf, "unknown");
84 }
85
86 #ifdef TEST
87
88 int main(void)
89 {
90   char *a = stk_strndup("are!",3);
91   a = stk_strcat(a, " the ");
92   a = stk_strmulticat(a, stk_strdup("Jabberwock, "), "my", NULL);
93   char *arr[] = { a, " son" };
94   a = stk_strarraycat(arr, 2);
95   a = stk_printf("Bew%s!", a);
96   puts(a);
97   puts(stk_hexdump(a, 3));
98   char *ary[] = { "The", "jaws", "that", "bite" };
99   puts(stk_strjoin(ary, 4, ' '));
100   puts(stk_fsize(1234567));
101   return 0;
102 }
103
104 #endif