]> mj.ucw.cz Git - libucw.git/blob - charset/mp-charconv.c
Slightly faster mp-charconv... minor change
[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 "lib/mempool.h"
12 #include "charset/mp-charconv.h"
13 #include <string.h>
14 #include <alloca.h>
15
16 byte *
17 mp_conv(struct mempool *mp, byte *s, uns in_cs, uns out_cs)
18 {
19   if (in_cs == out_cs)
20     return mp_strdup(mp, s);
21  
22   struct conv_context c;
23   char *b[32];
24   uns bs[32], n = 0, sum = 0;
25   uns l = strlen(s) + 1;
26   
27   conv_init(&c);
28   conv_set_charset(&c, in_cs, out_cs);
29   c.source = s;
30   c.source_end = s + l;
31
32   for (;;)
33     {
34       l <<= 1;
35       c.dest_start = c.dest = b[n] = alloca(l);
36       c.dest_end = c.dest_start+ l;
37       uns r = conv_run(&c);
38       sum += bs[n++] = c.dest - c.dest_start;
39       if (r & CONV_SOURCE_END)
40         {
41           c.dest_start = c.dest = mp_alloc(mp, sum);
42           for (uns i = 0; i < n; i++)
43             {
44               memcpy(c.dest, b[i], bs[i]);
45               c.dest += bs[i];
46             }
47           return c.dest_start;
48         }
49     }
50 }
51