]> gitweb.fperrin.net Git - Dictionary.git/blob - jars/icu4j-4_8_1_1/main/classes/charset/src/com/ibm/icu/charset/CharsetLMBCS.java
Added flags.
[Dictionary.git] / jars / icu4j-4_8_1_1 / main / classes / charset / src / com / ibm / icu / charset / CharsetLMBCS.java
1 /*
2  *******************************************************************************
3  * Copyright (C) 2008-2010, International Business Machines Corporation and    *
4  * others. All Rights Reserved.                                                *
5  *******************************************************************************
6  */
7 package com.ibm.icu.charset;
8
9 import java.nio.ByteBuffer;
10 import java.nio.CharBuffer;
11 import java.nio.IntBuffer;
12 import java.nio.charset.CharsetDecoder;
13 import java.nio.charset.CharsetEncoder;
14 import java.nio.charset.CoderResult;
15
16 import com.ibm.icu.charset.CharsetMBCS.CharsetDecoderMBCS;
17 import com.ibm.icu.charset.CharsetMBCS.CharsetEncoderMBCS;
18 import com.ibm.icu.text.UnicodeSet;
19 import com.ibm.icu.util.ULocale;
20 /**
21  * @author Michael Ow
22  *
23  */
24
25 /*
26  * LMBCS
27  * 
28  * (Lotus Multi-Byte Character Set)
29  * 
30  * LMBS was invented in the alte 1980's and is primarily used in Lotus Notes
31  * databases and in Lotus 1-2-3 files. Programmers who work with the APIs
32  * into these products will sometimes need to deal with strings in this format.
33  * 
34  * The code in this file provides an implementation for an ICU converter of
35  * LMBCS to and from Unicode.
36  * 
37  * Since the LMBCS character set is only sparsely documented in existing
38  * printed or online material, we have added extensive annotation to this
39  * file to serve as a guide to understanding LMBCS.
40  * 
41  * LMBCS was originally designed with these four sometimes-competing design goals:
42  * -Provide encodings for characters in 12 existing national standards
43  *  (plus a few other characters)
44  * -Minimal memory footprint
45  * -Maximal speed of conversion into the existing national character sets
46  * -No need to track a changing state as you interpret a string.
47  * 
48  * All of the national character sets LMBCS was trying to encode are 'ANSI'
49  * based, in that the bytes from 0x20 - 0x7F are almost exactly the
50  * same common Latin unaccented characters and symbols in all character sets.
51  * 
52  * So, in order to help meet the speed & memory design goals, the common ANSI
53  * bytes from 0x20-0x7F are represented by the same single-byte values in LMBCS.
54  */
55 class CharsetLMBCS extends CharsetICU {
56     /*
57      * The general LMBCS code unit is from 1-3 bytes. We can describe the 3 bytes as
58      * follows:
59      * [G] D1 [D2]
60      * That is, a sometimes-optional 'group' byte, followed by 1 and sometimes 2
61      * data bytes. The maximum size of a LMBCS character is 3 bytes:
62      */
63     private static final short ULMBCS_CHARSIZE_MAX = 3;
64     /*
65      * The single-byte values from 0x20 to 0x7F are examples of single D1 bytes.
66      * We often have to figure out if byte values are below or above this, so we
67      * use the ANSI nomenclature 'C0' and 'C1' to refer to the range of control
68      * characters just above & below the common lower-ANSI range.
69      */
70     private static final short ULMBCS_C0END    = 0x1F;
71     private static final short ULMBCS_C1START  = 0x80;
72     /*
73      * Most of the values less than 0x20 are reserved in LMBCS to announce
74      * which national character standard is being used for the 'D' bytes.
75      * In the comments we show that common name and the IBM character-set ID
76      * for these character-set announcers:
77      */
78     private static final short ULMBCS_GRP_L1   = 0x01; /* Latin-1      :ibm-850    */
79     private static final short ULMBCS_GRP_GR   = 0x02; /* Greek        :ibm-851    */
80     private static final short ULMBCS_GRP_HE   = 0x03; /* Hebrew       :ibm-1255   */
81     private static final short ULMBCS_GRP_AR   = 0x04; /* Arabic       :ibm-1256   */
82     private static final short ULMBCS_GRP_RU   = 0x05; /* Cyrillic     :ibm-1251   */
83     private static final short ULMBCS_GRP_L2   = 0x06; /* Latin-2      :ibm-852    */
84     private static final short ULMBCS_GRP_TR   = 0x08; /* Turkish      :ibm-1254   */
85     private static final short ULMBCS_GRP_TH   = 0x0B; /* Thai         :ibm-874    */
86     private static final short ULMBCS_GRP_JA   = 0x10; /* Japanese     :ibm-943    */
87     private static final short ULMBCS_GRP_KO   = 0x11; /* Korean       :ibm-1261   */
88     private static final short ULMBCS_GRP_TW   = 0x12; /* Chinese SC   :ibm-950    */
89     private static final short ULMBCS_GRP_CN   = 0x13; /* Chinese TC   :ibm-1386   */
90     /* 
91      * So, the beginnning of understanding LMBCS is that IF the first byte of a LMBCS
92      * character is one of those 12 values, you can interpret the remaining bytes of 
93      * that character as coming from one of those character sets. Since the lower
94      * ANSI bytes already are represented in singl bytes, using one of the chracter
95      * set announcers is used to announce a character that starts with a byte of
96      * 0x80 or greater.
97      * 
98      * The character sets are arranged so that the single byte sets all appear
99      * before the multi-byte character sets. When we need to tell whether a
100      * group byte is for a single byte char set or not we use this definition:
101      */
102     private static final short ULMBCS_DOUBLEOPTGROUP_START = 0x10;
103     /*
104      * However, to fully understand LMBCS, you must also understand a series of
105      * exceptions & optimizations made in service of the design goals.
106      * 
107      * First, those of you who are character set mavens may have noticed that
108      * the 'double-byte' character sets are actually multi-byte chracter sets
109      * that can have 1 or two bytes, even in upper-ascii range. To force
110      * each group byte to introduce a fixed-width encoding (to make it faster to
111      * count characters), we use a convention of doubling up on the group byte
112      * to introduce any single-byte character > 0x80 in an otherwise double-byte
113      * character set. So, for example, the LMBCS sequence x10 x10 xAE is the
114      * same as '0xAE' in the Japanese code page 943.
115      * 
116      * Next, you will notice that the list of group bytes has some gaps.
117      * These are used in various ways.
118      * 
119      * We reserve a few special single byte values for common control
120      * characters. These are in the same place as their ANSI equivalents for speed.
121      */
122     private static final short ULMBCS_HT   = 0x09; /* Fixed control-char - Horizontal Tab */
123     private static final short ULMBCS_LF   = 0x0A; /* Fixed control-char - Line Feed */
124     private static final short ULMBCS_CR   = 0x0D; /* Fixed control-char - Carriage Return */
125     /*
126      * Then, 1-2-3 reserved a special single-byte character to put at the
127      * beginning of internal 'system' range names:
128      */
129     private static final short ULMBCS_123SYSTEMRANGE   = 0x19;
130     /*
131      * Then we needed a place to put all the other ansi control characters
132      * that must be moved to different values because LMBCS reserves those
133      * values for other purposes. To represent the control characters, we start
134      * with a first byte of 0x0F & add the control character value as the
135      * second byte.
136      */
137     private static final short ULMBCS_GRP_CTRL = 0x0F;
138     /*
139      * For the C0 controls (less than 0x20), we add 0x20 to preserve the
140      * useful doctrine that any byte less than 0x20 in a LMBCS char must be
141      * the first byte of a character:
142      */
143     private static final short ULMBCS_CTRLOFFSET   = 0x20;
144     /*
145      * Where to put the characters that aren't part of any of the 12 national
146      * character sets? The first thing that was done, in the earlier years of
147      * LMBCS, was to use up the spaces of the form
148      *  [G] D1,
149      * where 'G' was one of the single-byte character groups, and
150      * D1 was less than 0x80. These sequences are gathered together
151      * into a Lotus-invented doublebyte character set to represent a
152      * lot of stray values. Internally, in this implementation, we track this
153      * as group '0', as a place to tuck this exceptions list.
154      */
155     private static final short ULMBCS_GRP_EXCEPT   = 0x00;
156     /*
157      * Finally, as the durability and usefulness of UNICODE became clear,
158      * LOTUS added a new group 0x14 to hold Unicode values not otherwise
159      * represented in LMBCS:
160      */
161     private static final short ULMBCS_GRP_UNICODE  = 0x14;
162     /*
163      * The two bytes appearing after a 0x14 are interpreted as UTF-16 BE
164      * (Big Endian) characters. The exception comes when UTF16 
165      * representation would have a zero as the second byte. In that case,
166      * 'F6' is used in its place, and the bytes are swapped. (This prevents
167      * LMBCS from encoding any Unicode values of the form U+F6xx, but that's OK:
168      * 0xF6xx is in the middle of the Private Use Area.)
169      */
170     private static char ULMBCS_UNICOMPATZERO    = 0x00F6;
171     /*
172      * It is also useful in our code to have a constant for the size of
173      * a LMBCS char that holds a literal Unicode value.
174      */
175     private static final short ULMBCS_UNICODE_SIZE = 3;
176     /*
177      * To squish the LMBCS representation down even further, and to make
178      * translations even faster, sometimes the optimization group byte can be dropped
179      * from a LMBCS character. This is decided on a process-by-process basis. The
180      * group byte that is dropped is called the 'optimization group.'
181      * 
182      * For Notes, the optimization group is always 0x1.
183      */
184     //private static final short ULMBCS_DEFAULTOPTGROUP  = 0x01;
185     /* For 1-2-3 files, the optimization group is stored in the header of the 1-2-3
186      * file.
187      * In any case, when using ICU, you either pass in the
188      * optimization group as part of the name of the converter (LMBCS-1, LMBCS-2,
189      * etc.). Using plain 'LMBCS' as the name of the converter will give you
190      * LMBCS-1.
191      */
192     
193     /* Implementation strategy */
194     /* 
195      * Because of the extensive use of other character sets, the LMBCS converter
196      * keeps a mapping between optimization groups and IBM character sets, so that
197      * ICU converters can be created and used as needed.
198      * 
199      * As you can see, even though any byte below 0x20 could be an optimization
200      * byte, only those at 0x13 or below can map to an actual converter. To limit
201      * some loops and searches, we define a value for that last group converter:
202      */
203     private static final short ULMBCS_GRP_LAST = 0x13; /* last LMBCS group that has a converter */
204     
205     private static final String[] OptGroupByteToCPName = {
206         /* 0x0000 */ "lmb-excp", /* internal home for the LOTUS exceptions list */
207         /* 0x0001 */ "ibm-850",
208         /* 0x0002 */ "ibm-851",
209         /* 0x0003 */ "windows-1255",
210         /* 0x0004 */ "windows-1256",
211         /* 0x0005 */ "windows-1251",
212         /* 0x0006 */ "ibm-852",
213         /* 0x0007 */ null,      /* Unused */
214         /* 0x0008 */ "windows-1254",
215         /* 0x0009 */ null,      /* Control char HT */
216         /* 0x000A */ null,      /* Control char LF */
217         /* 0x000B */ "windows-874",
218         /* 0x000C */ null,      /* Unused */
219         /* 0x000D */ null,      /* Control char CR */
220         /* 0x000E */ null,      /* Unused */
221         /* 0x000F */ null,      /* Control chars: 0x0F20 + C0/C1 character: algorithmic */
222         /* 0x0010 */ "windows-932",
223         /* 0x0011 */ "windows-949",
224         /* 0x0012 */ "windows-950",
225         /* 0x0013 */ "windows-936",
226         /* The rest are null, including the 0x0014 Unicode compatibility region
227          * and 0x0019, the 1-2-3 system range control char */
228         /* 0x0014 */ null 
229     };
230     
231     /* That's approximately all the data that's needed for translating
232      * LMBCS to Unicode.
233      * 
234      * However, to translate Unicode to LMBCS, we need some more support.
235      * 
236      * That's because there are often more than one possible mappings from a Unicode
237      * code point back into LMBCS. The first thing we do is look up into a table
238      * to figure out if there are more than one possible mapplings. This table,
239      * arranged by Unicode values (including ranges) either lists which group
240      * to use, or says that it could go into one or more of the SBCS sets, or
241      * into one or more of the DBCS sets. (If the character exists in both DBCS &
242      * SBCS, the table will place it in the SBCS sets, to make the LMBCS code point
243      * length as small as possible. Here's the two special markers we use to indicate
244      * ambiguous mappings:
245      */
246     private static final short ULMBCS_AMBIGUOUS_SBCS   = 0x80; /* could fit in more than one
247                                                            LMBCS sbcs native encoding
248                                                            (example: most accented latin) */
249     private static final short ULMBCS_AMBIGUOUS_MBCS   = 0x81; /* could fit in more than one
250                                                            LMBCS mbcs native encoding
251                                                            (example: Unihan) */
252     private static final short ULMBCS_AMBIGUOUS_ALL    = 0x82;
253     
254     /* And here's a simple way to see if a group falls in an appropriate range */
255     private boolean ULMBCS_AMBIGUOUS_MATCH(short agroup, short xgroup) {
256         return (((agroup == ULMBCS_AMBIGUOUS_SBCS) &&
257                  (xgroup < ULMBCS_DOUBLEOPTGROUP_START)) ||
258                 ((agroup == ULMBCS_AMBIGUOUS_MBCS) &&
259                  (xgroup >= ULMBCS_DOUBLEOPTGROUP_START)) ||
260                  ((agroup) == ULMBCS_AMBIGUOUS_ALL));
261     }
262     
263     /* The table & some code to use it: */
264     private static class _UniLMBCSGrpMap {
265         int uniStartRange;
266         int uniEndRange;
267         short GrpType;
268         _UniLMBCSGrpMap(int uniStartRange, int uniEndRange, short GrpType) {
269             this.uniStartRange  = uniStartRange;
270             this.uniEndRange    = uniEndRange;
271             this.GrpType        = GrpType;
272         }
273     }
274     
275     private static final _UniLMBCSGrpMap[] UniLMBCSGrpMap = {
276         new _UniLMBCSGrpMap(0x0001, 0x001F, ULMBCS_GRP_CTRL),
277         new _UniLMBCSGrpMap(0x0080, 0x009F, ULMBCS_GRP_CTRL),
278         new _UniLMBCSGrpMap(0x00A0, 0x00A6, ULMBCS_AMBIGUOUS_SBCS),
279         new _UniLMBCSGrpMap(0x00A7, 0x00A8, ULMBCS_AMBIGUOUS_ALL),
280         new _UniLMBCSGrpMap(0x00A9, 0x00AF, ULMBCS_AMBIGUOUS_SBCS),
281         new _UniLMBCSGrpMap(0x00B0, 0x00B1, ULMBCS_AMBIGUOUS_ALL),
282         new _UniLMBCSGrpMap(0x00B2, 0x00B3, ULMBCS_AMBIGUOUS_SBCS),
283         new _UniLMBCSGrpMap(0x00B4, 0x00B4, ULMBCS_AMBIGUOUS_ALL),
284         new _UniLMBCSGrpMap(0x00B5, 0x00B5, ULMBCS_AMBIGUOUS_SBCS),
285         new _UniLMBCSGrpMap(0x00B6, 0x00B6, ULMBCS_AMBIGUOUS_ALL),
286         new _UniLMBCSGrpMap(0x00B7, 0x00D6, ULMBCS_AMBIGUOUS_SBCS),
287         new _UniLMBCSGrpMap(0x00D7, 0x00D7, ULMBCS_AMBIGUOUS_ALL),
288         new _UniLMBCSGrpMap(0x00D8, 0x00F6, ULMBCS_AMBIGUOUS_SBCS),
289         new _UniLMBCSGrpMap(0x00F7, 0x00F7, ULMBCS_AMBIGUOUS_ALL),
290         new _UniLMBCSGrpMap(0x00F8, 0x01CD, ULMBCS_AMBIGUOUS_SBCS),
291         new _UniLMBCSGrpMap(0x01CE, 0x01CE, ULMBCS_GRP_TW ),
292         new _UniLMBCSGrpMap(0x01CF, 0x02B9, ULMBCS_AMBIGUOUS_SBCS),
293         new _UniLMBCSGrpMap(0x02BA, 0x02BA, ULMBCS_GRP_CN),
294         new _UniLMBCSGrpMap(0x02BC, 0x02C8, ULMBCS_AMBIGUOUS_SBCS),
295         new _UniLMBCSGrpMap(0x02C9, 0x02D0, ULMBCS_AMBIGUOUS_MBCS),
296         new _UniLMBCSGrpMap(0x02D8, 0x02DD, ULMBCS_AMBIGUOUS_SBCS),
297         new _UniLMBCSGrpMap(0x0384, 0x0390, ULMBCS_AMBIGUOUS_SBCS),
298         new _UniLMBCSGrpMap(0x0391, 0x03A9, ULMBCS_AMBIGUOUS_ALL),
299         new _UniLMBCSGrpMap(0x03AA, 0x03B0, ULMBCS_AMBIGUOUS_SBCS),
300         new _UniLMBCSGrpMap(0x03B1, 0x03C9, ULMBCS_AMBIGUOUS_ALL),
301         new _UniLMBCSGrpMap(0x03CA, 0x03CE, ULMBCS_AMBIGUOUS_SBCS),
302         new _UniLMBCSGrpMap(0x0400, 0x0400, ULMBCS_GRP_RU),
303         new _UniLMBCSGrpMap(0x0401, 0x0401, ULMBCS_AMBIGUOUS_ALL),
304         new _UniLMBCSGrpMap(0x0402, 0x040F, ULMBCS_GRP_RU),
305         new _UniLMBCSGrpMap(0x0410, 0x0431, ULMBCS_AMBIGUOUS_ALL),
306         new _UniLMBCSGrpMap(0x0432, 0x044E, ULMBCS_GRP_RU),
307         new _UniLMBCSGrpMap(0x044F, 0x044F, ULMBCS_AMBIGUOUS_ALL),
308         new _UniLMBCSGrpMap(0x0450, 0x0491, ULMBCS_GRP_RU),
309         new _UniLMBCSGrpMap(0x05B0, 0x05F2, ULMBCS_GRP_HE),
310         new _UniLMBCSGrpMap(0x060C, 0x06AF, ULMBCS_GRP_AR),
311         new _UniLMBCSGrpMap(0x0E01, 0x0E5B, ULMBCS_GRP_TH),
312         new _UniLMBCSGrpMap(0x200C, 0x200F, ULMBCS_AMBIGUOUS_SBCS),
313         new _UniLMBCSGrpMap(0x2010, 0x2010, ULMBCS_AMBIGUOUS_MBCS),
314         new _UniLMBCSGrpMap(0x2013, 0x2014, ULMBCS_AMBIGUOUS_SBCS),
315         new _UniLMBCSGrpMap(0x2015, 0x2015, ULMBCS_AMBIGUOUS_MBCS),
316         new _UniLMBCSGrpMap(0x2016, 0x2016, ULMBCS_AMBIGUOUS_MBCS),
317         new _UniLMBCSGrpMap(0x2017, 0x2017, ULMBCS_AMBIGUOUS_SBCS),
318         new _UniLMBCSGrpMap(0x2018, 0x2019, ULMBCS_AMBIGUOUS_ALL),
319         new _UniLMBCSGrpMap(0x201A, 0x201B, ULMBCS_AMBIGUOUS_SBCS),
320         new _UniLMBCSGrpMap(0x201C, 0x201D, ULMBCS_AMBIGUOUS_ALL),
321         new _UniLMBCSGrpMap(0x201E, 0x201F, ULMBCS_AMBIGUOUS_SBCS),
322         new _UniLMBCSGrpMap(0x2020, 0x2021, ULMBCS_AMBIGUOUS_ALL),
323         new _UniLMBCSGrpMap(0x2022, 0x2024, ULMBCS_AMBIGUOUS_SBCS),
324         new _UniLMBCSGrpMap(0x2025, 0x2025, ULMBCS_AMBIGUOUS_MBCS),
325         new _UniLMBCSGrpMap(0x2026, 0x2026, ULMBCS_AMBIGUOUS_ALL),
326         new _UniLMBCSGrpMap(0x2027, 0x2027, ULMBCS_GRP_TW),
327         new _UniLMBCSGrpMap(0x2030, 0x2030, ULMBCS_AMBIGUOUS_ALL),
328         new _UniLMBCSGrpMap(0x2031, 0x2031, ULMBCS_AMBIGUOUS_SBCS),
329         new _UniLMBCSGrpMap(0x2032, 0x2033, ULMBCS_AMBIGUOUS_MBCS),
330         new _UniLMBCSGrpMap(0x2035, 0x2035, ULMBCS_AMBIGUOUS_MBCS),
331         new _UniLMBCSGrpMap(0x2039, 0x203A, ULMBCS_AMBIGUOUS_SBCS),
332         new _UniLMBCSGrpMap(0x203B, 0x203B, ULMBCS_AMBIGUOUS_MBCS),
333         new _UniLMBCSGrpMap(0x203C, 0x203C, ULMBCS_GRP_EXCEPT),
334         new _UniLMBCSGrpMap(0x2074, 0x2074, ULMBCS_GRP_KO),
335         new _UniLMBCSGrpMap(0x207F, 0x207F, ULMBCS_GRP_EXCEPT),
336         new _UniLMBCSGrpMap(0x2081, 0x2084, ULMBCS_GRP_KO),
337         new _UniLMBCSGrpMap(0x20A4, 0x20AC, ULMBCS_AMBIGUOUS_SBCS),
338         new _UniLMBCSGrpMap(0x2103, 0x2109, ULMBCS_AMBIGUOUS_MBCS),
339         new _UniLMBCSGrpMap(0x2111, 0x2120, ULMBCS_AMBIGUOUS_SBCS),
340         /*zhujin: upgrade, for regressiont test, spr HKIA4YHTSU*/
341         new _UniLMBCSGrpMap(0x2121, 0x2121, ULMBCS_AMBIGUOUS_MBCS),
342         new _UniLMBCSGrpMap(0x2122, 0x2126, ULMBCS_AMBIGUOUS_SBCS),
343         new _UniLMBCSGrpMap(0x212B, 0x212B, ULMBCS_AMBIGUOUS_MBCS),
344         new _UniLMBCSGrpMap(0x2135, 0x2135, ULMBCS_AMBIGUOUS_SBCS),
345         new _UniLMBCSGrpMap(0x2153, 0x2154, ULMBCS_GRP_KO),
346         new _UniLMBCSGrpMap(0x215B, 0x215E, ULMBCS_GRP_EXCEPT),
347         new _UniLMBCSGrpMap(0x2160, 0x2179, ULMBCS_AMBIGUOUS_MBCS),
348         new _UniLMBCSGrpMap(0x2190, 0x2193, ULMBCS_AMBIGUOUS_ALL),
349         new _UniLMBCSGrpMap(0x2194, 0x2195, ULMBCS_GRP_EXCEPT),
350         new _UniLMBCSGrpMap(0x2196, 0x2199, ULMBCS_AMBIGUOUS_MBCS),
351         new _UniLMBCSGrpMap(0x21A8, 0x21A8, ULMBCS_GRP_EXCEPT),
352         new _UniLMBCSGrpMap(0x21B8, 0x21B9, ULMBCS_GRP_CN),
353         new _UniLMBCSGrpMap(0x21D0, 0x21D1, ULMBCS_GRP_EXCEPT),
354         new _UniLMBCSGrpMap(0x21D2, 0x21D2, ULMBCS_AMBIGUOUS_MBCS),
355         new _UniLMBCSGrpMap(0x21D3, 0x21D3, ULMBCS_GRP_EXCEPT),
356         new _UniLMBCSGrpMap(0x21D4, 0x21D4, ULMBCS_AMBIGUOUS_MBCS),
357         new _UniLMBCSGrpMap(0x21D5, 0x21D5, ULMBCS_GRP_EXCEPT),
358         new _UniLMBCSGrpMap(0x21E7, 0x21E7, ULMBCS_GRP_CN),
359         new _UniLMBCSGrpMap(0x2200, 0x2200, ULMBCS_AMBIGUOUS_MBCS),
360         new _UniLMBCSGrpMap(0x2201, 0x2201, ULMBCS_GRP_EXCEPT),
361         new _UniLMBCSGrpMap(0x2202, 0x2202, ULMBCS_AMBIGUOUS_MBCS),
362         new _UniLMBCSGrpMap(0x2203, 0x2203, ULMBCS_AMBIGUOUS_MBCS),
363         new _UniLMBCSGrpMap(0x2204, 0x2206, ULMBCS_GRP_EXCEPT),
364         new _UniLMBCSGrpMap(0x2207, 0x2208, ULMBCS_AMBIGUOUS_MBCS),
365         new _UniLMBCSGrpMap(0x2209, 0x220A, ULMBCS_GRP_EXCEPT),
366         new _UniLMBCSGrpMap(0x220B, 0x220B, ULMBCS_AMBIGUOUS_MBCS),
367         new _UniLMBCSGrpMap(0x220F, 0x2215, ULMBCS_AMBIGUOUS_MBCS),
368         new _UniLMBCSGrpMap(0x2219, 0x2219, ULMBCS_GRP_EXCEPT),
369         new _UniLMBCSGrpMap(0x221A, 0x221A, ULMBCS_AMBIGUOUS_MBCS),
370         new _UniLMBCSGrpMap(0x221B, 0x221C, ULMBCS_GRP_EXCEPT),
371         new _UniLMBCSGrpMap(0x221D, 0x221E, ULMBCS_AMBIGUOUS_MBCS),
372         new _UniLMBCSGrpMap(0x221F, 0x221F, ULMBCS_GRP_EXCEPT),
373         new _UniLMBCSGrpMap(0x2220, 0x2220, ULMBCS_AMBIGUOUS_MBCS),
374         new _UniLMBCSGrpMap(0x2223, 0x222A, ULMBCS_AMBIGUOUS_MBCS),
375         new _UniLMBCSGrpMap(0x222B, 0x223D, ULMBCS_AMBIGUOUS_MBCS),
376         new _UniLMBCSGrpMap(0x2245, 0x2248, ULMBCS_GRP_EXCEPT),
377         new _UniLMBCSGrpMap(0x224C, 0x224C, ULMBCS_GRP_TW),
378         new _UniLMBCSGrpMap(0x2252, 0x2252, ULMBCS_AMBIGUOUS_MBCS),
379         new _UniLMBCSGrpMap(0x2260, 0x2261, ULMBCS_AMBIGUOUS_MBCS),
380         new _UniLMBCSGrpMap(0x2262, 0x2265, ULMBCS_GRP_EXCEPT),
381         new _UniLMBCSGrpMap(0x2266, 0x226F, ULMBCS_AMBIGUOUS_MBCS),
382         new _UniLMBCSGrpMap(0x2282, 0x2283, ULMBCS_AMBIGUOUS_MBCS),
383         new _UniLMBCSGrpMap(0x2284, 0x2285, ULMBCS_GRP_EXCEPT),
384         new _UniLMBCSGrpMap(0x2286, 0x2287, ULMBCS_AMBIGUOUS_MBCS),
385         new _UniLMBCSGrpMap(0x2288, 0x2297, ULMBCS_GRP_EXCEPT),
386         new _UniLMBCSGrpMap(0x2299, 0x22BF, ULMBCS_AMBIGUOUS_MBCS),
387         new _UniLMBCSGrpMap(0x22C0, 0x22C0, ULMBCS_GRP_EXCEPT),
388         new _UniLMBCSGrpMap(0x2310, 0x2310, ULMBCS_GRP_EXCEPT),
389         new _UniLMBCSGrpMap(0x2312, 0x2312, ULMBCS_AMBIGUOUS_MBCS),
390         new _UniLMBCSGrpMap(0x2318, 0x2321, ULMBCS_GRP_EXCEPT),
391         new _UniLMBCSGrpMap(0x2318, 0x2321, ULMBCS_GRP_CN),
392         new _UniLMBCSGrpMap(0x2460, 0x24E9, ULMBCS_AMBIGUOUS_MBCS),
393         new _UniLMBCSGrpMap(0x2500, 0x2500, ULMBCS_AMBIGUOUS_SBCS),
394         new _UniLMBCSGrpMap(0x2501, 0x2501, ULMBCS_AMBIGUOUS_MBCS),
395         new _UniLMBCSGrpMap(0x2502, 0x2502, ULMBCS_AMBIGUOUS_ALL),
396         new _UniLMBCSGrpMap(0x2503, 0x2503, ULMBCS_AMBIGUOUS_MBCS),
397         new _UniLMBCSGrpMap(0x2504, 0x2505, ULMBCS_GRP_TW),
398         new _UniLMBCSGrpMap(0x2506, 0x2665, ULMBCS_AMBIGUOUS_ALL),
399         new _UniLMBCSGrpMap(0x2666, 0x2666, ULMBCS_GRP_EXCEPT),
400         new _UniLMBCSGrpMap(0x2667, 0x2669, ULMBCS_AMBIGUOUS_SBCS),
401         new _UniLMBCSGrpMap(0x266A, 0x266A, ULMBCS_AMBIGUOUS_ALL),
402         new _UniLMBCSGrpMap(0x266B, 0x266C, ULMBCS_AMBIGUOUS_SBCS),
403         new _UniLMBCSGrpMap(0x266D, 0x266D, ULMBCS_AMBIGUOUS_MBCS),
404         new _UniLMBCSGrpMap(0x266E, 0x266E, ULMBCS_AMBIGUOUS_SBCS),
405         new _UniLMBCSGrpMap(0x266F, 0x266F, ULMBCS_GRP_JA),
406         new _UniLMBCSGrpMap(0x2670, 0x2E7F, ULMBCS_AMBIGUOUS_SBCS),
407         new _UniLMBCSGrpMap(0x2E80, 0xF861, ULMBCS_AMBIGUOUS_MBCS),
408         new _UniLMBCSGrpMap(0xF862, 0xF8FF, ULMBCS_GRP_EXCEPT),
409         new _UniLMBCSGrpMap(0xF900, 0xFA2D, ULMBCS_AMBIGUOUS_MBCS),
410         new _UniLMBCSGrpMap(0xFB00, 0xFEFF, ULMBCS_AMBIGUOUS_SBCS),
411         new _UniLMBCSGrpMap(0xFF01, 0xFFEE, ULMBCS_AMBIGUOUS_MBCS),
412         new _UniLMBCSGrpMap(0xFFFF, 0xFFFF, ULMBCS_GRP_UNICODE)
413     };
414     
415     static short FindLMBCSUniRange(char uniChar) {
416         int index = 0;
417         
418         while (uniChar > UniLMBCSGrpMap[index].uniEndRange) {
419             index++;
420         }
421         
422         if (uniChar >= UniLMBCSGrpMap[index].uniStartRange) {
423             return UniLMBCSGrpMap[index].GrpType;
424         }
425         return ULMBCS_GRP_UNICODE;
426     }
427     
428     /*
429      * We also ask the creator of a converter to send in a preferred locale
430      * that we can use in resolving ambiguous mappings. They send the locale
431      * in as a string, and we map it, if possible, to one of the
432      * LMBCS groups. We use this table, and the associated code, to
433      * do the lookup:
434      * 
435      *     This table maps locale ID's to LMBCS opt groups.
436      *     The default return is group 0x01. Note that for
437      *     performance reasons, the table is sorted in
438      *     increasing alphabetic order, with the notable
439      *     exception of zhTW. This is to force the check
440      *     for Traditional Chinese before dropping back to
441      *     Simplified.
442      *     Note too that the Latin-1 groups have been
443      *     commented out because it's the default, and
444      *     this shortens the table, allowing a serial
445      *     search to go quickly.
446      */
447     private static class _LocaleLMBCSGrpMap {
448         String LocaleID;
449         short OptGroup;
450         _LocaleLMBCSGrpMap(String LocaleID, short OptGroup) {
451             this.LocaleID = LocaleID;
452             this.OptGroup = OptGroup;
453         }
454     }
455     private static final _LocaleLMBCSGrpMap[] LocaleLMBCSGrpMap = {
456         new _LocaleLMBCSGrpMap("ar", ULMBCS_GRP_AR),
457         new _LocaleLMBCSGrpMap("be", ULMBCS_GRP_RU),
458         new _LocaleLMBCSGrpMap("bg", ULMBCS_GRP_L2),
459         // new _LocaleLMBCSGrpMap("ca", ULMBCS_GRP_L1),
460         new _LocaleLMBCSGrpMap("cs", ULMBCS_GRP_L2),
461         // new _LocaleLMBCSGrpMap("da", ULMBCS_GRP_L1),
462         // new _LocaleLMBCSGrpMap("de", ULMBCS_GRP_L1),
463         new _LocaleLMBCSGrpMap("el", ULMBCS_GRP_GR),
464         // new _LocaleLMBCSGrpMap("en", ULMBCS_GRP_L1),
465         // new _LocaleLMBCSGrpMap("es", ULMBCS_GRP_L1),
466         // new _LocaleLMBCSGrpMap("et", ULMBCS_GRP_L1),
467         // new _LocaleLMBCSGrpMap("fi", ULMBCS_GRP_L1),
468         // new _LocaleLMBCSGrpMap("fr", ULMBCS_GRP_L1),
469         new _LocaleLMBCSGrpMap("he", ULMBCS_GRP_HE),
470         new _LocaleLMBCSGrpMap("hu", ULMBCS_GRP_L2),
471         // new _LocaleLMBCSGrpMap("is", ULMBCS_GRP_L1),
472         // new _LocaleLMBCSGrpMap("it", ULMBCS_GRP_L1),
473         new _LocaleLMBCSGrpMap("iw", ULMBCS_GRP_HE),
474         new _LocaleLMBCSGrpMap("ja", ULMBCS_GRP_JA),
475         new _LocaleLMBCSGrpMap("ko", ULMBCS_GRP_KO),
476         // new _LocaleLMBCSGrpMap("lt", ULMBCS_GRP_L1),
477         // new _LocaleLMBCSGrpMap("lv", ULMBCS_GRP_L1),
478         new _LocaleLMBCSGrpMap("mk", ULMBCS_GRP_RU),
479         // new _LocaleLMBCSGrpMap("nl", ULMBCS_GRP_L1),
480         // new _LocaleLMBCSGrpMap("no", ULMBCS_GRP_L1),
481         new _LocaleLMBCSGrpMap("pl", ULMBCS_GRP_L2),
482         // new _LocaleLMBCSGrpMap("pt", ULMBCS_GRP_L1),
483         new _LocaleLMBCSGrpMap("ro", ULMBCS_GRP_L2),
484         new _LocaleLMBCSGrpMap("ru", ULMBCS_GRP_RU),
485         new _LocaleLMBCSGrpMap("sh", ULMBCS_GRP_L2),
486         new _LocaleLMBCSGrpMap("sk", ULMBCS_GRP_L2),
487         new _LocaleLMBCSGrpMap("sl", ULMBCS_GRP_L2),
488         new _LocaleLMBCSGrpMap("sq", ULMBCS_GRP_L2),
489         new _LocaleLMBCSGrpMap("sr", ULMBCS_GRP_RU),
490         // new _LocaleLMBCSGrpMap("sv", ULMBCS_GRP_L1),
491         new _LocaleLMBCSGrpMap("th", ULMBCS_GRP_TH),
492         new _LocaleLMBCSGrpMap("tr", ULMBCS_GRP_TR),
493         new _LocaleLMBCSGrpMap("uk", ULMBCS_GRP_RU),
494         // new _LocaleLMBCSGrpMap("vi", ULMBCS_GRP_L1),
495         new _LocaleLMBCSGrpMap("zhTW", ULMBCS_GRP_TW),
496         new _LocaleLMBCSGrpMap("zh", ULMBCS_GRP_CN),
497         new _LocaleLMBCSGrpMap(null, ULMBCS_GRP_L1)
498     };
499     static short FindLMBCSLocale(String LocaleID) {
500         int index = 0;
501         
502         if (LocaleID == null) {
503             return 0;
504         }
505         
506         while (LocaleLMBCSGrpMap[index].LocaleID != null) {
507             if (LocaleLMBCSGrpMap[index].LocaleID == LocaleID) {
508                 return LocaleLMBCSGrpMap[index].OptGroup;
509             } else if (LocaleLMBCSGrpMap[index].LocaleID.compareTo(LocaleID) > 0){
510                break;
511             }
512             index++;
513         }
514         return ULMBCS_GRP_L1;
515     }
516     
517     /*
518      * Before we get to the main body of code, here's how we hook up the rest
519      * of ICU. ICU converters are required to define a structure that includes
520      * some function pointers, and some common data, in the style of a C++
521      * vtable. There is also room in there for converter-specific data. LMBCS
522      * uses that converter-specific data to keep track of the 12 subconverters
523      * we use, the optimization group, and the group (if any) that matches the
524      * locale. We have one structure instantiated for each of the 12 possible
525      * optimization groups.
526      */
527     private class UConverterDataLMBCS {
528         UConverterSharedData[] OptGrpConverter; /* Converter per Opt. grp. */
529         short OptGroup;                         /* default Opt. grp. for this LMBCS session */
530         short localeConverterIndex;             /* reasonable locale match for index */
531         CharsetDecoderMBCS decoder;
532         CharsetEncoderMBCS encoder;
533         CharsetMBCS charset;
534         UConverterDataLMBCS() {
535             OptGrpConverter = new UConverterSharedData[ULMBCS_GRP_LAST + 1];
536             charset = (CharsetMBCS)CharsetICU.forNameICU("ibm-850");
537             encoder = (CharsetEncoderMBCS)charset.newEncoder();
538             decoder = (CharsetDecoderMBCS)charset.newDecoder();
539         }
540     }
541     
542     private UConverterDataLMBCS extraInfo; /* extraInfo in ICU4C implementation */
543     
544     public CharsetLMBCS(String icuCanonicalName, String javaCanonicalName, String[] aliases) {
545         super(icuCanonicalName, javaCanonicalName, aliases);
546         maxBytesPerChar = ULMBCS_CHARSIZE_MAX; 
547         minBytesPerChar = 1;
548         maxCharsPerByte = 1;
549         
550         extraInfo = new UConverterDataLMBCS();
551         
552         for (int i = 0; i <= ULMBCS_GRP_LAST; i++) {
553             if (OptGroupByteToCPName[i] != null) {
554                 extraInfo.OptGrpConverter[i] = ((CharsetMBCS)CharsetICU.forNameICU(OptGroupByteToCPName[i])).sharedData;
555             }
556         }
557         
558       //get the Opt Group number for the LMBCS converter
559         int option = Integer.parseInt(icuCanonicalName.substring(6));
560         extraInfo.OptGroup = (short)option;
561         extraInfo.localeConverterIndex = FindLMBCSLocale(ULocale.getDefault().getBaseName());
562     }
563     
564     class CharsetDecoderLMBCS extends CharsetDecoderICU {
565         public CharsetDecoderLMBCS(CharsetICU cs) {
566             super(cs);
567             implReset();
568         }
569     
570         protected void implReset() {
571             super.implReset();
572         }
573         
574         /* A function to call when we are looking at the Unicode group byte in LMBCS */
575         private char GetUniFromLMBCSUni(ByteBuffer ppLMBCSin) {
576             short HighCh = (short)(ppLMBCSin.get() & UConverterConstants.UNSIGNED_BYTE_MASK);
577             short LowCh  = (short)(ppLMBCSin.get() & UConverterConstants.UNSIGNED_BYTE_MASK);
578             
579             if (HighCh == ULMBCS_UNICOMPATZERO) {
580                 HighCh = LowCh;
581                 LowCh = 0; /* zero-byte in LSB special character */
582             }
583             
584             return (char)((HighCh << 8) | LowCh);
585         }
586         
587         private int LMBCS_SimpleGetNextUChar(UConverterSharedData cnv, ByteBuffer source, int positionOffset, int length) {
588             int uniChar;
589             int oldSourceLimit;
590             int oldSourcePos;
591             
592             extraInfo.charset.sharedData = cnv;
593             
594             oldSourceLimit = source.limit();
595             oldSourcePos = source.position();
596             
597             source.position(oldSourcePos + positionOffset);
598             source.limit(source.position() + length);
599             
600             uniChar = extraInfo.decoder.simpleGetNextUChar(source, false);
601             
602             source.limit(oldSourceLimit);
603             source.position(oldSourcePos);
604
605             return uniChar;
606         }
607         /* Return the Unicode representation for the current LMBCS character. */
608         /*
609          * Note: Because there is no U_TRUNCATED_CHAR_FOUND error code in ICU4J, we
610          *       are going to use BufferOverFlow. The error will be handled correctly
611          *       by the calling function.
612          */
613         private int LMBCSGetNextUCharWorker(ByteBuffer source, CoderResult[] err) {
614             int uniChar = 0;  /* an output Unicode char */
615             short CurByte;   /* A byte from the input stream */
616             
617             /* error check */
618             if (!source.hasRemaining()) {
619                 err[0] = CoderResult.malformedForLength(0);
620                 return 0xffff;
621             }
622             /* Grab first byte & save address for error recovery */
623             CurByte = (short)(source.get() & UConverterConstants.UNSIGNED_BYTE_MASK);
624             
625             /*
626              * at entry of each if clause:
627              * 1. 'CurByte' points at the first byte of a LMBCS character
628              * 2. 'source' points to the next byte of the source stream after 'CurByte'
629              * 
630              * the job of each if clause is:
631              * 1. set 'source' to the point at the beginning of the next char (not if LMBCS char is only 1 byte)
632              * 2. set 'uniChar' up with the right Unicode value, or set 'err' appropriately
633              */
634             /* First lets check the simple fixed values. */
635             if ((CurByte > ULMBCS_C0END && CurByte < ULMBCS_C1START) /* ascii range */ ||
636                 CurByte == 0 || CurByte == ULMBCS_HT || CurByte == ULMBCS_CR || CurByte == ULMBCS_LF ||
637                 CurByte == ULMBCS_123SYSTEMRANGE) {
638                 
639                 uniChar = CurByte;
640             } else {
641                 short group;
642                 UConverterSharedData cnv;
643                 
644                 if (CurByte == ULMBCS_GRP_CTRL) {  /* Control character group - no opt group update */
645                     short C0C1byte;
646                     /* CHECK_SOURCE_LIMIT(1) */
647                     if (source.position() + 1 > source.limit()) {
648                         err[0] = CoderResult.OVERFLOW;
649                         source.position(source.limit());
650                         return 0xFFFF;
651                     }
652                     C0C1byte = (short)(source.get() & UConverterConstants.UNSIGNED_BYTE_MASK);
653                     uniChar = (C0C1byte < ULMBCS_C1START) ? C0C1byte - ULMBCS_CTRLOFFSET : C0C1byte;
654                 } else if (CurByte == ULMBCS_GRP_UNICODE) { /* Unicode Compatibility group: Big Endian UTF16 */
655                     /* CHECK_SOURCE_LIMIT(2) */
656                     if (source.position() + 2 > source.limit()) {
657                         err[0] = CoderResult.OVERFLOW;
658                         source.position(source.limit());
659                         return 0xFFFF;
660                     }
661                     
662                     /* don't check for error indicators fffe/ffff below */
663                     return GetUniFromLMBCSUni(source);
664                 } else if (CurByte <= ULMBCS_CTRLOFFSET) {
665                     group = CurByte;
666                     if (group > ULMBCS_GRP_LAST || (cnv = extraInfo.OptGrpConverter[group]) == null) {
667                         /* this is not a valid group byte - no converter */
668                         err[0] = CoderResult.unmappableForLength(1);
669                     } else if (group >= ULMBCS_DOUBLEOPTGROUP_START) {
670                         /* CHECK_SOURCE_LIMIT(2) */
671                         if (source.position() + 2 > source.limit()) {
672                             err[0] = CoderResult.OVERFLOW;
673                             source.position(source.limit());
674                             return 0xFFFF;
675                         }
676                         
677                         /* check for LMBCS doubled-group-byte case */
678                         if (source.get(source.position()) == group) {
679                             /* single byte */
680                             source.get();
681                             uniChar = LMBCS_SimpleGetNextUChar(cnv, source, 0, 1);
682                             source.get();
683                         } else {
684                             /* double byte */
685                             uniChar = LMBCS_SimpleGetNextUChar(cnv, source, 0, 2);
686                             source.get();
687                             source.get();
688                         }
689                     } else { /* single byte conversion */
690                         /* CHECK_SOURCE_LIMIT(1) */
691                         if (source.position() + 1 > source.limit()) {
692                             err[0] = CoderResult.OVERFLOW;
693                             source.position(source.limit());
694                             return 0xFFFF;
695                         }
696                         CurByte = (short)(source.get() & UConverterConstants.UNSIGNED_BYTE_MASK);
697                         
698                         if (CurByte >= ULMBCS_C1START) {
699                             uniChar = CharsetMBCS.MBCS_SINGLE_SIMPLE_GET_NEXT_BMP(cnv.mbcs, CurByte);
700                         } else {
701                             /*
702                              * The non-optimizable oddballs where there is an explicit byte
703                              * AND the second byte is not in the upper ascii range
704                              */
705                             byte[] bytes = new byte[2];
706                             
707                             cnv = extraInfo.OptGrpConverter[ULMBCS_GRP_EXCEPT];
708                             
709                             /* Lookup value must include opt group */
710                             bytes[0] = (byte)group;
711                             bytes[1] = (byte)CurByte;
712                             uniChar = LMBCS_SimpleGetNextUChar(cnv, ByteBuffer.wrap(bytes), 0, 2);
713                         }
714                     }
715                     
716                 } else if (CurByte >= ULMBCS_C1START) { /* group byte is implicit */
717                     group = extraInfo.OptGroup;
718                     cnv = extraInfo.OptGrpConverter[group];
719                     if (group >= ULMBCS_DOUBLEOPTGROUP_START) { /* double byte conversion */
720                         if (CharsetMBCS.MBCS_ENTRY_IS_TRANSITION(cnv.mbcs.stateTable[0][CurByte]) /* isLeadByte */) {
721                             /* CHECK_SOURCE_LIMIT(0) */
722                             if (source.position() + 0 > source.limit()) {
723                                 err[0] = CoderResult.OVERFLOW;
724                                 source.position(source.limit());
725                                 return 0xFFFF;
726                             }
727                             
728                             /* let the MBCS conversion consume CurByte again */
729                             uniChar = LMBCS_SimpleGetNextUChar(cnv, source, -1, 1);
730                         } else {
731                             /* CHECK_SOURCE_LIMIT(1) */
732                             if (source.position() + 1 > source.limit()) {
733                                 err[0] = CoderResult.OVERFLOW;
734                                 source.position(source.limit());
735                                 return 0xFFFF;
736                             }
737                             
738                             /* let the MBCS conversion consume CurByte again */
739                             uniChar = LMBCS_SimpleGetNextUChar(cnv, source, -1, 2);
740                             source.get();
741                         }
742                     } else {
743                         uniChar = CharsetMBCS.MBCS_SINGLE_SIMPLE_GET_NEXT_BMP(cnv.mbcs, CurByte);
744                     }
745                 }
746             }
747             
748             return uniChar;
749         }
750         
751         protected CoderResult decodeLoop(ByteBuffer source, CharBuffer target, IntBuffer offsets, boolean flush) { 
752             CoderResult[] err = new CoderResult[1];
753             err[0] = CoderResult.UNDERFLOW;
754             byte[] LMBCS = new byte[ULMBCS_CHARSIZE_MAX * 2]; /* Increase the size for proper handling in subsequent calls to MBCS functions */
755             char uniChar;   /* one output Unicode char */
756             int saveSource; /* beginning of current code point */
757             int errSource = 0; /* index to actual input in case an error occurs */
758             byte savebytes = 0;
759             
760             /* Process from source to limit, or until error */
761             while (err[0].isUnderflow() && source.hasRemaining() && target.hasRemaining()) {
762                 saveSource = source.position(); /* beginning of current code point */
763                 if (toULength > 0) { /* reassemble char from previous call */
764                     int size_old = toULength;
765                     ByteBuffer tmpSourceBuffer;
766                     
767                     /* limit from source is either remainder of temp buffer, or user limit on source */
768                     int size_new_maybe_1 = ULMBCS_CHARSIZE_MAX - size_old;
769                     int size_new_maybe_2 = source.remaining();
770                     int size_new = (size_new_maybe_1 < size_new_maybe_2) ? size_new_maybe_1 : size_new_maybe_2;
771                     savebytes = (byte)(size_old + size_new);
772                     for (int i = 0; i < savebytes; i++) {
773                         if (i < size_old) {
774                             LMBCS[i] = toUBytesArray[i];
775                         } else {
776                             LMBCS[i] = source.get();
777                         }
778                     }
779                     tmpSourceBuffer = ByteBuffer.wrap(LMBCS);
780                     tmpSourceBuffer.limit(savebytes);
781                     uniChar = (char)LMBCSGetNextUCharWorker(tmpSourceBuffer, err);
782                     source.position(saveSource + tmpSourceBuffer.position() - size_old);
783                     errSource = saveSource - size_old;
784                     
785                     if (err[0].isOverflow()) { /* err == U_TRUNCATED_CHAR_FOUND */ 
786                         /* evil special case: source buffers so small a char spans more than 2 buffers */
787                         toULength = savebytes;
788                         for (int i = 0; i < savebytes; i++) {
789                             toUBytesArray[i] = LMBCS[i];
790                         }
791                         source.position(source.limit());
792                         err[0] = CoderResult.UNDERFLOW;
793                         return err[0];
794                     } else {
795                         /* clear the partial-char marker */
796                         toULength = 0;
797                     }
798                 } else {
799                     errSource = saveSource;
800                     uniChar = (char)LMBCSGetNextUCharWorker(source, err);
801                     savebytes = (byte)(source.position() - saveSource);
802                 }
803                 
804                 if (err[0].isUnderflow()) {
805                     if (uniChar < 0x0fffe) {
806                         target.put(uniChar);
807                         if (offsets != null) {
808                             offsets.put(saveSource);
809                         }
810                     } else if (uniChar == 0xfffe) {
811                         err[0] = CoderResult.unmappableForLength(source.position() - saveSource);
812                     } else /* if (uniChar == 0xffff) */ {
813                         err[0] = CoderResult.malformedForLength(source.position() - saveSource);
814                     }
815                 }
816             }
817             /* If target ran out before source, return over flow buffer error. */
818             if (err[0].isUnderflow() && source.hasRemaining() && !target.hasRemaining()) {
819                 err[0] = CoderResult.OVERFLOW;
820             } else if (!err[0].isUnderflow()) {
821                 /* If character incomplete or unmappable/illegal, store it in toUBytesArray[] */
822                 toULength = savebytes;
823                 if (savebytes > 0) {
824                     for (int i = 0; i < savebytes; i++) {
825                         toUBytesArray[i] = source.get(errSource + i);
826                     }
827                 }
828                 if (err[0].isOverflow()) { /* err == U_TRUNCATED_CHAR_FOUND */
829                     err[0] = CoderResult.UNDERFLOW;
830                 }
831             }
832             return err[0];
833         }
834     }
835     
836     class CharsetEncoderLMBCS extends CharsetEncoderICU {
837         public CharsetEncoderLMBCS(CharsetICU cs) {
838             super(cs, fromUSubstitution);
839             implReset();
840         }
841         
842         protected void implReset() {
843             super.implReset();
844         }
845         /*
846          * Here's the basic helper function that we use when converting from
847          * Unicode to LMBCS, and we suspect that a Unicode character will fit into
848          * one of the 12 groups. The return value is the number of bytes written
849          * starting at pStartLMBCS (if any).
850          */
851         @SuppressWarnings("fallthrough")
852         private int LMBCSConversionWorker(short group, byte[] LMBCS, char pUniChar, short[] lastConverterIndex, boolean[] groups_tried) {
853             byte pLMBCS = 0;
854             UConverterSharedData xcnv = extraInfo.OptGrpConverter[group];
855             
856             int bytesConverted;
857             int[] value = new int[1];
858             short firstByte;
859             
860             extraInfo.charset.sharedData = xcnv;
861             bytesConverted = extraInfo.encoder.fromUChar32(pUniChar, value, false);
862             
863             /* get the first result byte */
864             if (bytesConverted > 0) {
865                 firstByte = (short)((value[0] >> ((bytesConverted - 1) * 8)) & UConverterConstants.UNSIGNED_BYTE_MASK);
866             } else {
867                 /* most common failure mode is an unassigned character */
868                 groups_tried[group] = true;
869                 return 0;
870             }
871             
872             lastConverterIndex[0] = group;
873             
874             /* 
875              * All initial byte values in lower ascii range should have been caught by now,
876              * except with the exception group.
877              */
878             
879             /* use converted data: first write 0, 1 or two group bytes */
880             if (group != ULMBCS_GRP_EXCEPT && extraInfo.OptGroup != group) {
881                 LMBCS[pLMBCS++] = (byte)group;
882                 if (bytesConverted == 1 && group >= ULMBCS_DOUBLEOPTGROUP_START) {
883                     LMBCS[pLMBCS++] = (byte)group;
884                 }
885             }
886             
887             /* don't emit control chars */
888             if (bytesConverted == 1 && firstByte < 0x20) {
889                 return 0;
890             }
891             
892             /* then move over the converted data */
893             switch (bytesConverted) {
894             case 4:
895                 LMBCS[pLMBCS++] = (byte)(value[0] >> 24);
896             case 3:
897                 LMBCS[pLMBCS++] = (byte)(value[0] >> 16);
898             case 2:
899                 LMBCS[pLMBCS++] = (byte)(value[0] >> 8);
900             case 1:
901                 LMBCS[pLMBCS++] = (byte)value[0];
902             default:
903                 /* will never occur */
904                 break;
905             }
906             
907             return pLMBCS;
908         }
909         /*
910          * This is a much simpler version of above, when we
911          * know we are writing LMBCS using the Unicode group.
912          */
913         private int LMBCSConvertUni(byte[] LMBCS, char uniChar) {
914             int index = 0;
915             short LowCh  = (short)(uniChar & UConverterConstants.UNSIGNED_BYTE_MASK);
916             short HighCh = (short)((uniChar >> 8) & UConverterConstants.UNSIGNED_BYTE_MASK);
917             
918             LMBCS[index++] = (byte)ULMBCS_GRP_UNICODE;
919             
920             if (LowCh == 0) {
921                 LMBCS[index++] = (byte)ULMBCS_UNICOMPATZERO;
922                 LMBCS[index++] = (byte)HighCh;
923             } else {
924                 LMBCS[index++] = (byte)HighCh;
925                 LMBCS[index++] = (byte)LowCh;
926             }
927             return ULMBCS_UNICODE_SIZE;
928         }
929         /* The main Unicode to LMBCS conversion function */
930         protected CoderResult encodeLoop(CharBuffer source, ByteBuffer target, IntBuffer offsets, boolean flush) {
931             CoderResult err = CoderResult.UNDERFLOW;
932             short[] lastConverterIndex = new short[1];
933             char uniChar;
934             byte[] LMBCS = new byte[ULMBCS_CHARSIZE_MAX];
935             byte pLMBCS;
936             int bytes_written;
937             boolean[] groups_tried = new boolean[ULMBCS_GRP_LAST+1];
938             int sourceIndex = 0;
939             
940             /*
941              * Basic strategy: attempt to fill in local LMBCS 1-char buffer.(LMBCS)
942              * If that succeeds, see if it will all fit into the target & copy it over
943              * if it does.
944              * 
945              * We try conversions in the following order:
946              * 1. Single-byte ascii & special fixed control chars (&null)
947              * 2. Look up group in table & try that (could b
948              *     A) Unicode group
949              *     B) control group
950              *     C) national encodeing
951              *        or ambiguous SBCS or MBCS group (on to step 4...)
952              * 3. If its ambiguous, try this order:
953              *     A) The optimization group
954              *     B) The locale group
955              *     C) The last group that succeeded with this string.
956              *     D) every other group that's relevant
957              *     E) If its single-byte ambiguous, try the exceptions group
958              * 4. And as a grand fallback: Unicode
959              */
960             
961             short OldConverterIndex = 0;
962             
963             while (source.hasRemaining() && err.isUnderflow()) {
964                 OldConverterIndex = extraInfo.localeConverterIndex;
965                 
966                 if (!target.hasRemaining()) {
967                     err = CoderResult.OVERFLOW;
968                     break;
969                 }
970                 
971                 uniChar = source.get(source.position());
972                 bytes_written = 0;
973                 pLMBCS = 0;
974                 
975                 /* check cases in rough order of how common they are, for speed */
976                 
977                 /* single-byte matches: strategy 1 */
978                 if((uniChar>=0x80) && (uniChar<=0xff) && (uniChar!=0xB1) && (uniChar!=0xD7) && (uniChar!=0xF7) &&
979                    (uniChar!=0xB0) && (uniChar!=0xB4) && (uniChar!=0xB6) && (uniChar!=0xA7) && (uniChar!=0xA8)) {
980                       extraInfo.localeConverterIndex = ULMBCS_GRP_L1;
981                 }
982                 if (((uniChar > ULMBCS_C0END) && (uniChar < ULMBCS_C1START)) ||
983                     uniChar == 0 || uniChar == ULMBCS_HT || uniChar == ULMBCS_CR ||
984                     uniChar == ULMBCS_LF || uniChar == ULMBCS_123SYSTEMRANGE) {
985                     LMBCS[pLMBCS++] = (byte)uniChar;
986                     bytes_written = 1;
987                 }
988                 
989                 if (bytes_written == 0) {
990                     /* Check by Unicode rage (Strategy 2) */
991                     short group = FindLMBCSUniRange(uniChar);
992                     if (group == ULMBCS_GRP_UNICODE) { /* (Strategy 2A) */
993                         bytes_written = LMBCSConvertUni(LMBCS, uniChar);
994                     } else if (group == ULMBCS_GRP_CTRL) { /* Strategy 2B) */
995                         /* Handle control characters here */
996                         if (uniChar <= ULMBCS_C0END) {
997                             LMBCS[pLMBCS++] = ULMBCS_GRP_CTRL;
998                             LMBCS[pLMBCS++] = (byte)(ULMBCS_CTRLOFFSET + uniChar);
999                         } else if (uniChar >= ULMBCS_C1START && uniChar <= (ULMBCS_C1START + ULMBCS_CTRLOFFSET)) {
1000                             LMBCS[pLMBCS++] = ULMBCS_GRP_CTRL;
1001                             LMBCS[pLMBCS++] = (byte)uniChar;
1002                         }
1003                         bytes_written = pLMBCS;
1004                     } else if (group < ULMBCS_GRP_UNICODE) { /* (Strategy 2C) */
1005                         /* a specific converter has been identified - use it */
1006                         bytes_written = LMBCSConversionWorker(group, LMBCS, uniChar, lastConverterIndex, groups_tried);
1007                     }
1008                     if (bytes_written == 0) { /* the ambiguous group cases (Strategy 3) */
1009                         groups_tried = new boolean[ULMBCS_GRP_LAST+1];
1010                         
1011                         /* check for non-default optimization group (Strategy 3A) */
1012                         if (extraInfo.OptGroup != 1 && ULMBCS_AMBIGUOUS_MATCH(group, extraInfo.OptGroup)) {
1013                             if(extraInfo.localeConverterIndex < ULMBCS_DOUBLEOPTGROUP_START) {
1014                                 bytes_written = LMBCSConversionWorker (ULMBCS_GRP_L1, LMBCS, uniChar, lastConverterIndex, groups_tried);
1015                             
1016                                 if(bytes_written == 0) {
1017                                     bytes_written = LMBCSConversionWorker (ULMBCS_GRP_EXCEPT, LMBCS, uniChar, lastConverterIndex, groups_tried);
1018                                 }
1019                                 if(bytes_written == 0) {
1020                                     bytes_written = LMBCSConversionWorker (extraInfo.localeConverterIndex, LMBCS, uniChar, lastConverterIndex, groups_tried);
1021                                 }
1022                             } else {
1023                                  bytes_written = LMBCSConversionWorker (extraInfo.localeConverterIndex, LMBCS, uniChar, lastConverterIndex, groups_tried);
1024                             }
1025                         }
1026                         /* check for locale optimization group (Strategy 3B) */
1027                         if (bytes_written == 0 && extraInfo.localeConverterIndex > 0 && ULMBCS_AMBIGUOUS_MATCH(group, extraInfo.localeConverterIndex)) {
1028                             
1029                             bytes_written = LMBCSConversionWorker(extraInfo.localeConverterIndex, LMBCS, uniChar, lastConverterIndex, groups_tried);
1030                         }
1031                         /* check for last optimization group used for this string (Strategy 3C) */
1032                         if (bytes_written == 0 && lastConverterIndex[0] > 0 && ULMBCS_AMBIGUOUS_MATCH(group, lastConverterIndex[0])) {
1033                             bytes_written = LMBCSConversionWorker(lastConverterIndex[0], LMBCS, uniChar, lastConverterIndex, groups_tried);
1034                         }
1035                         if (bytes_written == 0) {
1036                             /* just check every possible matching converter (Strategy 3D) */
1037                             short grp_start;
1038                             short grp_end;
1039                             short grp_ix;
1040                             
1041                             grp_start = (group == ULMBCS_AMBIGUOUS_MBCS) ? ULMBCS_DOUBLEOPTGROUP_START : ULMBCS_GRP_L1;
1042                             grp_end   = (group == ULMBCS_AMBIGUOUS_MBCS) ? ULMBCS_GRP_LAST : ULMBCS_GRP_TH;
1043                             
1044                             if(group == ULMBCS_AMBIGUOUS_ALL) {
1045                                 grp_start = ULMBCS_GRP_L1;
1046                                 grp_end = ULMBCS_GRP_LAST;
1047                             }
1048                             
1049                             for (grp_ix = grp_start; grp_ix <= grp_end && bytes_written == 0; grp_ix++) {
1050                                 if (extraInfo.OptGrpConverter[grp_ix] != null && !groups_tried[grp_ix]) {
1051                                     bytes_written = LMBCSConversionWorker(grp_ix, LMBCS, uniChar, lastConverterIndex, groups_tried);
1052                                 }
1053                             }
1054                             /* 
1055                              * a final conversion fallback to the exceptions group if its likely
1056                              * to be single byte (Strategy 3E) 
1057                              */
1058                             if (bytes_written == 0 && grp_start == ULMBCS_GRP_L1) {
1059                                 bytes_written = LMBCSConversionWorker(ULMBCS_GRP_EXCEPT, LMBCS, uniChar, lastConverterIndex, groups_tried);
1060                             }
1061                         }
1062                         /* all of our other strategies failed. Fallback to Unicode. (Strategy 4) */
1063                         if (bytes_written == 0) {
1064                             bytes_written = LMBCSConvertUni(LMBCS, uniChar);
1065                         }
1066                     }
1067                 }
1068                 /* we have a translation. increment source and write as much as possible to target */
1069                 source.get();
1070                 pLMBCS = 0;
1071                 while (target.hasRemaining() && bytes_written > 0) {
1072                     bytes_written--;
1073                     target.put(LMBCS[pLMBCS++]);
1074                     if (offsets != null) {
1075                         offsets.put(sourceIndex);
1076                     }
1077                 }
1078                 sourceIndex++;
1079                 if (bytes_written > 0) {
1080                     /*
1081                      * write any bytes that didn't fit in target to the error buffer,
1082                      * common code will move this to target if we get called back with
1083                      * enough target room
1084                      */
1085                     err = CoderResult.OVERFLOW;
1086                     errorBufferLength = bytes_written;
1087                     for (int i = 0; bytes_written > 0; i++, bytes_written--) {
1088                         errorBuffer[i] = LMBCS[pLMBCS++];
1089                     }
1090                 }
1091                 extraInfo.localeConverterIndex = OldConverterIndex;
1092             }
1093             
1094             return err;
1095         }
1096     }
1097     public CharsetDecoder newDecoder() {
1098         return new CharsetDecoderLMBCS(this);
1099     }
1100     
1101     public CharsetEncoder newEncoder() {
1102         return new CharsetEncoderLMBCS(this);
1103     }
1104     
1105     void getUnicodeSetImpl(UnicodeSet setFillIn, int which){
1106         getCompleteUnicodeSet(setFillIn);
1107     }
1108     private byte[] fromUSubstitution = new byte[]{ 0x3F };
1109 }