]> mj.ucw.cz Git - eval.git/blob - lib/stkstring.c
Detect breakpoint instructions, which are reported as syscall #-1.
[eval.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(const 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 uns
54 stk_vprintf_internal(const char *fmt, va_list args)
55 {
56   uns len = 256;
57   char *buf = alloca(len);
58   va_list args2;
59   for (;;)
60     {
61       va_copy(args2, args);
62       int l = vsnprintf(buf, len, fmt, args2);
63       va_end(args2);
64       if (l < 0)
65         len *= 2;
66       else
67         {
68           va_end(args);
69           return l+1;
70         }
71       buf = alloca(len);
72     }
73 }
74
75 void
76 stk_hexdump_internal(char *dst, const byte *src, uns n)
77 {
78   for (uns i=0; i<n; i++)
79     {
80       if (i)
81         *dst++ = ' ';
82       dst += sprintf(dst, "%02x", *src++);
83     }
84   *dst = 0;
85 }
86
87 void
88 stk_fsize_internal(char *buf, u64 x)
89 {
90   if (x < 1<<10)
91     sprintf(buf, "%dB", (int)x);
92   else if (x < 10<<10)
93     sprintf(buf, "%.1fK", (double)x/(1<<10));
94   else if (x < 1<<20)
95     sprintf(buf, "%dK", (int)(x/(1<<10)));
96   else if (x < 10<<20)
97     sprintf(buf, "%.1fM", (double)x/(1<<20));
98   else if (x < 1<<30)
99     sprintf(buf, "%dM", (int)(x/(1<<20)));
100   else if (x < (u64)10<<30)
101     sprintf(buf, "%.1fG", (double)x/(1<<30));
102   else if (x != ~(u64)0)
103     sprintf(buf, "%dG", (int)(x/(1<<30)));
104   else
105     strcpy(buf, "unknown");
106 }
107
108 #ifdef TEST
109
110 int main(void)
111 {
112   char *a = stk_strndup("are!",3);
113   a = stk_strcat(a, " the ");
114   a = stk_strmulticat(a, stk_strdup("Jabberwock, "), "my", NULL);
115   char *arr[] = { a, " son" };
116   a = stk_strarraycat(arr, 2);
117   a = stk_printf("Bew%s!", a);
118   puts(a);
119   puts(stk_hexdump(a, 3));
120   char *ary[] = { "The", "jaws", "that", "bite" };
121   puts(stk_strjoin(ary, 4, ' '));
122   puts(stk_fsize(1234567));
123   return 0;
124 }
125
126 #endif