1 /*
  2  * Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.  Oracle designates this
  8  * particular file as subject to the "Classpath" exception as provided
  9  * by Oracle in the LICENSE file that accompanied this code.
 10  *
 11  * This code is distributed in the hope that it will be useful, but WITHOUT
 12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 14  * version 2 for more details (a copy is included in the LICENSE file that
 15  * accompanied this code).
 16  *
 17  * You should have received a copy of the GNU General Public License version
 18  * 2 along with this work; if not, write to the Free Software Foundation,
 19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 20  *
 21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 22  * or visit www.oracle.com if you need additional information or have any
 23  * questions.
 24  */
 25 
 26 package java.nio.charset;
 27 
 28 import jdk.internal.misc.Gate;
 29 import jdk.internal.misc.VM;
 30 import sun.nio.cs.ThreadLocalCoders;
 31 import sun.security.action.GetPropertyAction;
 32 
 33 import java.nio.ByteBuffer;
 34 import java.nio.CharBuffer;
 35 import java.nio.charset.spi.CharsetProvider;
 36 import java.security.AccessController;
 37 import java.security.PrivilegedAction;
 38 import java.util.Arrays;
 39 import java.util.Collections;
 40 import java.util.HashSet;
 41 import java.util.Iterator;
 42 import java.util.Locale;
 43 import java.util.Map;
 44 import java.util.NoSuchElementException;
 45 import java.util.Objects;
 46 import java.util.ServiceConfigurationError;
 47 import java.util.ServiceLoader;
 48 import java.util.Set;
 49 import java.util.SortedMap;
 50 import java.util.TreeMap;
 51 
 52 
 53 /**
 54  * A named mapping between sequences of sixteen-bit Unicode <a
 55  * href="../../lang/Character.html#unicode">code units</a> and sequences of
 56  * bytes.  This class defines methods for creating decoders and encoders and
 57  * for retrieving the various names associated with a charset.  Instances of
 58  * this class are immutable.
 59  *
 60  * <p> This class also defines static methods for testing whether a particular
 61  * charset is supported, for locating charset instances by name, and for
 62  * constructing a map that contains every charset for which support is
 63  * available in the current Java virtual machine.  Support for new charsets can
 64  * be added via the service-provider interface defined in the {@link
 65  * java.nio.charset.spi.CharsetProvider} class.
 66  *
 67  * <p> All of the methods defined in this class are safe for use by multiple
 68  * concurrent threads.
 69  *
 70  *
 71  * <h2><a id="names">Charset names</a></h2>
 72  *
 73  * <p> Charsets are named by strings composed of the following characters:
 74  *
 75  * <ul>
 76  *
 77  *   <li> The uppercase letters {@code 'A'} through {@code 'Z'}
 78  *        (<code>'&#92;u0041'</code>&nbsp;through&nbsp;<code>'&#92;u005a'</code>),
 79  *
 80  *   <li> The lowercase letters {@code 'a'} through {@code 'z'}
 81  *        (<code>'&#92;u0061'</code>&nbsp;through&nbsp;<code>'&#92;u007a'</code>),
 82  *
 83  *   <li> The digits {@code '0'} through {@code '9'}
 84  *        (<code>'&#92;u0030'</code>&nbsp;through&nbsp;<code>'&#92;u0039'</code>),
 85  *
 86  *   <li> The dash character {@code '-'}
 87  *        (<code>'&#92;u002d'</code>,&nbsp;<small>HYPHEN-MINUS</small>),
 88  *
 89  *   <li> The plus character {@code '+'}
 90  *        (<code>'&#92;u002b'</code>,&nbsp;<small>PLUS SIGN</small>),
 91  *
 92  *   <li> The period character {@code '.'}
 93  *        (<code>'&#92;u002e'</code>,&nbsp;<small>FULL STOP</small>),
 94  *
 95  *   <li> The colon character {@code ':'}
 96  *        (<code>'&#92;u003a'</code>,&nbsp;<small>COLON</small>), and
 97  *
 98  *   <li> The underscore character {@code '_'}
 99  *        (<code>'&#92;u005f'</code>,&nbsp;<small>LOW&nbsp;LINE</small>).
100  *
101  * </ul>
102  *
103  * A charset name must begin with either a letter or a digit.  The empty string
104  * is not a legal charset name.  Charset names are not case-sensitive; that is,
105  * case is always ignored when comparing charset names.  Charset names
106  * generally follow the conventions documented in <a
107  * href="http://www.ietf.org/rfc/rfc2278.txt"><i>RFC&nbsp;2278:&nbsp;IANA Charset
108  * Registration Procedures</i></a>.
109  *
110  * <p> Every charset has a <i>canonical name</i> and may also have one or more
111  * <i>aliases</i>.  The canonical name is returned by the {@link #name() name} method
112  * of this class.  Canonical names are, by convention, usually in upper case.
113  * The aliases of a charset are returned by the {@link #aliases() aliases}
114  * method.
115  *
116  * <p><a id="hn">Some charsets have an <i>historical name</i> that is defined for
117  * compatibility with previous versions of the Java platform.</a>  A charset's
118  * historical name is either its canonical name or one of its aliases.  The
119  * historical name is returned by the {@code getEncoding()} methods of the
120  * {@link java.io.InputStreamReader#getEncoding InputStreamReader} and {@link
121  * java.io.OutputStreamWriter#getEncoding OutputStreamWriter} classes.
122  *
123  * <p><a id="iana"> </a>If a charset listed in the <a
124  * href="http://www.iana.org/assignments/character-sets"><i>IANA Charset
125  * Registry</i></a> is supported by an implementation of the Java platform then
126  * its canonical name must be the name listed in the registry. Many charsets
127  * are given more than one name in the registry, in which case the registry
128  * identifies one of the names as <i>MIME-preferred</i>.  If a charset has more
129  * than one registry name then its canonical name must be the MIME-preferred
130  * name and the other names in the registry must be valid aliases.  If a
131  * supported charset is not listed in the IANA registry then its canonical name
132  * must begin with one of the strings {@code "X-"} or {@code "x-"}.
133  *
134  * <p> The IANA charset registry does change over time, and so the canonical
135  * name and the aliases of a particular charset may also change over time.  To
136  * ensure compatibility it is recommended that no alias ever be removed from a
137  * charset, and that if the canonical name of a charset is changed then its
138  * previous canonical name be made into an alias.
139  *
140  *
141  * <h2><a id="standard">Standard charsets</a></h2>
142  *
143  *
144  * <p> Every implementation of the Java platform is required to support the
145  * following standard charsets.  Consult the release documentation for your
146  * implementation to see if any other charsets are supported.  The behavior
147  * of such optional charsets may differ between implementations.
148  *
149  * <blockquote><table class="striped" style="width:80%">
150  * <caption style="display:none">Description of standard charsets</caption>
151  * <thead>
152  * <tr><th scope="col" style="text-align:left">Charset</th><th scope="col" style="text-align:left">Description</th></tr>
153  * </thead>
154  * <tbody>
155  * <tr><th scope="row" style="vertical-align:top">{@code US-ASCII}</th>
156  *     <td>Seven-bit ASCII, a.k.a. {@code ISO646-US},
157  *         a.k.a. the Basic Latin block of the Unicode character set</td></tr>
158  * <tr><th scope="row" style="vertical-align:top"><code>ISO-8859-1&nbsp;&nbsp;</code></th>
159  *     <td>ISO Latin Alphabet No. 1, a.k.a. {@code ISO-LATIN-1}</td></tr>
160  * <tr><th scope="row" style="vertical-align:top">{@code UTF-8}</th>
161  *     <td>Eight-bit UCS Transformation Format</td></tr>
162  * <tr><th scope="row" style="vertical-align:top">{@code UTF-16BE}</th>
163  *     <td>Sixteen-bit UCS Transformation Format,
164  *         big-endian byte&nbsp;order</td></tr>
165  * <tr><th scope="row" style="vertical-align:top">{@code UTF-16LE}</th>
166  *     <td>Sixteen-bit UCS Transformation Format,
167  *         little-endian byte&nbsp;order</td></tr>
168  * <tr><th scope="row" style="vertical-align:top">{@code UTF-16}</th>
169  *     <td>Sixteen-bit UCS Transformation Format,
170  *         byte&nbsp;order identified by an optional byte-order mark</td></tr>
171  * </tbody>
172  * </table></blockquote>
173  *
174  * <p> The {@code UTF-8} charset is specified by <a
175  * href="http://www.ietf.org/rfc/rfc2279.txt"><i>RFC&nbsp;2279</i></a>; the
176  * transformation format upon which it is based is specified in
177  * Amendment&nbsp;2 of ISO&nbsp;10646-1 and is also described in the <a
178  * href="http://www.unicode.org/standard/standard.html"><i>Unicode
179  * Standard</i></a>.
180  *
181  * <p> The {@code UTF-16} charsets are specified by <a
182  * href="http://www.ietf.org/rfc/rfc2781.txt"><i>RFC&nbsp;2781</i></a>; the
183  * transformation formats upon which they are based are specified in
184  * Amendment&nbsp;1 of ISO&nbsp;10646-1 and are also described in the <a
185  * href="http://www.unicode.org/standard/standard.html"><i>Unicode
186  * Standard</i></a>.
187  *
188  * <p> The {@code UTF-16} charsets use sixteen-bit quantities and are
189  * therefore sensitive to byte order.  In these encodings the byte order of a
190  * stream may be indicated by an initial <i>byte-order mark</i> represented by
191  * the Unicode character <code>'&#92;uFEFF'</code>.  Byte-order marks are handled
192  * as follows:
193  *
194  * <ul>
195  *
196  *   <li><p> When decoding, the {@code UTF-16BE} and {@code UTF-16LE}
197  *   charsets interpret the initial byte-order marks as a <small>ZERO-WIDTH
198  *   NON-BREAKING SPACE</small>; when encoding, they do not write
199  *   byte-order marks. </p></li>
200  *
201  *   <li><p> When decoding, the {@code UTF-16} charset interprets the
202  *   byte-order mark at the beginning of the input stream to indicate the
203  *   byte-order of the stream but defaults to big-endian if there is no
204  *   byte-order mark; when encoding, it uses big-endian byte order and writes
205  *   a big-endian byte-order mark. </p></li>
206  *
207  * </ul>
208  *
209  * In any case, byte order marks occurring after the first element of an
210  * input sequence are not omitted since the same code is used to represent
211  * <small>ZERO-WIDTH NON-BREAKING SPACE</small>.
212  *
213  * <p> Every instance of the Java virtual machine has a default charset, which
214  * is {@code UTF-8} unless changed in an implementation specific manner. Refer to
215  * {@link #defaultCharset()} for more detail.
216  *
217  * <p> The {@link StandardCharsets} class defines constants for each of the
218  * standard charsets.
219  *
220  * <h2>Terminology</h2>
221  *
222  * <p> The name of this class is taken from the terms used in
223  * <a href="http://www.ietf.org/rfc/rfc2278.txt"><i>RFC&nbsp;2278</i></a>.
224  * In that document a <i>charset</i> is defined as the combination of
225  * one or more coded character sets and a character-encoding scheme.
226  * (This definition is confusing; some other software systems define
227  * <i>charset</i> as a synonym for <i>coded character set</i>.)
228  *
229  * <p> A <i>coded character set</i> is a mapping between a set of abstract
230  * characters and a set of integers.  US-ASCII, ISO&nbsp;8859-1,
231  * JIS&nbsp;X&nbsp;0201, and Unicode are examples of coded character sets.
232  *
233  * <p> Some standards have defined a <i>character set</i> to be simply a
234  * set of abstract characters without an associated assigned numbering.
235  * An alphabet is an example of such a character set.  However, the subtle
236  * distinction between <i>character set</i> and <i>coded character set</i>
237  * is rarely used in practice; the former has become a short form for the
238  * latter, including in the Java API specification.
239  *
240  * <p> A <i>character-encoding scheme</i> is a mapping between one or more
241  * coded character sets and a set of octet (eight-bit byte) sequences.
242  * UTF-8, UTF-16, ISO&nbsp;2022, and EUC are examples of
243  * character-encoding schemes.  Encoding schemes are often associated with
244  * a particular coded character set; UTF-8, for example, is used only to
245  * encode Unicode.  Some schemes, however, are associated with multiple
246  * coded character sets; EUC, for example, can be used to encode
247  * characters in a variety of Asian coded character sets.
248  *
249  * <p> When a coded character set is used exclusively with a single
250  * character-encoding scheme then the corresponding charset is usually
251  * named for the coded character set; otherwise a charset is usually named
252  * for the encoding scheme and, possibly, the locale of the coded
253  * character sets that it supports.  Hence {@code US-ASCII} is both the
254  * name of a coded character set and of the charset that encodes it, while
255  * {@code EUC-JP} is the name of the charset that encodes the
256  * JIS&nbsp;X&nbsp;0201, JIS&nbsp;X&nbsp;0208, and JIS&nbsp;X&nbsp;0212
257  * coded character sets for the Japanese language.
258  *
259  * <p> The native character encoding of the Java programming language is
260  * UTF-16.  A charset in the Java platform therefore defines a mapping
261  * between sequences of sixteen-bit UTF-16 code units (that is, sequences
262  * of chars) and sequences of bytes. </p>
263  *
264  *
265  * @author Mark Reinhold
266  * @author JSR-51 Expert Group
267  * @since 1.4
268  *
269  * @see CharsetDecoder
270  * @see CharsetEncoder
271  * @see java.nio.charset.spi.CharsetProvider
272  * @see java.lang.Character
273  */
274 
275 public abstract class Charset
276     implements Comparable<Charset>
277 {
278 
279     /* -- Static methods -- */
280 
281     /**
282      * Checks that the given string is a legal charset name. </p>
283      *
284      * @param  s
285      *         A purported charset name
286      *
287      * @throws  IllegalCharsetNameException
288      *          If the given name is not a legal charset name
289      */
290     private static void checkName(String s) {
291         int n = s.length();
292         if (n == 0) {
293             throw new IllegalCharsetNameException(s);
294         }
295         for (int i = 0; i < n; i++) {
296             char c = s.charAt(i);
297             if (c >= 'A' && c <= 'Z') continue;
298             if (c >= 'a' && c <= 'z') continue;
299             if (c >= '0' && c <= '9') continue;
300             if (c == '-' && i != 0) continue;
301             if (c == '+' && i != 0) continue;
302             if (c == ':' && i != 0) continue;
303             if (c == '_' && i != 0) continue;
304             if (c == '.' && i != 0) continue;
305             throw new IllegalCharsetNameException(s);
306         }
307     }
308 
309     /* The standard set of charsets */
310     private static final CharsetProvider standardProvider
311         = new sun.nio.cs.StandardCharsets();
312 
313     private static final String[] zeroAliases = new String[0];
314 
315     // Cache of the most-recently-returned charsets,
316     // along with the names that were used to find them
317     //
318     private static volatile Object[] cache1; // "Level 1" cache
319     private static volatile Object[] cache2; // "Level 2" cache
320 
321     private static void cache(String charsetName, Charset cs) {
322         cache2 = cache1;
323         cache1 = new Object[] { charsetName, cs };
324     }
325 
326     // Creates an iterator that walks over the available providers, ignoring
327     // those whose lookup or instantiation causes a security exception to be
328     // thrown.  Should be invoked with full privileges.
329     //
330     private static Iterator<CharsetProvider> providers() {
331         return new Iterator<>() {
332                 ClassLoader cl = ClassLoader.getSystemClassLoader();
333                 ServiceLoader<CharsetProvider> sl =
334                     ServiceLoader.load(CharsetProvider.class, cl);
335                 Iterator<CharsetProvider> i = sl.iterator();
336                 CharsetProvider next = null;
337 
338                 private boolean getNext() {
339                     while (next == null) {
340                         try {
341                             if (!i.hasNext())
342                                 return false;
343                             next = i.next();
344                         } catch (ServiceConfigurationError sce) {
345                             if (sce.getCause() instanceof SecurityException) {
346                                 // Ignore security exceptions
347                                 continue;
348                             }
349                             throw sce;
350                         }
351                     }
352                     return true;
353                 }
354 
355                 public boolean hasNext() {
356                     return getNext();
357                 }
358 
359                 public CharsetProvider next() {
360                     if (!getNext())
361                         throw new NoSuchElementException();
362                     CharsetProvider n = next;
363                     next = null;
364                     return n;
365                 }
366 
367                 public void remove() {
368                     throw new UnsupportedOperationException();
369                 }
370 
371             };
372     }
373 
374     // gate to prevent recursive provider lookups
375     private static class Holder {
376         static final Gate LOOKUP_GATE = Gate.create();
377     }
378 
379     private static Gate gate() {
380         return Holder.LOOKUP_GATE;
381     }
382 
383     @SuppressWarnings("removal")
384     private static Charset lookupViaProviders(final String charsetName) {
385 
386         // The runtime startup sequence looks up standard charsets as a
387         // consequence of the VM's invocation of System.initializeSystemClass
388         // in order to, e.g., set system properties and encode filenames.  At
389         // that point the application class loader has not been initialized,
390         // however, so we can't look for providers because doing so will cause
391         // that loader to be prematurely initialized with incomplete
392         // information.
393         //
394         if (!VM.isBooted())
395             return null;
396 
397         if (!gate().tryEnter())
398             // Avoid recursive provider lookups
399             return null;
400         try {


401             return AccessController.doPrivileged(
402                 new PrivilegedAction<>() {
403                     public Charset run() {
404                         for (Iterator<CharsetProvider> i = providers();
405                              i.hasNext();) {
406                             CharsetProvider cp = i.next();
407                             Charset cs = cp.charsetForName(charsetName);
408                             if (cs != null)
409                                 return cs;
410                         }
411                         return null;
412                     }
413                 });
414 
415         } finally {
416             gate().exit();
417         }
418     }
419 
420     /* The extended set of charsets */
421     private static class ExtendedProviderHolder {
422         static final CharsetProvider[] extendedProviders = extendedProviders();
423         // returns ExtendedProvider, if installed
424         @SuppressWarnings("removal")
425         private static CharsetProvider[] extendedProviders() {
426             return AccessController.doPrivileged(new PrivilegedAction<>() {
427                     public CharsetProvider[] run() {
428                         CharsetProvider[] cps = new CharsetProvider[1];
429                         int n = 0;
430                         ServiceLoader<CharsetProvider> sl =
431                             ServiceLoader.loadInstalled(CharsetProvider.class);
432                         for (CharsetProvider cp : sl) {
433                             if (n + 1 > cps.length) {
434                                 cps = Arrays.copyOf(cps, cps.length << 1);
435                             }
436                             cps[n++] = cp;
437                         }
438                         return n == cps.length ? cps : Arrays.copyOf(cps, n);
439                     }});
440         }
441     }
442 
443     private static Charset lookupExtendedCharset(String charsetName) {
444         if (!VM.isBooted())  // see lookupViaProviders()
445             return null;
446         CharsetProvider[] ecps = ExtendedProviderHolder.extendedProviders;
447         for (CharsetProvider cp : ecps) {
448             Charset cs = cp.charsetForName(charsetName);
449             if (cs != null)
450                 return cs;
451         }
452         return null;
453     }
454 
455     private static Charset lookup(String charsetName) {
456         if (charsetName == null)
457             throw new IllegalArgumentException("Null charset name");
458         Object[] a;
459         if ((a = cache1) != null && charsetName.equals(a[0]))
460             return (Charset)a[1];
461         // We expect most programs to use one Charset repeatedly.
462         // We convey a hint to this effect to the VM by putting the
463         // level 1 cache miss code in a separate method.
464         return lookup2(charsetName);
465     }
466 
467     private static Charset lookup2(String charsetName) {
468         Object[] a;
469         if ((a = cache2) != null && charsetName.equals(a[0])) {
470             cache2 = cache1;
471             cache1 = a;
472             return (Charset)a[1];
473         }
474         Charset cs;
475         if ((cs = standardProvider.charsetForName(charsetName)) != null ||
476             (cs = lookupExtendedCharset(charsetName))           != null ||
477             (cs = lookupViaProviders(charsetName))              != null)
478         {
479             cache(charsetName, cs);
480             return cs;
481         }
482 
483         /* Only need to check the name if we didn't find a charset for it */
484         checkName(charsetName);
485         return null;
486     }
487 
488     /**
489      * Tells whether the named charset is supported.
490      *
491      * @param  charsetName
492      *         The name of the requested charset; may be either
493      *         a canonical name or an alias
494      *
495      * @return  {@code true} if, and only if, support for the named charset
496      *          is available in the current Java virtual machine
497      *
498      * @throws IllegalCharsetNameException
499      *         If the given charset name is illegal
500      *
501      * @throws  IllegalArgumentException
502      *          If the given {@code charsetName} is null
503      */
504     public static boolean isSupported(String charsetName) {
505         return (lookup(charsetName) != null);
506     }
507 
508     /**
509      * Returns a charset object for the named charset.
510      *
511      * @param  charsetName
512      *         The name of the requested charset; may be either
513      *         a canonical name or an alias
514      *
515      * @return  A charset object for the named charset
516      *
517      * @throws  IllegalCharsetNameException
518      *          If the given charset name is illegal
519      *
520      * @throws  IllegalArgumentException
521      *          If the given {@code charsetName} is null
522      *
523      * @throws  UnsupportedCharsetException
524      *          If no support for the named charset is available
525      *          in this instance of the Java virtual machine
526      */
527     public static Charset forName(String charsetName) {
528         Charset cs = lookup(charsetName);
529         if (cs != null)
530             return cs;
531         throw new UnsupportedCharsetException(charsetName);
532     }
533 
534     /**
535      * Returns a charset object for the named charset. If the charset object
536      * for the named charset is not available or {@code charsetName} is not a
537      * legal charset name, then {@code fallback} is returned.
538      *
539      * @param  charsetName
540      *         The name of the requested charset; may be either
541      *         a canonical name or an alias
542      *
543      * @param  fallback
544      *         fallback charset in case the charset object for the named
545      *         charset is not available or {@code charsetName} is not a legal
546      *         charset name. May be {@code null}
547      *
548      * @return  A charset object for the named charset, or {@code fallback}
549      *          in case the charset object for the named charset is not
550      *          available or {@code charsetName} is not a legal charset name
551      *
552      * @throws  IllegalArgumentException
553      *          If the given {@code charsetName} is {@code null}
554      *
555      * @since 18
556      */
557     public static Charset forName(String charsetName,
558                                   Charset fallback) {
559         try {
560             Charset cs = lookup(charsetName);
561             return cs != null ? cs : fallback;
562         } catch (IllegalCharsetNameException icne) {
563             return fallback;
564         }
565     }
566 
567     // Fold charsets from the given iterator into the given map, ignoring
568     // charsets whose names already have entries in the map.
569     //
570     private static void put(Iterator<Charset> i, Map<String,Charset> m) {
571         while (i.hasNext()) {
572             Charset cs = i.next();
573             if (!m.containsKey(cs.name()))
574                 m.put(cs.name(), cs);
575         }
576     }
577 
578     /**
579      * Constructs a sorted map from canonical charset names to charset objects.
580      *
581      * <p> The map returned by this method will have one entry for each charset
582      * for which support is available in the current Java virtual machine.  If
583      * two or more supported charsets have the same canonical name then the
584      * resulting map will contain just one of them; which one it will contain
585      * is not specified. </p>
586      *
587      * <p> The invocation of this method, and the subsequent use of the
588      * resulting map, may cause time-consuming disk or network I/O operations
589      * to occur.  This method is provided for applications that need to
590      * enumerate all of the available charsets, for example to allow user
591      * charset selection.  This method is not used by the {@link #forName
592      * forName} method, which instead employs an efficient incremental lookup
593      * algorithm.
594      *
595      * <p> This method may return different results at different times if new
596      * charset providers are dynamically made available to the current Java
597      * virtual machine.  In the absence of such changes, the charsets returned
598      * by this method are exactly those that can be retrieved via the {@link
599      * #forName forName} method.  </p>
600      *
601      * @return An immutable, case-insensitive map from canonical charset names
602      *         to charset objects
603      */
604     @SuppressWarnings("removal")
605     public static SortedMap<String,Charset> availableCharsets() {
606         return AccessController.doPrivileged(
607             new PrivilegedAction<>() {
608                 public SortedMap<String,Charset> run() {
609                     TreeMap<String,Charset> m =
610                         new TreeMap<>(
611                             String.CASE_INSENSITIVE_ORDER);
612                     put(standardProvider.charsets(), m);
613                     CharsetProvider[] ecps = ExtendedProviderHolder.extendedProviders;
614                     for (CharsetProvider ecp :ecps) {
615                         put(ecp.charsets(), m);
616                     }
617                     for (Iterator<CharsetProvider> i = providers(); i.hasNext();) {
618                         CharsetProvider cp = i.next();
619                         put(cp.charsets(), m);
620                     }
621                     return Collections.unmodifiableSortedMap(m);
622                 }
623             });
624     }
625 
626     private static volatile Charset defaultCharset;
627 
628     /**
629      * Returns the default charset of this Java virtual machine.
630      *
631      * <p> The default charset is {@code UTF-8}, unless changed in an
632      * implementation specific manner.
633      *
634      * @implNote An implementation may override the default charset with
635      * the system property {@code file.encoding} on the command line. If the
636      * value is {@code COMPAT}, the default charset is derived from
637      * the {@code native.encoding} system property, which typically depends
638      * upon the locale and charset of the underlying operating system.
639      *
640      * @return  A charset object for the default charset
641      * @see <a href="../../lang/System.html#file.encoding">file.encoding</a>
642      * @see <a href="../../lang/System.html#native.encoding">native.encoding</a>
643      *
644      * @since 1.5
645      */
646     public static Charset defaultCharset() {
647         if (defaultCharset == null) {
648             synchronized (Charset.class) {
649                 String csn = GetPropertyAction
650                         .privilegedGetProperty("file.encoding");
651                 Charset cs = lookup(csn);
652                 if (cs != null)
653                     defaultCharset = cs;
654                 else
655                     defaultCharset = sun.nio.cs.UTF_8.INSTANCE;
656             }
657         }
658         return defaultCharset;
659     }
660 
661 
662     /* -- Instance fields and methods -- */
663 
664     private final String name;          // tickles a bug in oldjavac
665     private final String[] aliases;     // tickles a bug in oldjavac
666     private Set<String> aliasSet = null;
667 
668     /**
669      * Initializes a new charset with the given canonical name and alias
670      * set.
671      *
672      * @param  canonicalName
673      *         The canonical name of this charset
674      *
675      * @param  aliases
676      *         An array of this charset's aliases, or null if it has no aliases
677      *
678      * @throws IllegalCharsetNameException
679      *         If the canonical name or any of the aliases are illegal
680      */
681     protected Charset(String canonicalName, String[] aliases) {
682         String[] as = Objects.requireNonNullElse(aliases, zeroAliases);
683 
684         // Skip checks for the standard, built-in Charsets we always load
685         // during initialization.
686         if (canonicalName != "ISO-8859-1"
687                 && canonicalName != "US-ASCII"
688                 && canonicalName != "UTF-8") {
689             checkName(canonicalName);
690             for (int i = 0; i < as.length; i++) {
691                 checkName(as[i]);
692             }
693         }
694         this.name = canonicalName;
695         this.aliases = as;
696     }
697 
698     /**
699      * Returns this charset's canonical name.
700      *
701      * @return  The canonical name of this charset
702      */
703     public final String name() {
704         return name;
705     }
706 
707     /**
708      * Returns a set containing this charset's aliases.
709      *
710      * @return  An immutable set of this charset's aliases
711      */
712     public final Set<String> aliases() {
713         if (aliasSet != null)
714             return aliasSet;
715         int n = aliases.length;
716         HashSet<String> hs = new HashSet<>(n);
717         for (int i = 0; i < n; i++)
718             hs.add(aliases[i]);
719         aliasSet = Collections.unmodifiableSet(hs);
720         return aliasSet;
721     }
722 
723     /**
724      * Returns this charset's human-readable name for the default locale.
725      *
726      * <p> The default implementation of this method simply returns this
727      * charset's canonical name.  Concrete subclasses of this class may
728      * override this method in order to provide a localized display name. </p>
729      *
730      * @return  The display name of this charset in the default locale
731      */
732     public String displayName() {
733         return name;
734     }
735 
736     /**
737      * Tells whether or not this charset is registered in the <a
738      * href="http://www.iana.org/assignments/character-sets">IANA Charset
739      * Registry</a>.
740      *
741      * @return  {@code true} if, and only if, this charset is known by its
742      *          implementor to be registered with the IANA
743      */
744     public final boolean isRegistered() {
745         return !name.startsWith("X-") && !name.startsWith("x-");
746     }
747 
748     /**
749      * Returns this charset's human-readable name for the given locale.
750      *
751      * <p> The default implementation of this method simply returns this
752      * charset's canonical name.  Concrete subclasses of this class may
753      * override this method in order to provide a localized display name. </p>
754      *
755      * @param  locale
756      *         The locale for which the display name is to be retrieved
757      *
758      * @return  The display name of this charset in the given locale
759      */
760     public String displayName(Locale locale) {
761         return name;
762     }
763 
764     /**
765      * Tells whether or not this charset contains the given charset.
766      *
767      * <p> A charset <i>C</i> is said to <i>contain</i> a charset <i>D</i> if,
768      * and only if, every character representable in <i>D</i> is also
769      * representable in <i>C</i>.  If this relationship holds then it is
770      * guaranteed that every string that can be encoded in <i>D</i> can also be
771      * encoded in <i>C</i> without performing any replacements.
772      *
773      * <p> That <i>C</i> contains <i>D</i> does not imply that each character
774      * representable in <i>C</i> by a particular byte sequence is represented
775      * in <i>D</i> by the same byte sequence, although sometimes this is the
776      * case.
777      *
778      * <p> Every charset contains itself.
779      *
780      * <p> This method computes an approximation of the containment relation:
781      * If it returns {@code true} then the given charset is known to be
782      * contained by this charset; if it returns {@code false}, however, then
783      * it is not necessarily the case that the given charset is not contained
784      * in this charset.
785      *
786      * @param   cs
787      *          The given charset
788      *
789      * @return  {@code true} if the given charset is contained in this charset
790      */
791     public abstract boolean contains(Charset cs);
792 
793     /**
794      * Constructs a new decoder for this charset.
795      *
796      * @return  A new decoder for this charset
797      */
798     public abstract CharsetDecoder newDecoder();
799 
800     /**
801      * Constructs a new encoder for this charset.
802      *
803      * @return  A new encoder for this charset
804      *
805      * @throws  UnsupportedOperationException
806      *          If this charset does not support encoding
807      */
808     public abstract CharsetEncoder newEncoder();
809 
810     /**
811      * Tells whether or not this charset supports encoding.
812      *
813      * <p> Nearly all charsets support encoding.  The primary exceptions are
814      * special-purpose <i>auto-detect</i> charsets whose decoders can determine
815      * which of several possible encoding schemes is in use by examining the
816      * input byte sequence.  Such charsets do not support encoding because
817      * there is no way to determine which encoding should be used on output.
818      * Implementations of such charsets should override this method to return
819      * {@code false}. </p>
820      *
821      * @return  {@code true} if, and only if, this charset supports encoding
822      */
823     public boolean canEncode() {
824         return true;
825     }
826 
827     /**
828      * Convenience method that decodes bytes in this charset into Unicode
829      * characters.
830      *
831      * <p> An invocation of this method upon a charset {@code cs} returns the
832      * same result as the expression
833      *
834      * <pre>
835      *     cs.newDecoder()
836      *       .onMalformedInput(CodingErrorAction.REPLACE)
837      *       .onUnmappableCharacter(CodingErrorAction.REPLACE)
838      *       .decode(bb); </pre>
839      *
840      * except that it is potentially more efficient because it can cache
841      * decoders between successive invocations.
842      *
843      * <p> This method always replaces malformed-input and unmappable-character
844      * sequences with this charset's default replacement byte array.  In order
845      * to detect such sequences, use the {@link
846      * CharsetDecoder#decode(java.nio.ByteBuffer)} method directly.  </p>
847      *
848      * @param  bb  The byte buffer to be decoded
849      *
850      * @return  A char buffer containing the decoded characters
851      */
852     public final CharBuffer decode(ByteBuffer bb) {
853         try {
854             return ThreadLocalCoders.decoderFor(this)
855                 .onMalformedInput(CodingErrorAction.REPLACE)
856                 .onUnmappableCharacter(CodingErrorAction.REPLACE)
857                 .decode(bb);
858         } catch (CharacterCodingException x) {
859             throw new Error(x);         // Can't happen
860         }
861     }
862 
863     /**
864      * Convenience method that encodes Unicode characters into bytes in this
865      * charset.
866      *
867      * <p> An invocation of this method upon a charset {@code cs} returns the
868      * same result as the expression
869      *
870      * <pre>
871      *     cs.newEncoder()
872      *       .onMalformedInput(CodingErrorAction.REPLACE)
873      *       .onUnmappableCharacter(CodingErrorAction.REPLACE)
874      *       .encode(bb); </pre>
875      *
876      * except that it is potentially more efficient because it can cache
877      * encoders between successive invocations.
878      *
879      * <p> This method always replaces malformed-input and unmappable-character
880      * sequences with this charset's default replacement string.  In order to
881      * detect such sequences, use the {@link
882      * CharsetEncoder#encode(java.nio.CharBuffer)} method directly.  </p>
883      *
884      * @param  cb  The char buffer to be encoded
885      *
886      * @return  A byte buffer containing the encoded characters
887      */
888     public final ByteBuffer encode(CharBuffer cb) {
889         try {
890             return ThreadLocalCoders.encoderFor(this)
891                 .onMalformedInput(CodingErrorAction.REPLACE)
892                 .onUnmappableCharacter(CodingErrorAction.REPLACE)
893                 .encode(cb);
894         } catch (CharacterCodingException x) {
895             throw new Error(x);         // Can't happen
896         }
897     }
898 
899     /**
900      * Convenience method that encodes a string into bytes in this charset.
901      *
902      * <p> An invocation of this method upon a charset {@code cs} returns the
903      * same result as the expression
904      *
905      * <pre>
906      *     cs.encode(CharBuffer.wrap(s)); </pre>
907      *
908      * @param  str  The string to be encoded
909      *
910      * @return  A byte buffer containing the encoded characters
911      */
912     public final ByteBuffer encode(String str) {
913         return encode(CharBuffer.wrap(str));
914     }
915 
916     /**
917      * Compares this charset to another.
918      *
919      * <p> Charsets are ordered by their canonical names, without regard to
920      * case. </p>
921      *
922      * @param  that
923      *         The charset to which this charset is to be compared
924      *
925      * @return A negative integer, zero, or a positive integer as this charset
926      *         is less than, equal to, or greater than the specified charset
927      */
928     public final int compareTo(Charset that) {
929         return (name().compareToIgnoreCase(that.name()));
930     }
931 
932     /**
933      * Computes a hashcode for this charset.
934      *
935      * @return  An integer hashcode
936      */
937     public final int hashCode() {
938         return name().hashCode();
939     }
940 
941     /**
942      * Tells whether or not this object is equal to another.
943      *
944      * <p> Two charsets are equal if, and only if, they have the same canonical
945      * names.  A charset is never equal to any other type of object.  </p>
946      *
947      * @return  {@code true} if, and only if, this charset is equal to the
948      *          given object
949      */
950     public final boolean equals(Object ob) {
951         if (!(ob instanceof Charset))
952             return false;
953         if (this == ob)
954             return true;
955         return name.equals(((Charset)ob).name());
956     }
957 
958     /**
959      * Returns a string describing this charset.
960      *
961      * @return  A string describing this charset
962      */
963     public final String toString() {
964         return name();
965     }
966 
967 }
--- EOF ---