]> mj.ucw.cz Git - libucw.git/blob - ucw/mempool-str.c
Packages: install-ucw-sorter-api make target moved into install-libucw-api.
[libucw.git] / ucw / mempool-str.c
1 /*
2  *      UCW Library -- Memory Pools (String Operations)
3  *
4  *      (c) 2004 Martin Mares <mj@ucw.cz>
5  *
6  *      This software may be freely distributed and used according to the terms
7  *      of the GNU Lesser General Public License.
8  */
9
10 #include <ucw/lib.h>
11 #include <ucw/mempool.h>
12
13 #include <alloca.h>
14 #include <string.h>
15
16 char *
17 mp_strdup(struct mempool *p, const char *s)
18 {
19   if (!s)
20     return NULL;
21   uns l = strlen(s) + 1;
22   char *t = mp_alloc_fast_noalign(p, l);
23   memcpy(t, s, l);
24   return t;
25 }
26
27 void *
28 mp_memdup(struct mempool *p, const void *s, uns len)
29 {
30   void *t = mp_alloc_fast(p, len);
31   memcpy(t, s, len);
32   return t;
33 }
34
35 char *
36 mp_multicat(struct mempool *p, ...)
37 {
38   va_list args, a;
39   va_start(args, p);
40   char *x, *y;
41   uns cnt = 0;
42   va_copy(a, args);
43   while (x = va_arg(a, char *))
44     cnt++;
45   uns *sizes = alloca(cnt * sizeof(uns));
46   uns len = 1;
47   cnt = 0;
48   va_end(a);
49   va_copy(a, args);
50   while (x = va_arg(a, char *))
51     len += sizes[cnt++] = strlen(x);
52   char *buf = mp_alloc_fast_noalign(p, len);
53   y = buf;
54   va_end(a);
55   cnt = 0;
56   while (x = va_arg(args, char *))
57     {
58       memcpy(y, x, sizes[cnt]);
59       y += sizes[cnt++];
60     }
61   *y = 0;
62   va_end(args);
63   return buf;
64 }
65
66 char *
67 mp_strjoin(struct mempool *p, char **a, uns n, uns sep)
68 {
69   uns sizes[n];
70   uns len = 1;
71   for (uns i=0; i<n; i++)
72     len += sizes[i] = strlen(a[i]);
73   if (sep && n)
74     len += n-1;
75   char *dest = mp_alloc_fast_noalign(p, len);
76   char *d = dest;
77   for (uns i=0; i<n; i++)
78     {
79       if (sep && i)
80         *d++ = sep;
81       memcpy(d, a[i], sizes[i]);
82       d += sizes[i];
83     }
84   *d = 0;
85   return dest;
86 }
87
88 char *
89 mp_str_from_mem(struct mempool *a, const void *mem, uns len)
90 {
91   char *str = mp_alloc_noalign(a, len+1);
92   memcpy(str, mem, len);
93   str[len] = 0;
94   return str;
95 }
96
97 #ifdef TEST
98
99 #include <stdio.h>
100
101 int main(void)
102 {
103   struct mempool *p = mp_new(64);
104   char *s = mp_strdup(p, "12345");
105   char *c = mp_multicat(p, "<<", s, ">>", NULL);
106   puts(c);
107   char *a[] = { "bugs", "gnats", "insects" };
108   puts(mp_strjoin(p, a, 3, '.'));
109   puts(mp_strjoin(p, a, 3, 0));
110   puts(mp_str_from_mem(p, s+1, 2));
111   return 0;
112 }
113
114 #endif