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