]> mj.ucw.cz Git - libucw.git/blob - ucw/mempool-str.c
hashtable: Implemented new HASH_TABLE_VARS parameter.
[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   uns l = strlen(s) + 1;
20   char *t = mp_alloc_fast_noalign(p, l);
21   memcpy(t, s, l);
22   return t;
23 }
24
25 void *
26 mp_memdup(struct mempool *p, const void *s, uns len)
27 {
28   void *t = mp_alloc_fast(p, len);
29   memcpy(t, s, len);
30   return t;
31 }
32
33 char *
34 mp_multicat(struct mempool *p, ...)
35 {
36   va_list args, a;
37   va_start(args, p);
38   char *x, *y;
39   uns cnt = 0;
40   va_copy(a, args);
41   while (x = va_arg(a, char *))
42     cnt++;
43   uns *sizes = alloca(cnt * sizeof(uns));
44   uns len = 1;
45   cnt = 0;
46   va_end(a);
47   va_copy(a, args);
48   while (x = va_arg(a, char *))
49     len += sizes[cnt++] = strlen(x);
50   char *buf = mp_alloc_fast_noalign(p, len);
51   y = buf;
52   va_end(a);
53   cnt = 0;
54   while (x = va_arg(args, char *))
55     {
56       memcpy(y, x, sizes[cnt]);
57       y += sizes[cnt++];
58     }
59   *y = 0;
60   va_end(args);
61   return buf;
62 }
63
64 char *
65 mp_strjoin(struct mempool *p, char **a, uns n, uns sep)
66 {
67   uns sizes[n];
68   uns len = 1;
69   for (uns i=0; i<n; i++)
70     len += sizes[i] = strlen(a[i]);
71   if (sep && n)
72     len += n-1;
73   char *dest = mp_alloc_fast_noalign(p, len);
74   char *d = dest;
75   for (uns i=0; i<n; i++)
76     {
77       if (sep && i)
78         *d++ = sep;
79       memcpy(d, a[i], sizes[i]);
80       d += sizes[i];
81     }
82   *d = 0;
83   return dest;
84 }
85
86 #ifdef TEST
87
88 #include <stdio.h>
89
90 int main(void)
91 {
92   struct mempool *p = mp_new(64);
93   char *s = mp_strdup(p, "12345");
94   char *c = mp_multicat(p, "<<", s, ">>", NULL);
95   puts(c);
96   char *a[] = { "bugs", "gnats", "insects" };
97   puts(mp_strjoin(p, a, 3, '.'));
98   puts(mp_strjoin(p, a, 3, 0));
99   return 0;
100 }
101
102 #endif