]> mj.ucw.cz Git - libucw.git/blob - ucw/mempool-str.c
Build: Added support for custom PKG_CONFIG_PATH in UCW::Configure::PkgConfig().
[libucw.git] / ucw / mempool-str.c
1 /*
2  *      UCW Library -- Memory Pools (String Operations)
3  *
4  *      (c) 2004--2015 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 #include <ucw/unicode.h>
13
14 #include <alloca.h>
15 #include <string.h>
16
17 char *
18 mp_strdup(struct mempool *p, const char *s)
19 {
20   if (!s)
21     return NULL;
22   size_t l = strlen(s) + 1;
23   char *t = mp_alloc_fast_noalign(p, l);
24   memcpy(t, s, l);
25   return t;
26 }
27
28 void *
29 mp_memdup(struct mempool *p, const void *s, size_t len)
30 {
31   void *t = mp_alloc_fast(p, len);
32   memcpy(t, s, len);
33   return t;
34 }
35
36 char *
37 mp_multicat(struct mempool *p, ...)
38 {
39   va_list args, a;
40   va_start(args, p);
41   char *x, *y;
42   uint cnt = 0;
43   va_copy(a, args);
44   while (x = va_arg(a, char *))
45     cnt++;
46   size_t *sizes = alloca(cnt * sizeof(*sizes));
47   size_t len = 1;
48   cnt = 0;
49   va_end(a);
50   va_copy(a, args);
51   while (x = va_arg(a, char *))
52     len += sizes[cnt++] = strlen(x);
53   char *buf = mp_alloc_fast_noalign(p, len);
54   y = buf;
55   va_end(a);
56   cnt = 0;
57   while (x = va_arg(args, char *))
58     {
59       memcpy(y, x, sizes[cnt]);
60       y += sizes[cnt++];
61     }
62   *y = 0;
63   va_end(args);
64   return buf;
65 }
66
67 char *
68 mp_strjoin(struct mempool *p, char **a, uint n, uint sep)
69 {
70   size_t sizes[n];
71   size_t len = 1;
72   for (uint i=0; i<n; i++)
73     len += sizes[i] = strlen(a[i]);
74   if (sep && n)
75     len += n-1;
76   char *dest = mp_alloc_fast_noalign(p, len);
77   char *d = dest;
78   for (uint i=0; i<n; i++)
79     {
80       if (sep && i)
81         *d++ = sep;
82       memcpy(d, a[i], sizes[i]);
83       d += sizes[i];
84     }
85   *d = 0;
86   return dest;
87 }
88
89 char *
90 mp_str_from_mem(struct mempool *a, const void *mem, size_t len)
91 {
92   char *str = mp_alloc_noalign(a, len+1);
93   memcpy(str, mem, len);
94   str[len] = 0;
95   return str;
96 }
97
98 void *mp_append_utf8_32(struct mempool *pool, void *p, uint c)
99 {
100   p = mp_spread(pool, p, UTF8_MAX_LEN);
101   return utf8_32_put(p, c);
102 }
103
104 #ifdef TEST
105
106 #include <stdio.h>
107
108 int main(void)
109 {
110   struct mempool *p = mp_new(64);
111   char *s = mp_strdup(p, "12345");
112   char *c = mp_multicat(p, "<<", s, ">>", NULL);
113   puts(c);
114   char *a[] = { "bugs", "gnats", "insects" };
115   puts(mp_strjoin(p, a, 3, '.'));
116   puts(mp_strjoin(p, a, 3, 0));
117   puts(mp_str_from_mem(p, s+1, 2));
118   return 0;
119 }
120
121 #endif