Sync Citrus iconv support with NetBSD.
[dragonfly.git] / lib / libc / citrus / modules / citrus_iso2022.c
1 /* $NetBSD: citrus_iso2022.c,v 1.18 2007/11/21 14:19:32 tnozaki Exp $ */
2 /* $DragonFly: src/lib/libc/citrus/modules/citrus_iso2022.c,v 1.2 2008/04/10 10:21:01 hasso Exp $ */
3
4 /*-
5  * Copyright (c)1999, 2002 Citrus Project,
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  *      $Citrus: xpg4dl/FreeBSD/lib/libc/locale/iso2022.c,v 1.23 2001/06/21 01:51:44 yamt Exp $
30  */
31
32 #include <sys/types.h>
33 #include <assert.h>
34 #include <errno.h>
35 #include <limits.h>
36 #include <locale.h>
37 #include <stddef.h>
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <wchar.h>
42
43 #include "citrus_namespace.h"
44 #include "citrus_types.h"
45 #include "citrus_module.h"
46 #include "citrus_ctype.h"
47 #include "citrus_stdenc.h"
48 #include "citrus_iso2022.h"
49
50
51 /* ----------------------------------------------------------------------
52  * private stuffs used by templates
53  */
54
55
56 /*
57  * wchar_t mappings:
58  * ASCII (ESC ( B)              00000000 00000000 00000000 0xxxxxxx
59  * iso-8859-1 (ESC , A)         00000000 00000000 00000000 1xxxxxxx
60  * 94 charset (ESC ( F)         0fffffff 00000000 00000000 0xxxxxxx
61  * 94 charset (ESC ( M F)       0fffffff 1mmmmmmm 00000000 0xxxxxxx
62  * 96 charset (ESC , F)         0fffffff 00000000 00000000 1xxxxxxx
63  * 96 charset (ESC , M F)       0fffffff 1mmmmmmm 00000000 1xxxxxxx
64  * 94x94 charset (ESC $ ( F)    0fffffff 00000000 0xxxxxxx 0xxxxxxx
65  * 96x96 charset (ESC $ , F)    0fffffff 00000000 0xxxxxxx 1xxxxxxx
66  * 94x94 charset (ESC & V ESC $ ( F)
67  *                              0fffffff 1vvvvvvv 0xxxxxxx 0xxxxxxx
68  * 94x94x94 charset (ESC $ ( F) 0fffffff 0xxxxxxx 0xxxxxxx 0xxxxxxx
69  * 96x96x96 charset (ESC $ , F) 0fffffff 0xxxxxxx 0xxxxxxx 1xxxxxxx
70  * reserved for UCS4 co-existence (UCS4 is 31bit encoding thanks to mohta bit)
71  *                              1xxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx
72  */
73
74 typedef struct {
75         u_char  type;
76 #define CS94            (0U)
77 #define CS96            (1U)
78 #define CS94MULTI       (2U)
79 #define CS96MULTI       (3U)
80
81         u_char  final;
82         u_char  interm;
83         u_char  vers;
84 } _ISO2022Charset;
85
86 static const _ISO2022Charset ascii    = { CS94, 'B', '\0', '\0' };
87 static const _ISO2022Charset iso88591 = { CS96, 'A', '\0', '\0' };
88
89 typedef struct {
90         _ISO2022Charset g[4];
91         /* need 3 bits to hold -1, 0, ..., 3 */
92         int     gl:3,
93                 gr:3,
94                 singlegl:3,
95                 singlegr:3;
96         char ch[7];     /* longest escape sequence (ESC & V ESC $ ( F) */
97         int chlen;
98         int flags;
99 #define _ISO2022STATE_FLAG_INITIALIZED  1
100 } _ISO2022State;
101
102 typedef struct {
103         _ISO2022Charset *recommend[4];
104         size_t  recommendsize[4];
105         _ISO2022Charset initg[4];
106         int     maxcharset;
107         int     flags;
108 #define F_8BIT  0x0001
109 #define F_NOOLD 0x0002
110 #define F_SI    0x0010  /*0F*/
111 #define F_SO    0x0020  /*0E*/
112 #define F_LS0   0x0010  /*0F*/
113 #define F_LS1   0x0020  /*0E*/
114 #define F_LS2   0x0040  /*ESC n*/
115 #define F_LS3   0x0080  /*ESC o*/
116 #define F_LS1R  0x0100  /*ESC ~*/
117 #define F_LS2R  0x0200  /*ESC }*/
118 #define F_LS3R  0x0400  /*ESC |*/
119 #define F_SS2   0x0800  /*ESC N*/
120 #define F_SS3   0x1000  /*ESC O*/
121 #define F_SS2R  0x2000  /*8E*/
122 #define F_SS3R  0x4000  /*8F*/
123 } _ISO2022EncodingInfo;
124 typedef struct {
125         _ISO2022EncodingInfo ei;
126         struct {
127                 /* for future multi-locale facility */
128                 _ISO2022State   s_mblen;
129                 _ISO2022State   s_mbrlen;
130                 _ISO2022State   s_mbrtowc;
131                 _ISO2022State   s_mbtowc;
132                 _ISO2022State   s_mbsrtowcs;
133                 _ISO2022State   s_wcrtomb;
134                 _ISO2022State   s_wcsrtombs;
135                 _ISO2022State   s_wctomb;
136         } states;
137 } _ISO2022CTypeInfo;
138
139 #define _CEI_TO_EI(_cei_)               (&(_cei_)->ei)
140 #define _CEI_TO_STATE(_cei_, _func_)    (_cei_)->states.s_##_func_
141
142 #define _FUNCNAME(m)                    _citrus_ISO2022_##m
143 #define _ENCODING_INFO                  _ISO2022EncodingInfo
144 #define _CTYPE_INFO                     _ISO2022CTypeInfo
145 #define _ENCODING_STATE                 _ISO2022State
146 #define _ENCODING_MB_CUR_MAX(_ei_)      MB_LEN_MAX
147 #define _ENCODING_IS_STATE_DEPENDENT    1
148 #define _STATE_NEEDS_EXPLICIT_INIT(_ps_)        \
149     (!((_ps_)->flags & _ISO2022STATE_FLAG_INITIALIZED))
150
151
152 #define _ISO2022INVALID (wchar_t)-1
153
154 static __inline int isc0(__uint8_t x) { return ((x & 0x1f) == x); }
155 static __inline int isc1(__uint8_t x) { return (0x80 <= x && x <= 0x9f); }
156 static __inline int iscntl(__uint8_t x) { return (isc0(x) || isc1(x) || x == 0x7f); }
157 static __inline int is94(__uint8_t x) { return (0x21 <= x && x <= 0x7e); }
158 static __inline int is96(__uint8_t x) { return (0x20 <= x && x <= 0x7f); }
159 static __inline int isecma(__uint8_t x) { return (0x30 <= x && x <= 0x7f); }
160 static __inline int isinterm(__uint8_t x) { return (0x20 <= x && x <= 0x2f); }
161 static __inline int isthree(__uint8_t x) { return (0x60 <= x && x <= 0x6f); }
162
163 static __inline int
164 getcs(const char * __restrict p, _ISO2022Charset * __restrict cs)
165 {
166
167         _DIAGASSERT(p != NULL);
168         _DIAGASSERT(cs != NULL);
169
170         if (!strncmp(p, "94$", 3) && p[3] && !p[4]) {
171                 cs->final = (u_char)(p[3] & 0xff);
172                 cs->interm = '\0';
173                 cs->vers = '\0';
174                 cs->type = CS94MULTI;
175         } else if (!strncmp(p, "96$", 3) && p[3] && !p[4]) {
176                 cs->final = (u_char)(p[3] & 0xff);
177                 cs->interm = '\0';
178                 cs->vers = '\0';
179                 cs->type = CS96MULTI;
180         } else if (!strncmp(p, "94", 2) && p[2] && !p[3]) {
181                 cs->final = (u_char)(p[2] & 0xff);
182                 cs->interm = '\0';
183                 cs->vers = '\0';
184                 cs->type = CS94;
185         } else if (!strncmp(p, "96", 2) && p[2] && !p[3]) {
186                 cs->final = (u_char )(p[2] & 0xff);
187                 cs->interm = '\0';
188                 cs->vers = '\0';
189                 cs->type = CS96;
190         } else {
191                 return 1;
192         }
193
194         return 0;
195 }
196
197
198 #define _NOTMATCH       0
199 #define _MATCH          1
200 #define _PARSEFAIL      2
201
202 static __inline int
203 get_recommend(_ISO2022EncodingInfo * __restrict ei,
204               const char * __restrict token)
205 {
206         int i;
207         _ISO2022Charset cs, *p;
208
209         if (!strchr("0123", token[0]) || token[1] != '=')
210                 return (_NOTMATCH);
211
212         if (getcs(&token[2], &cs) == 0)
213                 ;
214         else if (!strcmp(&token[2], "94")) {
215                 cs.final = (u_char)(token[4]);
216                 cs.interm = '\0';
217                 cs.vers = '\0';
218                 cs.type = CS94;
219         } else if (!strcmp(&token[2], "96")) {
220                 cs.final = (u_char)(token[4]);
221                 cs.interm = '\0';
222                 cs.vers = '\0';
223                 cs.type = CS96;
224         } else if (!strcmp(&token[2], "94$")) {
225                 cs.final = (u_char)(token[5]);
226                 cs.interm = '\0';
227                 cs.vers = '\0';
228                 cs.type = CS94MULTI;
229         } else if (!strcmp(&token[2], "96$")) {
230                 cs.final = (u_char)(token[5]);
231                 cs.interm = '\0';
232                 cs.vers = '\0';
233                 cs.type = CS96MULTI;
234         } else {
235                 return (_PARSEFAIL);
236         }
237
238         i = token[0] - '0';
239         if (!ei->recommend[i]) {
240                 ei->recommend[i] = malloc(sizeof(_ISO2022Charset));
241         } else {
242                 p = realloc(ei->recommend[i],
243                     sizeof(_ISO2022Charset) * (ei->recommendsize[i] + 1));
244                 if (!p)
245                         return (_PARSEFAIL);
246                 ei->recommend[i] = p;
247         }
248         if (!ei->recommend[i])
249                 return (_PARSEFAIL);
250         ei->recommendsize[i]++;
251
252         (ei->recommend[i] + (ei->recommendsize[i] - 1))->final = cs.final;
253         (ei->recommend[i] + (ei->recommendsize[i] - 1))->interm = cs.interm;
254         (ei->recommend[i] + (ei->recommendsize[i] - 1))->vers = cs.vers;
255         (ei->recommend[i] + (ei->recommendsize[i] - 1))->type = cs.type;
256
257         return (_MATCH);
258 }
259
260 static __inline int
261 get_initg(_ISO2022EncodingInfo * __restrict ei,
262           const char * __restrict token)
263 {
264         _ISO2022Charset cs;
265
266         if (strncmp("INIT", &token[0], 4) ||
267             !strchr("0123", token[4]) ||
268             token[5] != '=')
269                 return (_NOTMATCH);
270
271         if (getcs(&token[6], &cs) != 0)
272                 return (_PARSEFAIL);
273
274         ei->initg[token[4] - '0'].type = cs.type;
275         ei->initg[token[4] - '0'].final = cs.final;
276         ei->initg[token[4] - '0'].interm = cs.interm;
277         ei->initg[token[4] - '0'].vers = cs.vers;
278
279         return (_MATCH);
280 }
281
282 static __inline int
283 get_max(_ISO2022EncodingInfo * __restrict ei,
284         const char * __restrict token)
285 {
286         if (!strcmp(token, "MAX1")) {
287                 ei->maxcharset = 1;
288         } else if (!strcmp(token, "MAX2")) {
289                 ei->maxcharset = 2;
290         } else if (!strcmp(token, "MAX3")) {
291                 ei->maxcharset = 3;
292         } else
293                 return (_NOTMATCH);
294
295         return (_MATCH);
296 }
297
298
299 static __inline int
300 get_flags(_ISO2022EncodingInfo * __restrict ei,
301           const char * __restrict token)
302 {
303         int i;
304         static struct {
305                 const char      *tag;
306                 int             flag;
307         } const tags[] = {
308                 { "DUMMY",      0       },
309                 { "8BIT",       F_8BIT  },
310                 { "NOOLD",      F_NOOLD },
311                 { "SI",         F_SI    },
312                 { "SO",         F_SO    },
313                 { "LS0",        F_LS0   },
314                 { "LS1",        F_LS1   },
315                 { "LS2",        F_LS2   },
316                 { "LS3",        F_LS3   },
317                 { "LS1R",       F_LS1R  },
318                 { "LS2R",       F_LS2R  },
319                 { "LS3R",       F_LS3R  },
320                 { "SS2",        F_SS2   },
321                 { "SS3",        F_SS3   },
322                 { "SS2R",       F_SS2R  },
323                 { "SS3R",       F_SS3R  },
324                 { NULL,         0 }
325         };
326
327         for (i = 0; tags[i].tag; i++) {
328                 if (!strcmp(token, tags[i].tag)) {
329                         ei->flags |= tags[i].flag;
330                         return (_MATCH);
331                 }
332         }
333
334         return (_NOTMATCH);
335 }
336
337
338 static __inline int
339 _citrus_ISO2022_parse_variable(_ISO2022EncodingInfo * __restrict ei,
340                                const void * __restrict var, size_t lenvar)
341 {
342         char const *v, *e;
343         char buf[20];
344         int i, len, ret;
345
346         _DIAGASSERT(ei != NULL);
347
348
349         /*
350          * parse VARIABLE section.
351          */
352
353         if (!var)
354                 return (EFTYPE);
355
356         v = (const char *) var;
357
358         /* initialize structure */
359         ei->maxcharset = 0;
360         for (i = 0; i < 4; i++) {
361                 ei->recommend[i] = NULL;
362                 ei->recommendsize[i] = 0;
363         }
364         ei->flags = 0;
365
366         while (*v) {
367                 while (*v == ' ' || *v == '\t')
368                         ++v;
369
370                 /* find the token */
371                 e = v;
372                 while (*e && *e != ' ' && *e != '\t')
373                         ++e;
374
375                 len = e-v;
376                 if (len == 0)
377                         break;
378                 if (len>=sizeof(buf))
379                         goto parsefail;
380                 snprintf(buf, sizeof(buf), "%.*s", len, v);
381
382                 if ((ret = get_recommend(ei, buf)) != _NOTMATCH)
383                         ;
384                 else if ((ret = get_initg(ei, buf)) != _NOTMATCH)
385                         ;
386                 else if ((ret = get_max(ei, buf)) != _NOTMATCH)
387                         ;
388                 else if ((ret = get_flags(ei, buf)) != _NOTMATCH)
389                         ;
390                 else
391                         ret = _PARSEFAIL;
392                 if (ret==_PARSEFAIL)
393                         goto parsefail;
394                 v = e;
395
396         }
397
398         return (0);
399
400 parsefail:
401         free(ei->recommend[0]);
402         free(ei->recommend[1]);
403         free(ei->recommend[2]);
404         free(ei->recommend[3]);
405
406         return (EFTYPE);
407 }
408
409 static __inline void
410 /*ARGSUSED*/
411 _citrus_ISO2022_init_state(_ISO2022EncodingInfo * __restrict ei,
412                            _ISO2022State * __restrict s)
413 {
414         int i;
415
416         memset(s, 0, sizeof(*s));
417         s->gl = 0;
418         s->gr = (ei->flags & F_8BIT) ? 1 : -1;
419
420         for (i = 0; i < 4; i++) {
421                 if (ei->initg[i].final) {
422                         s->g[i].type = ei->initg[i].type;
423                         s->g[i].final = ei->initg[i].final;
424                         s->g[i].interm = ei->initg[i].interm;
425                 }
426         }
427         s->singlegl = s->singlegr = -1;
428         s->flags |= _ISO2022STATE_FLAG_INITIALIZED;
429 }
430
431 static __inline void
432 /*ARGSUSED*/
433 _citrus_ISO2022_pack_state(_ISO2022EncodingInfo * __restrict ei,
434                            void * __restrict pspriv,
435                            const _ISO2022State * __restrict s)
436 {
437         memcpy(pspriv, (const void *)s, sizeof(*s));
438 }
439
440 static __inline void
441 /*ARGSUSED*/
442 _citrus_ISO2022_unpack_state(_ISO2022EncodingInfo * __restrict ei,
443                              _ISO2022State * __restrict s,
444                              const void * __restrict pspriv)
445 {
446         memcpy((void *)s, pspriv, sizeof(*s));
447 }
448
449 static int
450 /*ARGSUSED*/
451 _citrus_ISO2022_encoding_module_init(_ISO2022EncodingInfo * __restrict ei,
452                                      const void * __restrict var,
453                                      size_t lenvar)
454 {
455
456         _DIAGASSERT(ei != NULL);
457
458         return _citrus_ISO2022_parse_variable(ei, var, lenvar);
459 }
460
461 static void
462 /*ARGSUSED*/
463 _citrus_ISO2022_encoding_module_uninit(_ISO2022EncodingInfo *ei)
464 {
465 }
466
467 #define ESC     '\033'
468 #define ECMA    -1
469 #define INTERM  -2
470 #define OECMA   -3
471
472 static const struct seqtable {
473         int type;
474         int csoff;
475         int finaloff;
476         int intermoff;
477         int versoff;
478         int len;
479         int chars[10];
480 } seqtable[] = {
481         /* G0 94MULTI special */
482         { CS94MULTI, -1, 2, -1, -1,     3, { ESC, '$', OECMA }, },
483         /* G0 94MULTI special with version identification */
484         { CS94MULTI, -1, 5, -1, 2,      6, { ESC, '&', ECMA, ESC, '$', OECMA }, },
485         /* G? 94 */
486         { CS94, 1, 2, -1, -1,           3, { ESC, CS94, ECMA, }, },
487         /* G? 94 with 2nd intermediate char */
488         { CS94, 1, 3, 2, -1,            4, { ESC, CS94, INTERM, ECMA, }, },
489         /* G? 96 */
490         { CS96, 1, 2, -1, -1,           3, { ESC, CS96, ECMA, }, },
491         /* G? 96 with 2nd intermediate char */
492         { CS96, 1, 3, 2, -1,            4, { ESC, CS96, INTERM, ECMA, }, },
493         /* G? 94MULTI */
494         { CS94MULTI, 2, 3, -1, -1,      4, { ESC, '$', CS94, ECMA, }, },
495         /* G? 96MULTI */
496         { CS96MULTI, 2, 3, -1, -1,      4, { ESC, '$', CS96, ECMA, }, },
497         /* G? 94MULTI with version specification */
498         { CS94MULTI, 5, 6, -1, 2,       7, { ESC, '&', ECMA, ESC, '$', CS94, ECMA, }, },
499         /* LS2/3 */
500         { -1, -1, -1, -1, -1,           2, { ESC, 'n', }, },
501         { -1, -1, -1, -1, -1,           2, { ESC, 'o', }, },
502         /* LS1/2/3R */
503         { -1, -1, -1, -1, -1,           2, { ESC, '~', }, },
504         { -1, -1, -1, -1, -1,           2, { ESC, /*{*/ '}', }, },
505         { -1, -1, -1, -1, -1,           2, { ESC, '|', }, },
506         /* SS2/3 */
507         { -1, -1, -1, -1, -1,           2, { ESC, 'N', }, },
508         { -1, -1, -1, -1, -1,           2, { ESC, 'O', }, },
509         /* end of records */
510         { 0, }
511 };
512
513 static int
514 seqmatch(const char * __restrict s, size_t n,
515          const struct seqtable * __restrict sp)
516 {
517         const int *p;
518
519         _DIAGASSERT(s != NULL);
520         _DIAGASSERT(sp != NULL);
521
522         p = sp->chars;
523         while (p - sp->chars < n && p - sp->chars < sp->len) {
524                 switch (*p) {
525                 case ECMA:
526                         if (!isecma(*s))
527                                 goto terminate;
528                         break;
529                 case OECMA:
530                         if (*s && strchr("@AB", *s))
531                                 break;
532                         else
533                                 goto terminate;
534                 case INTERM:
535                         if (!isinterm(*s))
536                                 goto terminate;
537                         break;
538                 case CS94:
539                         if (*s && strchr("()*+", *s))
540                                 break;
541                         else
542                                 goto terminate;
543                 case CS96:
544                         if (*s && strchr(",-./", *s))
545                                 break;
546                         else
547                                 goto terminate;
548                 default:
549                         if (*s != *p)
550                                 goto terminate;
551                         break;
552                 }
553
554                 p++;
555                 s++;
556         }
557
558 terminate:
559         return p - sp->chars;
560 }
561
562 static wchar_t
563 _ISO2022_sgetwchar(_ISO2022EncodingInfo * __restrict ei,
564                 const char * __restrict string, size_t n,
565                 const char ** __restrict result,
566                 _ISO2022State * __restrict psenc)
567 {
568         wchar_t wchar = 0;
569         int cur;
570         const struct seqtable *sp;
571         int nmatch;
572         int i;
573
574         _DIAGASSERT(ei != NULL);
575         _DIAGASSERT(string != NULL);
576         /* result may be NULL */
577
578         while (1) {
579                 /* SI/SO */
580                 if (1 <= n && string[0] == '\017') {
581                         psenc->gl = 0;
582                         string++;
583                         n--;
584                         continue;
585                 }
586                 if (1 <= n && string[0] == '\016') {
587                         psenc->gl = 1;
588                         string++;
589                         n--;
590                         continue;
591                 }
592
593                 /* SS2/3R */
594                 if (1 <= n && string[0] && strchr("\217\216", string[0])) {
595                         psenc->singlegl = psenc->singlegr =
596                             (string[0] - '\216') + 2;
597                         string++;
598                         n--;
599                         continue;
600                 }
601
602                 /* eat the letter if this is not ESC */
603                 if (1 <= n && string[0] != '\033')
604                         break;
605
606                 /* look for a perfect match from escape sequences */
607                 for (sp = &seqtable[0]; sp->len; sp++) {
608                         nmatch = seqmatch(string, n, sp);
609                         if (sp->len == nmatch && n >= sp->len)
610                                 break;
611                 }
612
613                 if (!sp->len)
614                         goto notseq;
615
616                 if (sp->type != -1) {
617                         if (sp->csoff == -1)
618                                 i = 0;
619                         else {
620                                 switch (sp->type) {
621                                 case CS94:
622                                 case CS94MULTI:
623                                         i = string[sp->csoff] - '(';
624                                         break;
625                                 case CS96:
626                                 case CS96MULTI:
627                                         i = string[sp->csoff] - ',';
628                                         break;
629                                 default:
630                                         return (_ISO2022INVALID);
631                                 }
632                         }
633                         psenc->g[i].type = sp->type;
634                         psenc->g[i].final = '\0';
635                         psenc->g[i].interm = '\0';
636                         psenc->g[i].vers = '\0';
637                         /* sp->finaloff must not be -1 */
638                         if (sp->finaloff != -1)
639                                 psenc->g[i].final = string[sp->finaloff];
640                         if (sp->intermoff != -1)
641                                 psenc->g[i].interm = string[sp->intermoff];
642                         if (sp->versoff != -1)
643                                 psenc->g[i].vers = string[sp->versoff];
644
645                         string += sp->len;
646                         n -= sp->len;
647                         continue;
648                 }
649
650                 /* LS2/3 */
651                 if (2 <= n && string[0] == '\033'
652                  && string[1] && strchr("no", string[1])) {
653                         psenc->gl = string[1] - 'n' + 2;
654                         string += 2;
655                         n -= 2;
656                         continue;
657                 }
658
659                 /* LS1/2/3R */
660                         /* XXX: { for vi showmatch */
661                 if (2 <= n && string[0] == '\033'
662                  && string[1] && strchr("~}|", string[1])) {
663                         psenc->gr = 3 - (string[1] - '|');
664                         string += 2;
665                         n -= 2;
666                         continue;
667                 }
668
669                 /* SS2/3 */
670                 if (2 <= n && string[0] == '\033'
671                  && string[1] && strchr("NO", string[1])) {
672                         psenc->singlegl = (string[1] - 'N') + 2;
673                         string += 2;
674                         n -= 2;
675                         continue;
676                 }
677
678         notseq:
679                 /*
680                  * if we've got an unknown escape sequence, eat the ESC at the
681                  * head.  otherwise, wait till full escape sequence comes.
682                  */
683                 for (sp = &seqtable[0]; sp->len; sp++) {
684                         nmatch = seqmatch(string, n, sp);
685                         if (!nmatch)
686                                 continue;
687
688                         /*
689                          * if we are in the middle of escape sequence,
690                          * we still need to wait for more characters to come
691                          */
692                         if (n < sp->len) {
693                                 if (nmatch == n) {
694                                         if (result)
695                                                 *result = string;
696                                         return (_ISO2022INVALID);
697                                 }
698                         } else {
699                                 if (nmatch == sp->len) {
700                                         /* this case should not happen */
701                                         goto eat;
702                                 }
703                         }
704                 }
705
706                 break;
707         }
708
709 eat:
710         /* no letter to eat */
711         if (n < 1) {
712                 if (result)
713                         *result = string;
714                 return (_ISO2022INVALID);
715         }
716
717         /* normal chars.  always eat C0/C1 as is. */
718         if (iscntl(*string & 0xff))
719                 cur = -1;
720         else if (*string & 0x80) {
721                 cur = (psenc->singlegr == -1)
722                         ? psenc->gr : psenc->singlegr;
723         } else {
724                 cur = (psenc->singlegl == -1)
725                         ? psenc->gl : psenc->singlegl;
726         }
727
728         if (cur == -1) {
729 asis:
730                 wchar = *string++ & 0xff;
731                 if (result)
732                         *result = string;
733                 /* reset single shift state */
734                 psenc->singlegr = psenc->singlegl = -1;
735                 return wchar;
736         }
737
738         /* length error check */
739         switch (psenc->g[cur].type) {
740         case CS94MULTI:
741         case CS96MULTI:
742                 if (!isthree(psenc->g[cur].final)) {
743                         if (2 <= n
744                          && (string[0] & 0x80) == (string[1] & 0x80))
745                                 break;
746                 } else {
747                         if (3 <= n
748                          && (string[0] & 0x80) == (string[1] & 0x80)
749                          && (string[0] & 0x80) == (string[2] & 0x80))
750                                 break;
751                 }
752
753                 /* we still need to wait for more characters to come */
754                 if (result)
755                         *result = string;
756                 return (_ISO2022INVALID);
757
758         case CS94:
759         case CS96:
760                 if (1 <= n)
761                         break;
762
763                 /* we still need to wait for more characters to come */
764                 if (result)
765                         *result = string;
766                 return (_ISO2022INVALID);
767         }
768
769         /* range check */
770         switch (psenc->g[cur].type) {
771         case CS94:
772                 if (!(is94(string[0] & 0x7f)))
773                         goto asis;
774         case CS96:
775                 if (!(is96(string[0] & 0x7f)))
776                         goto asis;
777                 break;
778         case CS94MULTI:
779                 if (!(is94(string[0] & 0x7f) && is94(string[1] & 0x7f)))
780                         goto asis;
781                 break;
782         case CS96MULTI:
783                 if (!(is96(string[0] & 0x7f) && is96(string[1] & 0x7f)))
784                         goto asis;
785                 break;
786         }
787
788         /* extract the character. */
789         switch (psenc->g[cur].type) {
790         case CS94:
791                 /* special case for ASCII. */
792                 if (psenc->g[cur].final == 'B' && !psenc->g[cur].interm) {
793                         wchar = *string++;
794                         wchar &= 0x7f;
795                         break;
796                 }
797                 wchar = psenc->g[cur].final;
798                 wchar = (wchar << 8);
799                 wchar |= (psenc->g[cur].interm ? (0x80 | psenc->g[cur].interm) : 0);
800                 wchar = (wchar << 8);
801                 wchar = (wchar << 8) | (*string++ & 0x7f);
802                 break;
803         case CS96:
804                 /* special case for ISO-8859-1. */
805                 if (psenc->g[cur].final == 'A' && !psenc->g[cur].interm) {
806                         wchar = *string++;
807                         wchar &= 0x7f;
808                         wchar |= 0x80;
809                         break;
810                 }
811                 wchar = psenc->g[cur].final;
812                 wchar = (wchar << 8);
813                 wchar |= (psenc->g[cur].interm ? (0x80 | psenc->g[cur].interm) : 0);
814                 wchar = (wchar << 8);
815                 wchar = (wchar << 8) | (*string++ & 0x7f);
816                 wchar |= 0x80;
817                 break;
818         case CS94MULTI:
819         case CS96MULTI:
820                 wchar = psenc->g[cur].final;
821                 wchar = (wchar << 8);
822                 if (isthree(psenc->g[cur].final))
823                         wchar |= (*string++ & 0x7f);
824                 wchar = (wchar << 8) | (*string++ & 0x7f);
825                 wchar = (wchar << 8) | (*string++ & 0x7f);
826                 if (psenc->g[cur].type == CS96MULTI)
827                         wchar |= 0x80;
828                 break;
829         }
830
831         if (result)
832                 *result = string;
833         /* reset single shift state */
834         psenc->singlegr = psenc->singlegl = -1;
835         return wchar;
836 }
837
838
839
840 static int
841 _citrus_ISO2022_mbrtowc_priv(_ISO2022EncodingInfo * __restrict ei,
842                              wchar_t * __restrict pwc,
843                              const char ** __restrict s,
844                              size_t n, _ISO2022State * __restrict psenc,
845                              size_t * __restrict nresult)
846 {
847         wchar_t wchar;
848         const char *s0, *p, *result;
849         int c;
850         int chlenbak;
851
852         _DIAGASSERT(nresult != 0);
853         _DIAGASSERT(ei != NULL);
854         _DIAGASSERT(psenc != NULL);
855         _DIAGASSERT(s != NULL);
856
857         if (*s == NULL) {
858                 _citrus_ISO2022_init_state(ei, psenc);
859                 *nresult = _ENCODING_IS_STATE_DEPENDENT;
860                 return 0;
861         }
862         s0 = *s;
863         c = 0;
864         chlenbak = psenc->chlen;
865
866         /*
867          * if we have something in buffer, use that.
868          * otherwise, skip here
869          */
870         if (psenc->chlen < 0 || psenc->chlen > sizeof(psenc->ch)) {
871                 /* illgeal state */
872                 _citrus_ISO2022_init_state(ei, psenc);
873                 goto encoding_error;
874         }
875         if (psenc->chlen == 0)
876                 goto emptybuf;
877
878         /* buffer is not empty */
879         p = psenc->ch;
880         while (psenc->chlen < sizeof(psenc->ch) && n >= 0) {
881                 if (n > 0) {
882                         psenc->ch[psenc->chlen++] = *s0++;
883                         n--;
884                 }
885
886                 wchar = _ISO2022_sgetwchar(ei, p, psenc->chlen - (p-psenc->ch),
887                                            &result, psenc);
888                 c += result - p;
889                 if (wchar != _ISO2022INVALID) {
890                         if (psenc->chlen > c)
891                                 memmove(psenc->ch, result, psenc->chlen - c);
892                         if (psenc->chlen < c)
893                                 psenc->chlen = 0;
894                         else
895                                 psenc->chlen -= c;
896                         goto output;
897                 }
898
899                 if (n == 0) {
900                         if ((result - p) == psenc->chlen)
901                                 /* complete shift sequence. */
902                                 psenc->chlen = 0;
903                         goto restart;
904                 }
905
906                 p = result;
907         }
908
909         /* escape sequence too long? */
910         goto encoding_error;
911
912 emptybuf:
913         wchar = _ISO2022_sgetwchar(ei, s0, n, &result, psenc);
914         if (wchar != _ISO2022INVALID) {
915                 c += result - s0;
916                 psenc->chlen = 0;
917                 s0 = result;
918                 goto output;
919         }
920         if (result > s0) {
921                 c += (result - s0);
922                 n -= (result - s0);
923                 s0 = result;
924                 if (n>0)
925                         goto emptybuf;
926                 /* complete shift sequence. */
927                 goto restart;
928         }
929         n += c;
930         if (n < sizeof(psenc->ch)) {
931                 memcpy(psenc->ch, s0 - c, n);
932                 psenc->chlen = n;
933                 s0 = result;
934                 goto restart;
935         }
936
937         /* escape sequence too long? */
938
939 encoding_error:
940         psenc->chlen = 0;
941         *nresult = (size_t)-1;
942         return (EILSEQ);
943
944 output:
945         *s = s0;
946         if (pwc)
947                 *pwc = wchar;
948
949         if (!wchar)
950                 *nresult = 0;
951         else
952                 *nresult = c - chlenbak;
953
954         return (0);
955
956 restart:
957         *s = s0;
958         *nresult = (size_t)-2;
959
960         return (0);
961 }
962
963 static int
964 recommendation(_ISO2022EncodingInfo * __restrict ei,
965                _ISO2022Charset * __restrict cs)
966 {
967         int i, j;
968         _ISO2022Charset *recommend;
969
970         _DIAGASSERT(ei != NULL);
971         _DIAGASSERT(cs != NULL);
972
973         /* first, try a exact match. */
974         for (i = 0; i < 4; i++) {
975                 recommend = ei->recommend[i];
976                 for (j = 0; j < ei->recommendsize[i]; j++) {
977                         if (cs->type != recommend[j].type)
978                                 continue;
979                         if (cs->final != recommend[j].final)
980                                 continue;
981                         if (cs->interm != recommend[j].interm)
982                                 continue;
983
984                         return i;
985                 }
986         }
987
988         /* then, try a wildcard match over final char. */
989         for (i = 0; i < 4; i++) {
990                 recommend = ei->recommend[i];
991                 for (j = 0; j < ei->recommendsize[i]; j++) {
992                         if (cs->type != recommend[j].type)
993                                 continue;
994                         if (cs->final && (cs->final != recommend[j].final))
995                                 continue;
996                         if (cs->interm && (cs->interm != recommend[j].interm))
997                                 continue;
998
999                         return i;
1000                 }
1001         }
1002
1003         /* there's no recommendation. make a guess. */
1004         if (ei->maxcharset == 0) {
1005                 return 0;
1006         } else {
1007                 switch (cs->type) {
1008                 case CS94:
1009                 case CS94MULTI:
1010                         return 0;
1011                 case CS96:
1012                 case CS96MULTI:
1013                         return 1;
1014                 }
1015         }
1016         return 0;
1017 }
1018
1019 static int
1020 _ISO2022_sputwchar(_ISO2022EncodingInfo * __restrict ei, wchar_t wc,
1021                    char * __restrict string, size_t n,
1022                    char ** __restrict result,
1023                    _ISO2022State * __restrict psenc,
1024                    size_t * __restrict nresult)
1025 {
1026         int i = 0;
1027         size_t len;
1028         _ISO2022Charset cs;
1029         char *p;
1030         char tmp[MB_LEN_MAX];
1031         int target;
1032         u_char mask;
1033         int bit8;
1034
1035         _DIAGASSERT(ei != NULL);
1036         _DIAGASSERT(string != NULL);
1037         /* result may be NULL */
1038         _DIAGASSERT(psenc != NULL);
1039         _DIAGASSERT(nresult != NULL);
1040
1041         if (isc0(wc & 0xff)) {
1042                 /* go back to INIT0 or ASCII on control chars */
1043                 cs = ei->initg[0].final ? ei->initg[0] : ascii;
1044         } else if (isc1(wc & 0xff)) {
1045                 /* go back to INIT1 or ISO-8859-1 on control chars */
1046                 cs = ei->initg[1].final ? ei->initg[1] : iso88591;
1047         } else if (!(wc & ~0xff)) {
1048                 if (wc & 0x80) {
1049                         /* special treatment for ISO-8859-1 */
1050                         cs = iso88591;
1051                 } else {
1052                         /* special treatment for ASCII */
1053                         cs = ascii;
1054                 }
1055         } else {
1056                 cs.final = (wc >> 24) & 0x7f;
1057                 if ((wc >> 16) & 0x80)
1058                         cs.interm = (wc >> 16) & 0x7f;
1059                 else
1060                         cs.interm = '\0';
1061                 if (wc & 0x80)
1062                         cs.type = (wc & 0x00007f00) ? CS96MULTI : CS96;
1063                 else
1064                         cs.type = (wc & 0x00007f00) ? CS94MULTI : CS94;
1065         }
1066         target = recommendation(ei, &cs);
1067         p = tmp;
1068         bit8 = ei->flags & F_8BIT;
1069
1070         /* designate the charset onto the target plane(G0/1/2/3). */
1071         if (psenc->g[target].type == cs.type
1072          && psenc->g[target].final == cs.final
1073          && psenc->g[target].interm == cs.interm)
1074                 goto planeok;
1075
1076         *p++ = '\033';
1077         if (cs.type == CS94MULTI || cs.type == CS96MULTI)
1078                 *p++ = '$';
1079         if (target == 0 && cs.type == CS94MULTI && strchr("@AB", cs.final)
1080          && !cs.interm && !(ei->flags & F_NOOLD))
1081                 ;
1082         else if (cs.type == CS94 || cs.type == CS94MULTI)
1083                 *p++ = "()*+"[target];
1084         else
1085                 *p++ = ",-./"[target];
1086         if (cs.interm)
1087                 *p++ = cs.interm;
1088         *p++ = cs.final;
1089
1090         psenc->g[target].type = cs.type;
1091         psenc->g[target].final = cs.final;
1092         psenc->g[target].interm = cs.interm;
1093
1094 planeok:
1095         /* invoke the plane onto GL or GR. */
1096         if (psenc->gl == target)
1097                 goto sideok;
1098         if (bit8 && psenc->gr == target)
1099                 goto sideok;
1100
1101         if (target == 0 && (ei->flags & F_LS0)) {
1102                 *p++ = '\017';
1103                 psenc->gl = 0;
1104         } else if (target == 1 && (ei->flags & F_LS1)) {
1105                 *p++ = '\016';
1106                 psenc->gl = 1;
1107         } else if (target == 2 && (ei->flags & F_LS2)) {
1108                 *p++ = '\033';
1109                 *p++ = 'n';
1110                 psenc->gl = 2;
1111         } else if (target == 3 && (ei->flags & F_LS3)) {
1112                 *p++ = '\033';
1113                 *p++ = 'o';
1114                 psenc->gl = 3;
1115         } else if (bit8 && target == 1 && (ei->flags & F_LS1R)) {
1116                 *p++ = '\033';
1117                 *p++ = '~';
1118                 psenc->gr = 1;
1119         } else if (bit8 && target == 2 && (ei->flags & F_LS2R)) {
1120                 *p++ = '\033';
1121                 /*{*/
1122                 *p++ = '}';
1123                 psenc->gr = 2;
1124         } else if (bit8 && target == 3 && (ei->flags & F_LS3R)) {
1125                 *p++ = '\033';
1126                 *p++ = '|';
1127                 psenc->gr = 3;
1128         } else if (target == 2 && (ei->flags & F_SS2)) {
1129                 *p++ = '\033';
1130                 *p++ = 'N';
1131                 psenc->singlegl = 2;
1132         } else if (target == 3 && (ei->flags & F_SS3)) {
1133                 *p++ = '\033';
1134                 *p++ = 'O';
1135                 psenc->singlegl = 3;
1136         } else if (bit8 && target == 2 && (ei->flags & F_SS2R)) {
1137                 *p++ = '\216';
1138                 *p++ = 'N';
1139                 psenc->singlegl = psenc->singlegr = 2;
1140         } else if (bit8 && target == 3 && (ei->flags & F_SS3R)) {
1141                 *p++ = '\217';
1142                 *p++ = 'O';
1143                 psenc->singlegl = psenc->singlegr = 3;
1144         } else
1145                 goto ilseq;
1146
1147 sideok:
1148         if (psenc->singlegl == target)
1149                 mask = 0x00;
1150         else if (psenc->singlegr == target)
1151                 mask = 0x80;
1152         else if (psenc->gl == target)
1153                 mask = 0x00;
1154         else if ((ei->flags & F_8BIT) && psenc->gr == target)
1155                 mask = 0x80;
1156         else
1157                 goto ilseq;
1158
1159         switch (cs.type) {
1160         case CS94:
1161         case CS96:
1162                 i = 1;
1163                 break;
1164         case CS94MULTI:
1165         case CS96MULTI:
1166                 i = !iscntl(wc & 0xff) ?
1167                     (isthree(cs.final) ? 3 : 2) : 1;
1168                 break;
1169         }
1170         while (i-- > 0)
1171                 *p++ = ((wc >> (i << 3)) & 0x7f) | mask;
1172
1173         /* reset single shift state */
1174         psenc->singlegl = psenc->singlegr = -1;
1175
1176         len = (size_t)(p - tmp);
1177         if (n < len) {
1178                 if (result)
1179                         *result = (char *)0;
1180                 *nresult = (size_t)-1;
1181                 return E2BIG;
1182         }
1183         if (result)
1184                 *result = string + len;
1185         memcpy(string, tmp, len);
1186         *nresult = len;
1187
1188         return 0;
1189
1190 ilseq:
1191         *nresult = (size_t)-1;
1192         return EILSEQ;
1193 }
1194
1195 static int
1196 _citrus_ISO2022_put_state_reset(_ISO2022EncodingInfo * __restrict ei,
1197                                 char * __restrict s, size_t n,
1198                                 _ISO2022State * __restrict psenc,
1199                                 size_t * __restrict nresult)
1200 {
1201         char buf[MB_LEN_MAX];
1202         char *result;
1203         int ret;
1204         size_t len;
1205
1206         _DIAGASSERT(ei != NULL);
1207         _DIAGASSERT(nresult != 0);
1208         _DIAGASSERT(s != NULL);
1209
1210         /* XXX state will be modified after this operation... */
1211         ret = _ISO2022_sputwchar(ei, L'\0', buf, sizeof(buf), &result, psenc,
1212             &len);
1213         if (ret) {
1214                 *nresult = len;
1215                 return ret;
1216         }
1217
1218         if (sizeof(buf) < len || n < len-1) {
1219                 /* XXX should recover state? */
1220                 *nresult = (size_t)-1;
1221                 return E2BIG;
1222         }
1223
1224         memcpy(s, buf, len-1);
1225         *nresult = len-1;
1226         return (0);
1227 }
1228
1229 static int
1230 _citrus_ISO2022_wcrtomb_priv(_ISO2022EncodingInfo * __restrict ei,
1231                              char * __restrict s, size_t n, wchar_t wc,
1232                              _ISO2022State * __restrict psenc,
1233                              size_t * __restrict nresult)
1234 {
1235         char buf[MB_LEN_MAX];
1236         char *result;
1237         int ret;
1238         size_t len;
1239
1240         _DIAGASSERT(ei != NULL);
1241         _DIAGASSERT(s != NULL);
1242         _DIAGASSERT(psenc != NULL);
1243         _DIAGASSERT(nresult != 0);
1244
1245         /* XXX state will be modified after this operation... */
1246         ret = _ISO2022_sputwchar(ei, wc, buf, sizeof(buf), &result, psenc,
1247             &len);
1248         if (ret) {
1249                 *nresult = len;
1250                 return ret;
1251         }
1252
1253         if (sizeof(buf) < len || n < len) {
1254                 /* XXX should recover state? */
1255                 *nresult = (size_t)-1;
1256                 return E2BIG;
1257         }
1258
1259         memcpy(s, buf, len);
1260         *nresult = len;
1261         return (0);
1262 }
1263
1264 static __inline int
1265 /*ARGSUSED*/
1266 _citrus_ISO2022_stdenc_wctocs(_ISO2022EncodingInfo * __restrict ei,
1267                               _csid_t * __restrict csid,
1268                               _index_t * __restrict idx, wchar_t wc)
1269 {
1270         wchar_t m, nm;
1271
1272         _DIAGASSERT(csid != NULL && idx != NULL);
1273
1274         m = wc & 0x7FFF8080;
1275         nm = wc & 0x007F7F7F;
1276         if (m & 0x00800000) {
1277                 nm &= 0x00007F7F;
1278         } else {
1279                 m &= 0x7F008080;
1280         }
1281         if (nm & 0x007F0000) {
1282                 /* ^3 mark */
1283                 m |= 0x007F0000;
1284         } else if (nm & 0x00007F00) {
1285                 /* ^2 mark */
1286                 m |= 0x00007F00;
1287         }
1288         *csid = (_csid_t)m;
1289         *idx  = (_index_t)nm;
1290
1291         return (0);
1292 }
1293
1294 static __inline int
1295 /*ARGSUSED*/
1296 _citrus_ISO2022_stdenc_cstowc(_ISO2022EncodingInfo * __restrict ei,
1297                               wchar_t * __restrict wc,
1298                               _csid_t csid, _index_t idx)
1299 {
1300
1301         _DIAGASSERT(ei != NULL && wc != NULL);
1302
1303         *wc = (wchar_t)(csid & 0x7F808080) | (wchar_t)idx;
1304
1305         return (0);
1306 }
1307
1308 static __inline int
1309 /*ARGSUSED*/
1310 _citrus_ISO2022_stdenc_get_state_desc_generic(_ISO2022EncodingInfo * __restrict ei,
1311                                               _ISO2022State * __restrict psenc,
1312                                               int * __restrict rstate)
1313 {
1314
1315         if (psenc->chlen == 0) {
1316                 /* XXX: it should distinguish initial and stable. */
1317                 *rstate = _STDENC_SDGEN_STABLE;
1318         } else {
1319                 if (psenc->ch[0] == '\033')
1320                         *rstate = _STDENC_SDGEN_INCOMPLETE_SHIFT;
1321                 else
1322                         *rstate = _STDENC_SDGEN_INCOMPLETE_CHAR;
1323         }
1324
1325         return 0;
1326 }
1327
1328 /* ----------------------------------------------------------------------
1329  * public interface for ctype
1330  */
1331
1332 _CITRUS_CTYPE_DECLS(ISO2022);
1333 _CITRUS_CTYPE_DEF_OPS(ISO2022);
1334
1335 #include "citrus_ctype_template.h"
1336
1337 /* ----------------------------------------------------------------------
1338  * public interface for stdenc
1339  */
1340
1341 _CITRUS_STDENC_DECLS(ISO2022);
1342 _CITRUS_STDENC_DEF_OPS(ISO2022);
1343
1344 #include "citrus_stdenc_template.h"