]> mj.ucw.cz Git - libucw.git/blob - charset/mp-charconv.c
Merge with git+ssh://git.ucw.cz/projects/sherlock/GIT/sherlock.git
[libucw.git] / charset / mp-charconv.c
1 /*
2  *      Sherlock Library -- Character Conversion with Allocation on a Memory Pool
3  *
4  *      (c) 2006 Pavel Charvat <pchar@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 "lib/lib.h"
11 #include "charset/mp-charconv.h"
12 #include <string.h>
13 #include <alloca.h>
14
15 byte *
16 mp_strconv(struct mempool *mp, byte *s, uns in_cs, uns out_cs)
17 {
18   if (in_cs == out_cs)
19     return mp_strdup(mp, s);
20
21   struct conv_context c;
22   char *b[32];
23   uns bs[32], n = 0, sum = 0;
24   uns l = strlen(s) + 1;
25
26   conv_init(&c);
27   conv_set_charset(&c, in_cs, out_cs);
28   c.source = s;
29   c.source_end = s + l;
30
31   for (;;)
32     {
33       l <<= 1;
34       c.dest_start = c.dest = b[n] = alloca(l);
35       c.dest_end = c.dest_start+ l;
36       uns r = conv_run(&c);
37       sum += bs[n++] = c.dest - c.dest_start;
38       if (r & CONV_SOURCE_END)
39         {
40           c.dest_start = c.dest = mp_alloc(mp, sum);
41           for (uns i = 0; i < n; i++)
42             {
43               memcpy(c.dest, b[i], bs[i]);
44               c.dest += bs[i];
45             }
46           return c.dest_start;
47         }
48     }
49 }
50