35faa6cc4bd52ba2fca0354bb6436900093d44b1
[apps/madmutt.git] / utf8.c
1 /*
2  * Copyright notice from original mutt:
3  * [none]
4  *
5  * This file is part of mutt-ng, see http://www.muttng.org/.
6  * It's licensed under the GNU General Public License,
7  * please see the file GPL in the top level source directory.
8  */
9
10 #if HAVE_CONFIG_H
11 # include "config.h"
12 #endif
13
14 #ifndef HAVE_WC_FUNCS
15
16 #include <errno.h>
17
18 #ifndef EILSEQ
19 #define EILSEQ EINVAL
20 #endif
21
22 int mutt_wctoutf8(char *p, unsigned int c)
23 {
24     static unsigned char const mark[7] = {
25         0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC
26     };
27
28     int bytes;
29
30     if (c >= 0x200000) {
31         errno = EILSEQ;
32         return -1;
33     }
34
35     bytes = 1 + (c >= 0x80) + (c >= 0x800) + (c >= 0x10000);
36     p += bytes;
37
38     switch (bytes) {
39       case 4: *--p = (c | 0x80) & 0xbf; c >>= 6;
40       case 3: *--p = (c | 0x80) & 0xbf; c >>= 6;
41       case 2: *--p = (c | 0x80) & 0xbf; c >>= 6;
42       case 1: *--p =  c | mark[bytes];
43     }
44
45     return bytes;
46 }
47
48 #endif /* !HAVE_WC_FUNCS */