1 /*
   2  * Copyright (c) 2000, 2017, 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.StandardCharsets;
  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  * <a id="names"></a><a id="charenc"></a>
  72  * <h2>Charset names</h2>
  73  *
  74  * <p> Charsets are named by strings composed of the following characters:
  75  *
  76  * <ul>
  77  *
  78  *   <li> The uppercase letters {@code 'A'} through {@code 'Z'}
  79  *        (<code>'\u0041'</code>&nbsp;through&nbsp;<code>'\u005a'</code>),
  80  *
  81  *   <li> The lowercase letters {@code 'a'} through {@code 'z'}
  82  *        (<code>'\u0061'</code>&nbsp;through&nbsp;<code>'\u007a'</code>),
  83  *
  84  *   <li> The digits {@code '0'} through {@code '9'}
  85  *        (<code>'\u0030'</code>&nbsp;through&nbsp;<code>'\u0039'</code>),
  86  *
  87  *   <li> The dash character {@code '-'}
  88  *        (<code>'\u002d'</code>,&nbsp;<small>HYPHEN-MINUS</small>),
  89  *
  90  *   <li> The plus character {@code '+'}
  91  *        (<code>'\u002b'</code>,&nbsp;<small>PLUS SIGN</small>),
  92  *
  93  *   <li> The period character {@code '.'}
  94  *        (<code>'\u002e'</code>,&nbsp;<small>FULL STOP</small>),
  95  *
  96  *   <li> The colon character {@code ':'}
  97  *        (<code>'\u003a'</code>,&nbsp;<small>COLON</small>), and
  98  *
  99  *   <li> The underscore character {@code '_'}
 100  *        (<code>'\u005f'</code>,&nbsp;<small>LOW&nbsp;LINE</small>).
 101  *
 102  * </ul>
 103  *
 104  * A charset name must begin with either a letter or a digit.  The empty string
 105  * is not a legal charset name.  Charset names are not case-sensitive; that is,
 106  * case is always ignored when comparing charset names.  Charset names
 107  * generally follow the conventions documented in <a
 108  * href="http://www.ietf.org/rfc/rfc2278.txt"><i>RFC&nbsp;2278:&nbsp;IANA Charset
 109  * Registration Procedures</i></a>.
 110  *
 111  * <p> Every charset has a <i>canonical name</i> and may also have one or more
 112  * <i>aliases</i>.  The canonical name is returned by the {@link #name() name} method
 113  * of this class.  Canonical names are, by convention, usually in upper case.
 114  * The aliases of a charset are returned by the {@link #aliases() aliases}
 115  * method.
 116  *
 117  * <p><a id="hn">Some charsets have an <i>historical name</i> that is defined for
 118  * compatibility with previous versions of the Java platform.</a>  A charset's
 119  * historical name is either its canonical name or one of its aliases.  The
 120  * historical name is returned by the {@code getEncoding()} methods of the
 121  * {@link java.io.InputStreamReader#getEncoding InputStreamReader} and {@link
 122  * java.io.OutputStreamWriter#getEncoding OutputStreamWriter} classes.
 123  *
 124  * <p><a id="iana"> </a>If a charset listed in the <a
 125  * href="http://www.iana.org/assignments/character-sets"><i>IANA Charset
 126  * Registry</i></a> is supported by an implementation of the Java platform then
 127  * its canonical name must be the name listed in the registry. Many charsets
 128  * are given more than one name in the registry, in which case the registry
 129  * identifies one of the names as <i>MIME-preferred</i>.  If a charset has more
 130  * than one registry name then its canonical name must be the MIME-preferred
 131  * name and the other names in the registry must be valid aliases.  If a
 132  * supported charset is not listed in the IANA registry then its canonical name
 133  * must begin with one of the strings {@code "X-"} or {@code "x-"}.
 134  *
 135  * <p> The IANA charset registry does change over time, and so the canonical
 136  * name and the aliases of a particular charset may also change over time.  To
 137  * ensure compatibility it is recommended that no alias ever be removed from a
 138  * charset, and that if the canonical name of a charset is changed then its
 139  * previous canonical name be made into an alias.
 140  *
 141  *
 142  * <h2>Standard charsets</h2>
 143  *
 144  *
 145  *
 146  * <p><a id="standard">Every implementation of the Java platform is required to support the
 147  * following standard charsets.</a>  Consult the release documentation for your
 148  * implementation to see if any other charsets are supported.  The behavior
 149  * of such optional charsets may differ between implementations.
 150  *
 151  * <blockquote><table class="striped" style="width:80%">
 152  * <caption style="display:none">Description of standard charsets</caption>
 153  * <thead>
 154  * <tr><th scope="col" style="text-align:left">Charset</th><th scope="col" style="text-align:left">Description</th></tr>
 155  * </thead>
 156  * <tbody>
 157  * <tr><th scope="row" style="vertical-align:top">{@code US-ASCII}</th>
 158  *     <td>Seven-bit ASCII, a.k.a. {@code ISO646-US},
 159  *         a.k.a. the Basic Latin block of the Unicode character set</td></tr>
 160  * <tr><th scope="row" style="vertical-align:top"><code>ISO-8859-1&nbsp;&nbsp;</code></th>
 161  *     <td>ISO Latin Alphabet No. 1, a.k.a. {@code ISO-LATIN-1}</td></tr>
 162  * <tr><th scope="row" style="vertical-align:top">{@code UTF-8}</th>
 163  *     <td>Eight-bit UCS Transformation Format</td></tr>
 164  * <tr><th scope="row" style="vertical-align:top">{@code UTF-16BE}</th>
 165  *     <td>Sixteen-bit UCS Transformation Format,
 166  *         big-endian byte&nbsp;order</td></tr>
 167  * <tr><th scope="row" style="vertical-align:top">{@code UTF-16LE}</th>
 168  *     <td>Sixteen-bit UCS Transformation Format,
 169  *         little-endian byte&nbsp;order</td></tr>
 170  * <tr><th scope="row" style="vertical-align:top">{@code UTF-16}</th>
 171  *     <td>Sixteen-bit UCS Transformation Format,
 172  *         byte&nbsp;order identified by an optional byte-order mark</td></tr>
 173  * </tbody>
 174  * </table></blockquote>
 175  *
 176  * <p> The {@code UTF-8} charset is specified by <a
 177  * href="http://www.ietf.org/rfc/rfc2279.txt"><i>RFC&nbsp;2279</i></a>; the
 178  * transformation format upon which it is based is specified in
 179  * Amendment&nbsp;2 of ISO&nbsp;10646-1 and is also described in the <a
 180  * href="http://www.unicode.org/unicode/standard/standard.html"><i>Unicode
 181  * Standard</i></a>.
 182  *
 183  * <p> The {@code UTF-16} charsets are specified by <a
 184  * href="http://www.ietf.org/rfc/rfc2781.txt"><i>RFC&nbsp;2781</i></a>; the
 185  * transformation formats upon which they are based are specified in
 186  * Amendment&nbsp;1 of ISO&nbsp;10646-1 and are also described in the <a
 187  * href="http://www.unicode.org/unicode/standard/standard.html"><i>Unicode
 188  * Standard</i></a>.
 189  *
 190  * <p> The {@code UTF-16} charsets use sixteen-bit quantities and are
 191  * therefore sensitive to byte order.  In these encodings the byte order of a
 192  * stream may be indicated by an initial <i>byte-order mark</i> represented by
 193  * the Unicode character <code>'\uFEFF'</code>.  Byte-order marks are handled
 194  * as follows:
 195  *
 196  * <ul>
 197  *
 198  *   <li><p> When decoding, the {@code UTF-16BE} and {@code UTF-16LE}
 199  *   charsets interpret the initial byte-order marks as a <small>ZERO-WIDTH
 200  *   NON-BREAKING SPACE</small>; when encoding, they do not write
 201  *   byte-order marks. </p></li>
 202 
 203  *
 204  *   <li><p> When decoding, the {@code UTF-16} charset interprets the
 205  *   byte-order mark at the beginning of the input stream to indicate the
 206  *   byte-order of the stream but defaults to big-endian if there is no
 207  *   byte-order mark; when encoding, it uses big-endian byte order and writes
 208  *   a big-endian byte-order mark. </p></li>
 209  *
 210  * </ul>
 211  *
 212  * In any case, byte order marks occurring after the first element of an
 213  * input sequence are not omitted since the same code is used to represent
 214  * <small>ZERO-WIDTH NON-BREAKING SPACE</small>.
 215  *
 216  * <p> Every instance of the Java virtual machine has a default charset, which
 217  * may or may not be one of the standard charsets.  The default charset is
 218  * determined during virtual-machine startup and typically depends upon the
 219  * locale and charset being used by the underlying operating system. </p>
 220  *
 221  * <p>The {@link StandardCharsets} class defines constants for each of the
 222  * standard charsets.
 223  *
 224  * <h2>Terminology</h2>
 225  *
 226  * <p> The name of this class is taken from the terms used in
 227  * <a href="http://www.ietf.org/rfc/rfc2278.txt"><i>RFC&nbsp;2278</i></a>.
 228  * In that document a <i>charset</i> is defined as the combination of
 229  * one or more coded character sets and a character-encoding scheme.
 230  * (This definition is confusing; some other software systems define
 231  * <i>charset</i> as a synonym for <i>coded character set</i>.)
 232  *
 233  * <p> A <i>coded character set</i> is a mapping between a set of abstract
 234  * characters and a set of integers.  US-ASCII, ISO&nbsp;8859-1,
 235  * JIS&nbsp;X&nbsp;0201, and Unicode are examples of coded character sets.
 236  *
 237  * <p> Some standards have defined a <i>character set</i> to be simply a
 238  * set of abstract characters without an associated assigned numbering.
 239  * An alphabet is an example of such a character set.  However, the subtle
 240  * distinction between <i>character set</i> and <i>coded character set</i>
 241  * is rarely used in practice; the former has become a short form for the
 242  * latter, including in the Java API specification.
 243  *
 244  * <p> A <i>character-encoding scheme</i> is a mapping between one or more
 245  * coded character sets and a set of octet (eight-bit byte) sequences.
 246  * UTF-8, UTF-16, ISO&nbsp;2022, and EUC are examples of
 247  * character-encoding schemes.  Encoding schemes are often associated with
 248  * a particular coded character set; UTF-8, for example, is used only to
 249  * encode Unicode.  Some schemes, however, are associated with multiple
 250  * coded character sets; EUC, for example, can be used to encode
 251  * characters in a variety of Asian coded character sets.
 252  *
 253  * <p> When a coded character set is used exclusively with a single
 254  * character-encoding scheme then the corresponding charset is usually
 255  * named for the coded character set; otherwise a charset is usually named
 256  * for the encoding scheme and, possibly, the locale of the coded
 257  * character sets that it supports.  Hence {@code US-ASCII} is both the
 258  * name of a coded character set and of the charset that encodes it, while
 259  * {@code EUC-JP} is the name of the charset that encodes the
 260  * JIS&nbsp;X&nbsp;0201, JIS&nbsp;X&nbsp;0208, and JIS&nbsp;X&nbsp;0212
 261  * coded character sets for the Japanese language.
 262  *
 263  * <p> The native character encoding of the Java programming language is
 264  * UTF-16.  A charset in the Java platform therefore defines a mapping
 265  * between sequences of sixteen-bit UTF-16 code units (that is, sequences
 266  * of chars) and sequences of bytes. </p>
 267  *
 268  *
 269  * @author Mark Reinhold
 270  * @author JSR-51 Expert Group
 271  * @since 1.4
 272  *
 273  * @see CharsetDecoder
 274  * @see CharsetEncoder
 275  * @see java.nio.charset.spi.CharsetProvider
 276  * @see java.lang.Character
 277  */
 278 
 279 public abstract class Charset
 280     implements Comparable<Charset>
 281 {
 282 
 283     /* -- Static methods -- */
 284 
 285     /**
 286      * Checks that the given string is a legal charset name. </p>
 287      *
 288      * @param  s
 289      *         A purported charset name
 290      *
 291      * @throws  IllegalCharsetNameException
 292      *          If the given name is not a legal charset name
 293      */
 294     private static void checkName(String s) {
 295         int n = s.length();
 296         if (n == 0) {
 297             throw new IllegalCharsetNameException(s);
 298         }
 299         for (int i = 0; i < n; i++) {
 300             char c = s.charAt(i);
 301             if (c >= 'A' && c <= 'Z') continue;
 302             if (c >= 'a' && c <= 'z') continue;
 303             if (c >= '0' && c <= '9') continue;
 304             if (c == '-' && i != 0) continue;
 305             if (c == '+' && i != 0) continue;
 306             if (c == ':' && i != 0) continue;
 307             if (c == '_' && i != 0) continue;
 308             if (c == '.' && i != 0) continue;
 309             throw new IllegalCharsetNameException(s);
 310         }
 311     }
 312 
 313     /* The standard set of charsets */
 314     private static final CharsetProvider standardProvider = new StandardCharsets();
 315 
 316     private static final String[] zeroAliases = new String[0];
 317 
 318     // Cache of the most-recently-returned charsets,
 319     // along with the names that were used to find them
 320     //
 321     private static volatile Object[] cache1; // "Level 1" cache
 322     private static volatile Object[] cache2; // "Level 2" cache
 323 
 324     private static void cache(String charsetName, Charset cs) {
 325         cache2 = cache1;
 326         cache1 = new Object[] { charsetName, cs };
 327     }
 328 
 329     // Creates an iterator that walks over the available providers, ignoring
 330     // those whose lookup or instantiation causes a security exception to be
 331     // thrown.  Should be invoked with full privileges.
 332     //
 333     private static Iterator<CharsetProvider> providers() {
 334         return new Iterator<>() {
 335                 ClassLoader cl = ClassLoader.getSystemClassLoader();
 336                 ServiceLoader<CharsetProvider> sl =
 337                     ServiceLoader.load(CharsetProvider.class, cl);
 338                 Iterator<CharsetProvider> i = sl.iterator();
 339                 CharsetProvider next = null;
 340 
 341                 private boolean getNext() {
 342                     while (next == null) {
 343                         try {
 344                             if (!i.hasNext())
 345                                 return false;
 346                             next = i.next();
 347                         } catch (ServiceConfigurationError sce) {
 348                             if (sce.getCause() instanceof SecurityException) {
 349                                 // Ignore security exceptions
 350                                 continue;
 351                             }
 352                             throw sce;
 353                         }
 354                     }
 355                     return true;
 356                 }
 357 
 358                 public boolean hasNext() {
 359                     return getNext();
 360                 }
 361 
 362                 public CharsetProvider next() {
 363                     if (!getNext())
 364                         throw new NoSuchElementException();
 365                     CharsetProvider n = next;
 366                     next = null;
 367                     return n;
 368                 }
 369 
 370                 public void remove() {
 371                     throw new UnsupportedOperationException();
 372                 }
 373 
 374             };
 375     }
 376 
 377     // Thread-local gate to prevent recursive provider lookups
 378     private static ThreadLocal<ThreadLocal<?>> gate =
 379             new ThreadLocal<ThreadLocal<?>>();
 380 
 381     private static Charset lookupViaProviders(final String charsetName) {
 382 
 383         // The runtime startup sequence looks up standard charsets as a
 384         // consequence of the VM's invocation of System.initializeSystemClass
 385         // in order to, e.g., set system properties and encode filenames.  At
 386         // that point the application class loader has not been initialized,
 387         // however, so we can't look for providers because doing so will cause
 388         // that loader to be prematurely initialized with incomplete
 389         // information.
 390         //
 391         if (!VM.isBooted())
 392             return null;
 393 
 394         if (gate.get() != null)
 395             // Avoid recursive provider lookups
 396             return null;
 397         try {
 398             gate.set(gate);
 399 
 400             return AccessController.doPrivileged(
 401                 new PrivilegedAction<>() {
 402                     public Charset run() {
 403                         for (Iterator<CharsetProvider> i = providers();
 404                              i.hasNext();) {
 405                             CharsetProvider cp = i.next();
 406                             Charset cs = cp.charsetForName(charsetName);
 407                             if (cs != null)
 408                                 return cs;
 409                         }
 410                         return null;
 411                     }
 412                 });
 413 
 414         } finally {
 415             gate.set(null);
 416         }
 417     }
 418 
 419     /* The extended set of charsets */
 420     private static class ExtendedProviderHolder {
 421         static final CharsetProvider[] extendedProviders = extendedProviders();
 422         // returns ExtendedProvider, if installed
 423         private static CharsetProvider[] extendedProviders() {
 424             return AccessController.doPrivileged(new PrivilegedAction<>() {
 425                     public CharsetProvider[] run() {
 426                         CharsetProvider[] cps = new CharsetProvider[1];
 427                         int n = 0;
 428                         ServiceLoader<CharsetProvider> sl =
 429                             ServiceLoader.loadInstalled(CharsetProvider.class);
 430                         for (CharsetProvider cp : sl) {
 431                             if (n + 1 > cps.length) {
 432                                 cps = Arrays.copyOf(cps, cps.length << 1);
 433                             }
 434                             cps[n++] = cp;
 435                         }
 436                         return n == cps.length ? cps : Arrays.copyOf(cps, n);
 437                     }});
 438         }
 439     }
 440 
 441     private static Charset lookupExtendedCharset(String charsetName) {
 442         if (!VM.isBooted())  // see lookupViaProviders()
 443             return null;
 444         CharsetProvider[] ecps = ExtendedProviderHolder.extendedProviders;
 445         for (CharsetProvider cp : ecps) {
 446             Charset cs = cp.charsetForName(charsetName);
 447             if (cs != null)
 448                 return cs;
 449         }
 450         return null;
 451     }
 452 
 453     private static Charset lookup(String charsetName) {
 454         if (charsetName == null)
 455             throw new IllegalArgumentException("Null charset name");
 456         Object[] a;
 457         if ((a = cache1) != null && charsetName.equals(a[0]))
 458             return (Charset)a[1];
 459         // We expect most programs to use one Charset repeatedly.
 460         // We convey a hint to this effect to the VM by putting the
 461         // level 1 cache miss code in a separate method.
 462         return lookup2(charsetName);
 463     }
 464 
 465     private static Charset lookup2(String charsetName) {
 466         Object[] a;
 467         if ((a = cache2) != null && charsetName.equals(a[0])) {
 468             cache2 = cache1;
 469             cache1 = a;
 470             return (Charset)a[1];
 471         }
 472         Charset cs;
 473         if ((cs = standardProvider.charsetForName(charsetName)) != null ||
 474             (cs = lookupExtendedCharset(charsetName))           != null ||
 475             (cs = lookupViaProviders(charsetName))              != null)
 476         {
 477             cache(charsetName, cs);
 478             return cs;
 479         }
 480 
 481         /* Only need to check the name if we didn't find a charset for it */
 482         checkName(charsetName);
 483         return null;
 484     }
 485 
 486     /**
 487      * Tells whether the named charset is supported.
 488      *
 489      * @param  charsetName
 490      *         The name of the requested charset; may be either
 491      *         a canonical name or an alias
 492      *
 493      * @return  {@code true} if, and only if, support for the named charset
 494      *          is available in the current Java virtual machine
 495      *
 496      * @throws IllegalCharsetNameException
 497      *         If the given charset name is illegal
 498      *
 499      * @throws  IllegalArgumentException
 500      *          If the given {@code charsetName} is null
 501      */
 502     public static boolean isSupported(String charsetName) {
 503         return (lookup(charsetName) != null);
 504     }
 505 
 506     /**
 507      * Returns a charset object for the named charset.
 508      *
 509      * @param  charsetName
 510      *         The name of the requested charset; may be either
 511      *         a canonical name or an alias
 512      *
 513      * @return  A charset object for the named charset
 514      *
 515      * @throws  IllegalCharsetNameException
 516      *          If the given charset name is illegal
 517      *
 518      * @throws  IllegalArgumentException
 519      *          If the given {@code charsetName} is null
 520      *
 521      * @throws  UnsupportedCharsetException
 522      *          If no support for the named charset is available
 523      *          in this instance of the Java virtual machine
 524      */
 525     public static Charset forName(String charsetName) {
 526         Charset cs = lookup(charsetName);
 527         if (cs != null)
 528             return cs;
 529         throw new UnsupportedCharsetException(charsetName);
 530     }
 531 
 532     // Fold charsets from the given iterator into the given map, ignoring
 533     // charsets whose names already have entries in the map.
 534     //
 535     private static void put(Iterator<Charset> i, Map<String,Charset> m) {
 536         while (i.hasNext()) {
 537             Charset cs = i.next();
 538             if (!m.containsKey(cs.name()))
 539                 m.put(cs.name(), cs);
 540         }
 541     }
 542 
 543     /**
 544      * Constructs a sorted map from canonical charset names to charset objects.
 545      *
 546      * <p> The map returned by this method will have one entry for each charset
 547      * for which support is available in the current Java virtual machine.  If
 548      * two or more supported charsets have the same canonical name then the
 549      * resulting map will contain just one of them; which one it will contain
 550      * is not specified. </p>
 551      *
 552      * <p> The invocation of this method, and the subsequent use of the
 553      * resulting map, may cause time-consuming disk or network I/O operations
 554      * to occur.  This method is provided for applications that need to
 555      * enumerate all of the available charsets, for example to allow user
 556      * charset selection.  This method is not used by the {@link #forName
 557      * forName} method, which instead employs an efficient incremental lookup
 558      * algorithm.
 559      *
 560      * <p> This method may return different results at different times if new
 561      * charset providers are dynamically made available to the current Java
 562      * virtual machine.  In the absence of such changes, the charsets returned
 563      * by this method are exactly those that can be retrieved via the {@link
 564      * #forName forName} method.  </p>
 565      *
 566      * @return An immutable, case-insensitive map from canonical charset names
 567      *         to charset objects
 568      */
 569     public static SortedMap<String,Charset> availableCharsets() {
 570         return AccessController.doPrivileged(
 571             new PrivilegedAction<>() {
 572                 public SortedMap<String,Charset> run() {
 573                     TreeMap<String,Charset> m =
 574                         new TreeMap<>(
 575                             String.CASE_INSENSITIVE_ORDER);
 576                     put(standardProvider.charsets(), m);
 577                     CharsetProvider[] ecps = ExtendedProviderHolder.extendedProviders;
 578                     for (CharsetProvider ecp :ecps) {
 579                         put(ecp.charsets(), m);
 580                     }
 581                     for (Iterator<CharsetProvider> i = providers(); i.hasNext();) {
 582                         CharsetProvider cp = i.next();
 583                         put(cp.charsets(), m);
 584                     }
 585                     return Collections.unmodifiableSortedMap(m);
 586                 }
 587             });
 588     }
 589 
 590     private static volatile Charset defaultCharset;
 591 
 592     /**
 593      * Returns the default charset of this Java virtual machine.
 594      *
 595      * <p> The default charset is determined during virtual-machine startup and
 596      * typically depends upon the locale and charset of the underlying
 597      * operating system.
 598      *
 599      * @return  A charset object for the default charset
 600      *
 601      * @since 1.5
 602      */
 603     public static Charset defaultCharset() {
 604         if (defaultCharset == null) {
 605             synchronized (Charset.class) {
 606                 String csn = GetPropertyAction
 607                         .privilegedGetProperty("file.encoding");
 608                 Charset cs = lookup(csn);
 609                 if (cs != null)
 610                     defaultCharset = cs;
 611                 else
 612                     defaultCharset = forName("UTF-8");
 613             }
 614         }
 615         return defaultCharset;
 616     }
 617 
 618 
 619     /* -- Instance fields and methods -- */
 620 
 621     private final String name;          // tickles a bug in oldjavac
 622     private final String[] aliases;     // tickles a bug in oldjavac
 623     private Set<String> aliasSet = null;
 624 
 625     /**
 626      * Initializes a new charset with the given canonical name and alias
 627      * set.
 628      *
 629      * @param  canonicalName
 630      *         The canonical name of this charset
 631      *
 632      * @param  aliases
 633      *         An array of this charset's aliases, or null if it has no aliases
 634      *
 635      * @throws IllegalCharsetNameException
 636      *         If the canonical name or any of the aliases are illegal
 637      */
 638     protected Charset(String canonicalName, String[] aliases) {
 639         String[] as = Objects.requireNonNullElse(aliases, zeroAliases);
 640 
 641         // Skip checks for the standard, built-in Charsets we always load
 642         // during initialization.  Use of identity is intentional to be
 643         // consistent with sun.nio.cs.StandardCharsets
 644         if (canonicalName != StandardCharsets.ISO_8859_1
 645                 && canonicalName != StandardCharsets.US_ASCII
 646                 && canonicalName != StandardCharsets.UTF_8) {
 647             checkName(canonicalName);
 648             for (int i = 0; i < as.length; i++) {
 649                 checkName(as[i]);
 650             }
 651         }
 652         this.name = canonicalName;
 653         this.aliases = as;
 654     }
 655 
 656     /**
 657      * Returns this charset's canonical name.
 658      *
 659      * @return  The canonical name of this charset
 660      */
 661     public final String name() {
 662         return name;
 663     }
 664 
 665     /**
 666      * Returns a set containing this charset's aliases.
 667      *
 668      * @return  An immutable set of this charset's aliases
 669      */
 670     public final Set<String> aliases() {
 671         if (aliasSet != null)
 672             return aliasSet;
 673         int n = aliases.length;
 674         HashSet<String> hs = new HashSet<>(n);
 675         for (int i = 0; i < n; i++)
 676             hs.add(aliases[i]);
 677         aliasSet = Collections.unmodifiableSet(hs);
 678         return aliasSet;
 679     }
 680 
 681     /**
 682      * Returns this charset's human-readable name for the default locale.
 683      *
 684      * <p> The default implementation of this method simply returns this
 685      * charset's canonical name.  Concrete subclasses of this class may
 686      * override this method in order to provide a localized display name. </p>
 687      *
 688      * @return  The display name of this charset in the default locale
 689      */
 690     public String displayName() {
 691         return name;
 692     }
 693 
 694     /**
 695      * Tells whether or not this charset is registered in the <a
 696      * href="http://www.iana.org/assignments/character-sets">IANA Charset
 697      * Registry</a>.
 698      *
 699      * @return  {@code true} if, and only if, this charset is known by its
 700      *          implementor to be registered with the IANA
 701      */
 702     public final boolean isRegistered() {
 703         return !name.startsWith("X-") && !name.startsWith("x-");
 704     }
 705 
 706     /**
 707      * Returns this charset's human-readable name for the given locale.
 708      *
 709      * <p> The default implementation of this method simply returns this
 710      * charset's canonical name.  Concrete subclasses of this class may
 711      * override this method in order to provide a localized display name. </p>
 712      *
 713      * @param  locale
 714      *         The locale for which the display name is to be retrieved
 715      *
 716      * @return  The display name of this charset in the given locale
 717      */
 718     public String displayName(Locale locale) {
 719         return name;
 720     }
 721 
 722     /**
 723      * Tells whether or not this charset contains the given charset.
 724      *
 725      * <p> A charset <i>C</i> is said to <i>contain</i> a charset <i>D</i> if,
 726      * and only if, every character representable in <i>D</i> is also
 727      * representable in <i>C</i>.  If this relationship holds then it is
 728      * guaranteed that every string that can be encoded in <i>D</i> can also be
 729      * encoded in <i>C</i> without performing any replacements.
 730      *
 731      * <p> That <i>C</i> contains <i>D</i> does not imply that each character
 732      * representable in <i>C</i> by a particular byte sequence is represented
 733      * in <i>D</i> by the same byte sequence, although sometimes this is the
 734      * case.
 735      *
 736      * <p> Every charset contains itself.
 737      *
 738      * <p> This method computes an approximation of the containment relation:
 739      * If it returns {@code true} then the given charset is known to be
 740      * contained by this charset; if it returns {@code false}, however, then
 741      * it is not necessarily the case that the given charset is not contained
 742      * in this charset.
 743      *
 744      * @param   cs
 745      *          The given charset
 746      *
 747      * @return  {@code true} if the given charset is contained in this charset
 748      */
 749     public abstract boolean contains(Charset cs);
 750 
 751     /**
 752      * Constructs a new decoder for this charset.
 753      *
 754      * @return  A new decoder for this charset
 755      */
 756     public abstract CharsetDecoder newDecoder();
 757 
 758     /**
 759      * Constructs a new encoder for this charset.
 760      *
 761      * @return  A new encoder for this charset
 762      *
 763      * @throws  UnsupportedOperationException
 764      *          If this charset does not support encoding
 765      */
 766     public abstract CharsetEncoder newEncoder();
 767 
 768     /**
 769      * Tells whether or not this charset supports encoding.
 770      *
 771      * <p> Nearly all charsets support encoding.  The primary exceptions are
 772      * special-purpose <i>auto-detect</i> charsets whose decoders can determine
 773      * which of several possible encoding schemes is in use by examining the
 774      * input byte sequence.  Such charsets do not support encoding because
 775      * there is no way to determine which encoding should be used on output.
 776      * Implementations of such charsets should override this method to return
 777      * {@code false}. </p>
 778      *
 779      * @return  {@code true} if, and only if, this charset supports encoding
 780      */
 781     public boolean canEncode() {
 782         return true;
 783     }
 784 
 785     /**
 786      * Convenience method that decodes bytes in this charset into Unicode
 787      * characters.
 788      *
 789      * <p> An invocation of this method upon a charset {@code cs} returns the
 790      * same result as the expression
 791      *
 792      * <pre>
 793      *     cs.newDecoder()
 794      *       .onMalformedInput(CodingErrorAction.REPLACE)
 795      *       .onUnmappableCharacter(CodingErrorAction.REPLACE)
 796      *       .decode(bb); </pre>
 797      *
 798      * except that it is potentially more efficient because it can cache
 799      * decoders between successive invocations.
 800      *
 801      * <p> This method always replaces malformed-input and unmappable-character
 802      * sequences with this charset's default replacement byte array.  In order
 803      * to detect such sequences, use the {@link
 804      * CharsetDecoder#decode(java.nio.ByteBuffer)} method directly.  </p>
 805      *
 806      * @param  bb  The byte buffer to be decoded
 807      *
 808      * @return  A char buffer containing the decoded characters
 809      */
 810     public final CharBuffer decode(ByteBuffer bb) {
 811         try {
 812             return ThreadLocalCoders.decoderFor(this)
 813                 .onMalformedInput(CodingErrorAction.REPLACE)
 814                 .onUnmappableCharacter(CodingErrorAction.REPLACE)
 815                 .decode(bb);
 816         } catch (CharacterCodingException x) {
 817             throw new Error(x);         // Can't happen
 818         }
 819     }
 820 
 821     /**
 822      * Convenience method that encodes Unicode characters into bytes in this
 823      * charset.
 824      *
 825      * <p> An invocation of this method upon a charset {@code cs} returns the
 826      * same result as the expression
 827      *
 828      * <pre>
 829      *     cs.newEncoder()
 830      *       .onMalformedInput(CodingErrorAction.REPLACE)
 831      *       .onUnmappableCharacter(CodingErrorAction.REPLACE)
 832      *       .encode(bb); </pre>
 833      *
 834      * except that it is potentially more efficient because it can cache
 835      * encoders between successive invocations.
 836      *
 837      * <p> This method always replaces malformed-input and unmappable-character
 838      * sequences with this charset's default replacement string.  In order to
 839      * detect such sequences, use the {@link
 840      * CharsetEncoder#encode(java.nio.CharBuffer)} method directly.  </p>
 841      *
 842      * @param  cb  The char buffer to be encoded
 843      *
 844      * @return  A byte buffer containing the encoded characters
 845      */
 846     public final ByteBuffer encode(CharBuffer cb) {
 847         try {
 848             return ThreadLocalCoders.encoderFor(this)
 849                 .onMalformedInput(CodingErrorAction.REPLACE)
 850                 .onUnmappableCharacter(CodingErrorAction.REPLACE)
 851                 .encode(cb);
 852         } catch (CharacterCodingException x) {
 853             throw new Error(x);         // Can't happen
 854         }
 855     }
 856 
 857     /**
 858      * Convenience method that encodes a string into bytes in this charset.
 859      *
 860      * <p> An invocation of this method upon a charset {@code cs} returns the
 861      * same result as the expression
 862      *
 863      * <pre>
 864      *     cs.encode(CharBuffer.wrap(s)); </pre>
 865      *
 866      * @param  str  The string to be encoded
 867      *
 868      * @return  A byte buffer containing the encoded characters
 869      */
 870     public final ByteBuffer encode(String str) {
 871         return encode(CharBuffer.wrap(str));
 872     }
 873 
 874     /**
 875      * Compares this charset to another.
 876      *
 877      * <p> Charsets are ordered by their canonical names, without regard to
 878      * case. </p>
 879      *
 880      * @param  that
 881      *         The charset to which this charset is to be compared
 882      *
 883      * @return A negative integer, zero, or a positive integer as this charset
 884      *         is less than, equal to, or greater than the specified charset
 885      */
 886     public final int compareTo(Charset that) {
 887         return (name().compareToIgnoreCase(that.name()));
 888     }
 889 
 890     /**
 891      * Computes a hashcode for this charset.
 892      *
 893      * @return  An integer hashcode
 894      */
 895     public final int hashCode() {
 896         return name().hashCode();
 897     }
 898 
 899     /**
 900      * Tells whether or not this object is equal to another.
 901      *
 902      * <p> Two charsets are equal if, and only if, they have the same canonical
 903      * names.  A charset is never equal to any other type of object.  </p>
 904      *
 905      * @return  {@code true} if, and only if, this charset is equal to the
 906      *          given object
 907      */
 908     public final boolean equals(Object ob) {
 909         if (!(ob instanceof Charset))
 910             return false;
 911         if (this == ob)
 912             return true;
 913         return name.equals(((Charset)ob).name());
 914     }
 915 
 916     /**
 917      * Returns a string describing this charset.
 918      *
 919      * @return  A string describing this charset
 920      */
 921     public final String toString() {
 922         return name();
 923     }
 924 
 925 }