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





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