rt/emul/compact/src/main/java/java/nio/charset/Charset.java
branchjdk7-b147
changeset 1334 588d5bf7a560
child 1343 802e5d2da9f6
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/rt/emul/compact/src/main/java/java/nio/charset/Charset.java	Thu Oct 03 15:40:35 2013 +0200
     1.3 @@ -0,0 +1,923 @@
     1.4 +/*
     1.5 + * Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
     1.6 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     1.7 + *
     1.8 + * This code is free software; you can redistribute it and/or modify it
     1.9 + * under the terms of the GNU General Public License version 2 only, as
    1.10 + * published by the Free Software Foundation.  Oracle designates this
    1.11 + * particular file as subject to the "Classpath" exception as provided
    1.12 + * by Oracle in the LICENSE file that accompanied this code.
    1.13 + *
    1.14 + * This code is distributed in the hope that it will be useful, but WITHOUT
    1.15 + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    1.16 + * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    1.17 + * version 2 for more details (a copy is included in the LICENSE file that
    1.18 + * accompanied this code).
    1.19 + *
    1.20 + * You should have received a copy of the GNU General Public License version
    1.21 + * 2 along with this work; if not, write to the Free Software Foundation,
    1.22 + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    1.23 + *
    1.24 + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    1.25 + * or visit www.oracle.com if you need additional information or have any
    1.26 + * questions.
    1.27 + */
    1.28 +
    1.29 +package java.nio.charset;
    1.30 +
    1.31 +import java.nio.ByteBuffer;
    1.32 +import java.nio.CharBuffer;
    1.33 +import java.nio.charset.spi.CharsetProvider;
    1.34 +import java.security.AccessController;
    1.35 +import java.security.AccessControlException;
    1.36 +import java.security.PrivilegedAction;
    1.37 +import java.util.Collections;
    1.38 +import java.util.HashSet;
    1.39 +import java.util.Iterator;
    1.40 +import java.util.Locale;
    1.41 +import java.util.Map;
    1.42 +import java.util.NoSuchElementException;
    1.43 +import java.util.Set;
    1.44 +import java.util.ServiceLoader;
    1.45 +import java.util.ServiceConfigurationError;
    1.46 +import java.util.SortedMap;
    1.47 +import java.util.TreeMap;
    1.48 +import sun.misc.ASCIICaseInsensitiveComparator;
    1.49 +import sun.nio.cs.StandardCharsets;
    1.50 +import sun.nio.cs.ThreadLocalCoders;
    1.51 +import sun.security.action.GetPropertyAction;
    1.52 +
    1.53 +
    1.54 +/**
    1.55 + * A named mapping between sequences of sixteen-bit Unicode <a
    1.56 + * href="../../lang/Character.html#unicode">code units</a> and sequences of
    1.57 + * bytes.  This class defines methods for creating decoders and encoders and
    1.58 + * for retrieving the various names associated with a charset.  Instances of
    1.59 + * this class are immutable.
    1.60 + *
    1.61 + * <p> This class also defines static methods for testing whether a particular
    1.62 + * charset is supported, for locating charset instances by name, and for
    1.63 + * constructing a map that contains every charset for which support is
    1.64 + * available in the current Java virtual machine.  Support for new charsets can
    1.65 + * be added via the service-provider interface defined in the {@link
    1.66 + * java.nio.charset.spi.CharsetProvider} class.
    1.67 + *
    1.68 + * <p> All of the methods defined in this class are safe for use by multiple
    1.69 + * concurrent threads.
    1.70 + *
    1.71 + *
    1.72 + * <a name="names"><a name="charenc">
    1.73 + * <h4>Charset names</h4>
    1.74 + *
    1.75 + * <p> Charsets are named by strings composed of the following characters:
    1.76 + *
    1.77 + * <ul>
    1.78 + *
    1.79 + *   <li> The uppercase letters <tt>'A'</tt> through <tt>'Z'</tt>
    1.80 + *        (<tt>'&#92;u0041'</tt>&nbsp;through&nbsp;<tt>'&#92;u005a'</tt>),
    1.81 + *
    1.82 + *   <li> The lowercase letters <tt>'a'</tt> through <tt>'z'</tt>
    1.83 + *        (<tt>'&#92;u0061'</tt>&nbsp;through&nbsp;<tt>'&#92;u007a'</tt>),
    1.84 + *
    1.85 + *   <li> The digits <tt>'0'</tt> through <tt>'9'</tt>
    1.86 + *        (<tt>'&#92;u0030'</tt>&nbsp;through&nbsp;<tt>'&#92;u0039'</tt>),
    1.87 + *
    1.88 + *   <li> The dash character <tt>'-'</tt>
    1.89 + *        (<tt>'&#92;u002d'</tt>,&nbsp;<small>HYPHEN-MINUS</small>),
    1.90 + *
    1.91 + *   <li> The plus character <tt>'+'</tt>
    1.92 + *        (<tt>'&#92;u002b'</tt>,&nbsp;<small>PLUS SIGN</small>),
    1.93 + *
    1.94 + *   <li> The period character <tt>'.'</tt>
    1.95 + *        (<tt>'&#92;u002e'</tt>,&nbsp;<small>FULL STOP</small>),
    1.96 + *
    1.97 + *   <li> The colon character <tt>':'</tt>
    1.98 + *        (<tt>'&#92;u003a'</tt>,&nbsp;<small>COLON</small>), and
    1.99 + *
   1.100 + *   <li> The underscore character <tt>'_'</tt>
   1.101 + *        (<tt>'&#92;u005f'</tt>,&nbsp;<small>LOW&nbsp;LINE</small>).
   1.102 + *
   1.103 + * </ul>
   1.104 + *
   1.105 + * A charset name must begin with either a letter or a digit.  The empty string
   1.106 + * is not a legal charset name.  Charset names are not case-sensitive; that is,
   1.107 + * case is always ignored when comparing charset names.  Charset names
   1.108 + * generally follow the conventions documented in <a
   1.109 + * href="http://www.ietf.org/rfc/rfc2278.txt"><i>RFC&nbsp;2278:&nbsp;IANA Charset
   1.110 + * Registration Procedures</i></a>.
   1.111 + *
   1.112 + * <p> Every charset has a <i>canonical name</i> and may also have one or more
   1.113 + * <i>aliases</i>.  The canonical name is returned by the {@link #name() name} method
   1.114 + * of this class.  Canonical names are, by convention, usually in upper case.
   1.115 + * The aliases of a charset are returned by the {@link #aliases() aliases}
   1.116 + * method.
   1.117 + *
   1.118 + * <a name="hn">
   1.119 + *
   1.120 + * <p> Some charsets have an <i>historical name</i> that is defined for
   1.121 + * compatibility with previous versions of the Java platform.  A charset's
   1.122 + * historical name is either its canonical name or one of its aliases.  The
   1.123 + * historical name is returned by the <tt>getEncoding()</tt> methods of the
   1.124 + * {@link java.io.InputStreamReader#getEncoding InputStreamReader} and {@link
   1.125 + * java.io.OutputStreamWriter#getEncoding OutputStreamWriter} classes.
   1.126 + *
   1.127 + * <a name="iana">
   1.128 + *
   1.129 + * <p> If a charset listed in the <a
   1.130 + * href="http://www.iana.org/assignments/character-sets"><i>IANA Charset
   1.131 + * Registry</i></a> is supported by an implementation of the Java platform then
   1.132 + * its canonical name must be the name listed in the registry.  Many charsets
   1.133 + * are given more than one name in the registry, in which case the registry
   1.134 + * identifies one of the names as <i>MIME-preferred</i>.  If a charset has more
   1.135 + * than one registry name then its canonical name must be the MIME-preferred
   1.136 + * name and the other names in the registry must be valid aliases.  If a
   1.137 + * supported charset is not listed in the IANA registry then its canonical name
   1.138 + * must begin with one of the strings <tt>"X-"</tt> or <tt>"x-"</tt>.
   1.139 + *
   1.140 + * <p> The IANA charset registry does change over time, and so the canonical
   1.141 + * name and the aliases of a particular charset may also change over time.  To
   1.142 + * ensure compatibility it is recommended that no alias ever be removed from a
   1.143 + * charset, and that if the canonical name of a charset is changed then its
   1.144 + * previous canonical name be made into an alias.
   1.145 + *
   1.146 + *
   1.147 + * <h4>Standard charsets</h4>
   1.148 + *
   1.149 + * <a name="standard">
   1.150 + *
   1.151 + * <p> Every implementation of the Java platform is required to support the
   1.152 + * following standard charsets.  Consult the release documentation for your
   1.153 + * implementation to see if any other charsets are supported.  The behavior
   1.154 + * of such optional charsets may differ between implementations.
   1.155 + *
   1.156 + * <blockquote><table width="80%" summary="Description of standard charsets">
   1.157 + * <tr><th><p align="left">Charset</p></th><th><p align="left">Description</p></th></tr>
   1.158 + * <tr><td valign=top><tt>US-ASCII</tt></td>
   1.159 + *     <td>Seven-bit ASCII, a.k.a. <tt>ISO646-US</tt>,
   1.160 + *         a.k.a. the Basic Latin block of the Unicode character set</td></tr>
   1.161 + * <tr><td valign=top><tt>ISO-8859-1&nbsp;&nbsp;</tt></td>
   1.162 + *     <td>ISO Latin Alphabet No. 1, a.k.a. <tt>ISO-LATIN-1</tt></td></tr>
   1.163 + * <tr><td valign=top><tt>UTF-8</tt></td>
   1.164 + *     <td>Eight-bit UCS Transformation Format</td></tr>
   1.165 + * <tr><td valign=top><tt>UTF-16BE</tt></td>
   1.166 + *     <td>Sixteen-bit UCS Transformation Format,
   1.167 + *         big-endian byte&nbsp;order</td></tr>
   1.168 + * <tr><td valign=top><tt>UTF-16LE</tt></td>
   1.169 + *     <td>Sixteen-bit UCS Transformation Format,
   1.170 + *         little-endian byte&nbsp;order</td></tr>
   1.171 + * <tr><td valign=top><tt>UTF-16</tt></td>
   1.172 + *     <td>Sixteen-bit UCS Transformation Format,
   1.173 + *         byte&nbsp;order identified by an optional byte-order mark</td></tr>
   1.174 + * </table></blockquote>
   1.175 + *
   1.176 + * <p> The <tt>UTF-8</tt> charset is specified by <a
   1.177 + * href="http://www.ietf.org/rfc/rfc2279.txt"><i>RFC&nbsp;2279</i></a>; the
   1.178 + * transformation format upon which it is based is specified in
   1.179 + * Amendment&nbsp;2 of ISO&nbsp;10646-1 and is also described in the <a
   1.180 + * href="http://www.unicode.org/unicode/standard/standard.html"><i>Unicode
   1.181 + * Standard</i></a>.
   1.182 + *
   1.183 + * <p> The <tt>UTF-16</tt> charsets are specified by <a
   1.184 + * href="http://www.ietf.org/rfc/rfc2781.txt"><i>RFC&nbsp;2781</i></a>; the
   1.185 + * transformation formats upon which they are based are specified in
   1.186 + * Amendment&nbsp;1 of ISO&nbsp;10646-1 and are also described in the <a
   1.187 + * href="http://www.unicode.org/unicode/standard/standard.html"><i>Unicode
   1.188 + * Standard</i></a>.
   1.189 + *
   1.190 + * <p> The <tt>UTF-16</tt> charsets use sixteen-bit quantities and are
   1.191 + * therefore sensitive to byte order.  In these encodings the byte order of a
   1.192 + * stream may be indicated by an initial <i>byte-order mark</i> represented by
   1.193 + * the Unicode character <tt>'&#92;uFEFF'</tt>.  Byte-order marks are handled
   1.194 + * as follows:
   1.195 + *
   1.196 + * <ul>
   1.197 + *
   1.198 + *   <li><p> When decoding, the <tt>UTF-16BE</tt> and <tt>UTF-16LE</tt>
   1.199 + *   charsets interpret the initial byte-order marks as a <small>ZERO-WIDTH
   1.200 + *   NON-BREAKING SPACE</small>; when encoding, they do not write
   1.201 + *   byte-order marks. </p></li>
   1.202 +
   1.203 + *
   1.204 + *   <li><p> When decoding, the <tt>UTF-16</tt> charset interprets the
   1.205 + *   byte-order mark at the beginning of the input stream to indicate the
   1.206 + *   byte-order of the stream but defaults to big-endian if there is no
   1.207 + *   byte-order mark; when encoding, it uses big-endian byte order and writes
   1.208 + *   a big-endian byte-order mark. </p></li>
   1.209 + *
   1.210 + * </ul>
   1.211 + *
   1.212 + * In any case, byte order marks occuring after the first element of an
   1.213 + * input sequence are not omitted since the same code is used to represent
   1.214 + * <small>ZERO-WIDTH NON-BREAKING SPACE</small>.
   1.215 + *
   1.216 + * <p> Every instance of the Java virtual machine has a default charset, which
   1.217 + * may or may not be one of the standard charsets.  The default charset is
   1.218 + * determined during virtual-machine startup and typically depends upon the
   1.219 + * locale and charset being used by the underlying operating system. </p>
   1.220 + *
   1.221 + * <p>The {@link StandardCharsets} class defines constants for each of the
   1.222 + * standard charsets.
   1.223 + *
   1.224 + * <h4>Terminology</h4>
   1.225 + *
   1.226 + * <p> The name of this class is taken from the terms used in
   1.227 + * <a href="http://www.ietf.org/rfc/rfc2278.txt"><i>RFC&nbsp;2278</i></a>.
   1.228 + * In that document a <i>charset</i> is defined as the combination of
   1.229 + * one or more coded character sets and a character-encoding scheme.
   1.230 + * (This definition is confusing; some other software systems define
   1.231 + * <i>charset</i> as a synonym for <i>coded character set</i>.)
   1.232 + *
   1.233 + * <p> A <i>coded character set</i> is a mapping between a set of abstract
   1.234 + * characters and a set of integers.  US-ASCII, ISO&nbsp;8859-1,
   1.235 + * JIS&nbsp;X&nbsp;0201, and Unicode are examples of coded character sets.
   1.236 + *
   1.237 + * <p> Some standards have defined a <i>character set</i> to be simply a
   1.238 + * set of abstract characters without an associated assigned numbering.
   1.239 + * An alphabet is an example of such a character set.  However, the subtle
   1.240 + * distinction between <i>character set</i> and <i>coded character set</i>
   1.241 + * is rarely used in practice; the former has become a short form for the
   1.242 + * latter, including in the Java API specification.
   1.243 + *
   1.244 + * <p> A <i>character-encoding scheme</i> is a mapping between one or more
   1.245 + * coded character sets and a set of octet (eight-bit byte) sequences.
   1.246 + * UTF-8, UTF-16, ISO&nbsp;2022, and EUC are examples of
   1.247 + * character-encoding schemes.  Encoding schemes are often associated with
   1.248 + * a particular coded character set; UTF-8, for example, is used only to
   1.249 + * encode Unicode.  Some schemes, however, are associated with multiple
   1.250 + * coded character sets; EUC, for example, can be used to encode
   1.251 + * characters in a variety of Asian coded character sets.
   1.252 + *
   1.253 + * <p> When a coded character set is used exclusively with a single
   1.254 + * character-encoding scheme then the corresponding charset is usually
   1.255 + * named for the coded character set; otherwise a charset is usually named
   1.256 + * for the encoding scheme and, possibly, the locale of the coded
   1.257 + * character sets that it supports.  Hence <tt>US-ASCII</tt> is both the
   1.258 + * name of a coded character set and of the charset that encodes it, while
   1.259 + * <tt>EUC-JP</tt> is the name of the charset that encodes the
   1.260 + * JIS&nbsp;X&nbsp;0201, JIS&nbsp;X&nbsp;0208, and JIS&nbsp;X&nbsp;0212
   1.261 + * coded character sets for the Japanese language.
   1.262 + *
   1.263 + * <p> The native character encoding of the Java programming language is
   1.264 + * UTF-16.  A charset in the Java platform therefore defines a mapping
   1.265 + * between sequences of sixteen-bit UTF-16 code units (that is, sequences
   1.266 + * of chars) and sequences of bytes. </p>
   1.267 + *
   1.268 + *
   1.269 + * @author Mark Reinhold
   1.270 + * @author JSR-51 Expert Group
   1.271 + * @since 1.4
   1.272 + *
   1.273 + * @see CharsetDecoder
   1.274 + * @see CharsetEncoder
   1.275 + * @see java.nio.charset.spi.CharsetProvider
   1.276 + * @see java.lang.Character
   1.277 + */
   1.278 +
   1.279 +public abstract class Charset
   1.280 +    implements Comparable<Charset>
   1.281 +{
   1.282 +
   1.283 +    /* -- Static methods -- */
   1.284 +
   1.285 +    private static volatile String bugLevel = null;
   1.286 +
   1.287 +    static boolean atBugLevel(String bl) {              // package-private
   1.288 +        String level = bugLevel;
   1.289 +        if (level == null) {
   1.290 +            if (!sun.misc.VM.isBooted())
   1.291 +                return false;
   1.292 +            bugLevel = level = AccessController.doPrivileged(
   1.293 +                new GetPropertyAction("sun.nio.cs.bugLevel", ""));
   1.294 +        }
   1.295 +        return level.equals(bl);
   1.296 +    }
   1.297 +
   1.298 +    /**
   1.299 +     * Checks that the given string is a legal charset name. </p>
   1.300 +     *
   1.301 +     * @param  s
   1.302 +     *         A purported charset name
   1.303 +     *
   1.304 +     * @throws  IllegalCharsetNameException
   1.305 +     *          If the given name is not a legal charset name
   1.306 +     */
   1.307 +    private static void checkName(String s) {
   1.308 +        int n = s.length();
   1.309 +        if (!atBugLevel("1.4")) {
   1.310 +            if (n == 0)
   1.311 +                throw new IllegalCharsetNameException(s);
   1.312 +        }
   1.313 +        for (int i = 0; i < n; i++) {
   1.314 +            char c = s.charAt(i);
   1.315 +            if (c >= 'A' && c <= 'Z') continue;
   1.316 +            if (c >= 'a' && c <= 'z') continue;
   1.317 +            if (c >= '0' && c <= '9') continue;
   1.318 +            if (c == '-' && i != 0) continue;
   1.319 +            if (c == '+' && i != 0) continue;
   1.320 +            if (c == ':' && i != 0) continue;
   1.321 +            if (c == '_' && i != 0) continue;
   1.322 +            if (c == '.' && i != 0) continue;
   1.323 +            throw new IllegalCharsetNameException(s);
   1.324 +        }
   1.325 +    }
   1.326 +
   1.327 +    /* The standard set of charsets */
   1.328 +    private static CharsetProvider standardProvider = new StandardCharsets();
   1.329 +
   1.330 +    // Cache of the most-recently-returned charsets,
   1.331 +    // along with the names that were used to find them
   1.332 +    //
   1.333 +    private static volatile Object[] cache1 = null; // "Level 1" cache
   1.334 +    private static volatile Object[] cache2 = null; // "Level 2" cache
   1.335 +
   1.336 +    private static void cache(String charsetName, Charset cs) {
   1.337 +        cache2 = cache1;
   1.338 +        cache1 = new Object[] { charsetName, cs };
   1.339 +    }
   1.340 +
   1.341 +    // Creates an iterator that walks over the available providers, ignoring
   1.342 +    // those whose lookup or instantiation causes a security exception to be
   1.343 +    // thrown.  Should be invoked with full privileges.
   1.344 +    //
   1.345 +    private static Iterator providers() {
   1.346 +        return new Iterator() {
   1.347 +
   1.348 +                ClassLoader cl = ClassLoader.getSystemClassLoader();
   1.349 +                ServiceLoader<CharsetProvider> sl =
   1.350 +                    ServiceLoader.load(CharsetProvider.class, cl);
   1.351 +                Iterator<CharsetProvider> i = sl.iterator();
   1.352 +
   1.353 +                Object next = null;
   1.354 +
   1.355 +                private boolean getNext() {
   1.356 +                    while (next == null) {
   1.357 +                        try {
   1.358 +                            if (!i.hasNext())
   1.359 +                                return false;
   1.360 +                            next = i.next();
   1.361 +                        } catch (ServiceConfigurationError sce) {
   1.362 +                            if (sce.getCause() instanceof SecurityException) {
   1.363 +                                // Ignore security exceptions
   1.364 +                                continue;
   1.365 +                            }
   1.366 +                            throw sce;
   1.367 +                        }
   1.368 +                    }
   1.369 +                    return true;
   1.370 +                }
   1.371 +
   1.372 +                public boolean hasNext() {
   1.373 +                    return getNext();
   1.374 +                }
   1.375 +
   1.376 +                public Object next() {
   1.377 +                    if (!getNext())
   1.378 +                        throw new NoSuchElementException();
   1.379 +                    Object n = next;
   1.380 +                    next = null;
   1.381 +                    return n;
   1.382 +                }
   1.383 +
   1.384 +                public void remove() {
   1.385 +                    throw new UnsupportedOperationException();
   1.386 +                }
   1.387 +
   1.388 +            };
   1.389 +    }
   1.390 +
   1.391 +    // Thread-local gate to prevent recursive provider lookups
   1.392 +    private static ThreadLocal<ThreadLocal> gate = new ThreadLocal<ThreadLocal>();
   1.393 +
   1.394 +    private static Charset lookupViaProviders(final String charsetName) {
   1.395 +
   1.396 +        // The runtime startup sequence looks up standard charsets as a
   1.397 +        // consequence of the VM's invocation of System.initializeSystemClass
   1.398 +        // in order to, e.g., set system properties and encode filenames.  At
   1.399 +        // that point the application class loader has not been initialized,
   1.400 +        // however, so we can't look for providers because doing so will cause
   1.401 +        // that loader to be prematurely initialized with incomplete
   1.402 +        // information.
   1.403 +        //
   1.404 +        if (!sun.misc.VM.isBooted())
   1.405 +            return null;
   1.406 +
   1.407 +        if (gate.get() != null)
   1.408 +            // Avoid recursive provider lookups
   1.409 +            return null;
   1.410 +        try {
   1.411 +            gate.set(gate);
   1.412 +
   1.413 +            return AccessController.doPrivileged(
   1.414 +                new PrivilegedAction<Charset>() {
   1.415 +                    public Charset run() {
   1.416 +                        for (Iterator i = providers(); i.hasNext();) {
   1.417 +                            CharsetProvider cp = (CharsetProvider)i.next();
   1.418 +                            Charset cs = cp.charsetForName(charsetName);
   1.419 +                            if (cs != null)
   1.420 +                                return cs;
   1.421 +                        }
   1.422 +                        return null;
   1.423 +                    }
   1.424 +                });
   1.425 +
   1.426 +        } finally {
   1.427 +            gate.set(null);
   1.428 +        }
   1.429 +    }
   1.430 +
   1.431 +    /* The extended set of charsets */
   1.432 +    private static Object extendedProviderLock = new Object();
   1.433 +    private static boolean extendedProviderProbed = false;
   1.434 +    private static CharsetProvider extendedProvider = null;
   1.435 +
   1.436 +    private static void probeExtendedProvider() {
   1.437 +        AccessController.doPrivileged(new PrivilegedAction<Object>() {
   1.438 +                public Object run() {
   1.439 +                    try {
   1.440 +                        Class epc
   1.441 +                            = Class.forName("sun.nio.cs.ext.ExtendedCharsets");
   1.442 +                        extendedProvider = (CharsetProvider)epc.newInstance();
   1.443 +                    } catch (ClassNotFoundException x) {
   1.444 +                        // Extended charsets not available
   1.445 +                        // (charsets.jar not present)
   1.446 +                    } catch (InstantiationException x) {
   1.447 +                        throw new Error(x);
   1.448 +                    } catch (IllegalAccessException x) {
   1.449 +                        throw new Error(x);
   1.450 +                    }
   1.451 +                    return null;
   1.452 +                }
   1.453 +            });
   1.454 +    }
   1.455 +
   1.456 +    private static Charset lookupExtendedCharset(String charsetName) {
   1.457 +        CharsetProvider ecp = null;
   1.458 +        synchronized (extendedProviderLock) {
   1.459 +            if (!extendedProviderProbed) {
   1.460 +                probeExtendedProvider();
   1.461 +                extendedProviderProbed = true;
   1.462 +            }
   1.463 +            ecp = extendedProvider;
   1.464 +        }
   1.465 +        return (ecp != null) ? ecp.charsetForName(charsetName) : null;
   1.466 +    }
   1.467 +
   1.468 +    private static Charset lookup(String charsetName) {
   1.469 +        if (charsetName == null)
   1.470 +            throw new IllegalArgumentException("Null charset name");
   1.471 +
   1.472 +        Object[] a;
   1.473 +        if ((a = cache1) != null && charsetName.equals(a[0]))
   1.474 +            return (Charset)a[1];
   1.475 +        // We expect most programs to use one Charset repeatedly.
   1.476 +        // We convey a hint to this effect to the VM by putting the
   1.477 +        // level 1 cache miss code in a separate method.
   1.478 +        return lookup2(charsetName);
   1.479 +    }
   1.480 +
   1.481 +    private static Charset lookup2(String charsetName) {
   1.482 +        Object[] a;
   1.483 +        if ((a = cache2) != null && charsetName.equals(a[0])) {
   1.484 +            cache2 = cache1;
   1.485 +            cache1 = a;
   1.486 +            return (Charset)a[1];
   1.487 +        }
   1.488 +
   1.489 +        Charset cs;
   1.490 +        if ((cs = standardProvider.charsetForName(charsetName)) != null ||
   1.491 +            (cs = lookupExtendedCharset(charsetName))           != null ||
   1.492 +            (cs = lookupViaProviders(charsetName))              != null)
   1.493 +        {
   1.494 +            cache(charsetName, cs);
   1.495 +            return cs;
   1.496 +        }
   1.497 +
   1.498 +        /* Only need to check the name if we didn't find a charset for it */
   1.499 +        checkName(charsetName);
   1.500 +        return null;
   1.501 +    }
   1.502 +
   1.503 +    /**
   1.504 +     * Tells whether the named charset is supported. </p>
   1.505 +     *
   1.506 +     * @param  charsetName
   1.507 +     *         The name of the requested charset; may be either
   1.508 +     *         a canonical name or an alias
   1.509 +     *
   1.510 +     * @return  <tt>true</tt> if, and only if, support for the named charset
   1.511 +     *          is available in the current Java virtual machine
   1.512 +     *
   1.513 +     * @throws IllegalCharsetNameException
   1.514 +     *         If the given charset name is illegal
   1.515 +     *
   1.516 +     * @throws  IllegalArgumentException
   1.517 +     *          If the given <tt>charsetName</tt> is null
   1.518 +     */
   1.519 +    public static boolean isSupported(String charsetName) {
   1.520 +        return (lookup(charsetName) != null);
   1.521 +    }
   1.522 +
   1.523 +    /**
   1.524 +     * Returns a charset object for the named charset. </p>
   1.525 +     *
   1.526 +     * @param  charsetName
   1.527 +     *         The name of the requested charset; may be either
   1.528 +     *         a canonical name or an alias
   1.529 +     *
   1.530 +     * @return  A charset object for the named charset
   1.531 +     *
   1.532 +     * @throws  IllegalCharsetNameException
   1.533 +     *          If the given charset name is illegal
   1.534 +     *
   1.535 +     * @throws  IllegalArgumentException
   1.536 +     *          If the given <tt>charsetName</tt> is null
   1.537 +     *
   1.538 +     * @throws  UnsupportedCharsetException
   1.539 +     *          If no support for the named charset is available
   1.540 +     *          in this instance of the Java virtual machine
   1.541 +     */
   1.542 +    public static Charset forName(String charsetName) {
   1.543 +        Charset cs = lookup(charsetName);
   1.544 +        if (cs != null)
   1.545 +            return cs;
   1.546 +        throw new UnsupportedCharsetException(charsetName);
   1.547 +    }
   1.548 +
   1.549 +    // Fold charsets from the given iterator into the given map, ignoring
   1.550 +    // charsets whose names already have entries in the map.
   1.551 +    //
   1.552 +    private static void put(Iterator<Charset> i, Map<String,Charset> m) {
   1.553 +        while (i.hasNext()) {
   1.554 +            Charset cs = i.next();
   1.555 +            if (!m.containsKey(cs.name()))
   1.556 +                m.put(cs.name(), cs);
   1.557 +        }
   1.558 +    }
   1.559 +
   1.560 +    /**
   1.561 +     * Constructs a sorted map from canonical charset names to charset objects.
   1.562 +     *
   1.563 +     * <p> The map returned by this method will have one entry for each charset
   1.564 +     * for which support is available in the current Java virtual machine.  If
   1.565 +     * two or more supported charsets have the same canonical name then the
   1.566 +     * resulting map will contain just one of them; which one it will contain
   1.567 +     * is not specified. </p>
   1.568 +     *
   1.569 +     * <p> The invocation of this method, and the subsequent use of the
   1.570 +     * resulting map, may cause time-consuming disk or network I/O operations
   1.571 +     * to occur.  This method is provided for applications that need to
   1.572 +     * enumerate all of the available charsets, for example to allow user
   1.573 +     * charset selection.  This method is not used by the {@link #forName
   1.574 +     * forName} method, which instead employs an efficient incremental lookup
   1.575 +     * algorithm.
   1.576 +     *
   1.577 +     * <p> This method may return different results at different times if new
   1.578 +     * charset providers are dynamically made available to the current Java
   1.579 +     * virtual machine.  In the absence of such changes, the charsets returned
   1.580 +     * by this method are exactly those that can be retrieved via the {@link
   1.581 +     * #forName forName} method.  </p>
   1.582 +     *
   1.583 +     * @return An immutable, case-insensitive map from canonical charset names
   1.584 +     *         to charset objects
   1.585 +     */
   1.586 +    public static SortedMap<String,Charset> availableCharsets() {
   1.587 +        return AccessController.doPrivileged(
   1.588 +            new PrivilegedAction<SortedMap<String,Charset>>() {
   1.589 +                public SortedMap<String,Charset> run() {
   1.590 +                    TreeMap<String,Charset> m =
   1.591 +                        new TreeMap<String,Charset>(
   1.592 +                            ASCIICaseInsensitiveComparator.CASE_INSENSITIVE_ORDER);
   1.593 +                    put(standardProvider.charsets(), m);
   1.594 +                    for (Iterator i = providers(); i.hasNext();) {
   1.595 +                        CharsetProvider cp = (CharsetProvider)i.next();
   1.596 +                        put(cp.charsets(), m);
   1.597 +                    }
   1.598 +                    return Collections.unmodifiableSortedMap(m);
   1.599 +                }
   1.600 +            });
   1.601 +    }
   1.602 +
   1.603 +    private static volatile Charset defaultCharset;
   1.604 +
   1.605 +    /**
   1.606 +     * Returns the default charset of this Java virtual machine.
   1.607 +     *
   1.608 +     * <p> The default charset is determined during virtual-machine startup and
   1.609 +     * typically depends upon the locale and charset of the underlying
   1.610 +     * operating system.
   1.611 +     *
   1.612 +     * @return  A charset object for the default charset
   1.613 +     *
   1.614 +     * @since 1.5
   1.615 +     */
   1.616 +    public static Charset defaultCharset() {
   1.617 +        if (defaultCharset == null) {
   1.618 +            synchronized (Charset.class) {
   1.619 +                String csn = AccessController.doPrivileged(
   1.620 +                    new GetPropertyAction("file.encoding"));
   1.621 +                Charset cs = lookup(csn);
   1.622 +                if (cs != null)
   1.623 +                    defaultCharset = cs;
   1.624 +                else
   1.625 +                    defaultCharset = forName("UTF-8");
   1.626 +            }
   1.627 +        }
   1.628 +        return defaultCharset;
   1.629 +    }
   1.630 +
   1.631 +
   1.632 +    /* -- Instance fields and methods -- */
   1.633 +
   1.634 +    private final String name;          // tickles a bug in oldjavac
   1.635 +    private final String[] aliases;     // tickles a bug in oldjavac
   1.636 +    private Set<String> aliasSet = null;
   1.637 +
   1.638 +    /**
   1.639 +     * Initializes a new charset with the given canonical name and alias
   1.640 +     * set. </p>
   1.641 +     *
   1.642 +     * @param  canonicalName
   1.643 +     *         The canonical name of this charset
   1.644 +     *
   1.645 +     * @param  aliases
   1.646 +     *         An array of this charset's aliases, or null if it has no aliases
   1.647 +     *
   1.648 +     * @throws IllegalCharsetNameException
   1.649 +     *         If the canonical name or any of the aliases are illegal
   1.650 +     */
   1.651 +    protected Charset(String canonicalName, String[] aliases) {
   1.652 +        checkName(canonicalName);
   1.653 +        String[] as = (aliases == null) ? new String[0] : aliases;
   1.654 +        for (int i = 0; i < as.length; i++)
   1.655 +            checkName(as[i]);
   1.656 +        this.name = canonicalName;
   1.657 +        this.aliases = as;
   1.658 +    }
   1.659 +
   1.660 +    /**
   1.661 +     * Returns this charset's canonical name. </p>
   1.662 +     *
   1.663 +     * @return  The canonical name of this charset
   1.664 +     */
   1.665 +    public final String name() {
   1.666 +        return name;
   1.667 +    }
   1.668 +
   1.669 +    /**
   1.670 +     * Returns a set containing this charset's aliases. </p>
   1.671 +     *
   1.672 +     * @return  An immutable set of this charset's aliases
   1.673 +     */
   1.674 +    public final Set<String> aliases() {
   1.675 +        if (aliasSet != null)
   1.676 +            return aliasSet;
   1.677 +        int n = aliases.length;
   1.678 +        HashSet<String> hs = new HashSet<String>(n);
   1.679 +        for (int i = 0; i < n; i++)
   1.680 +            hs.add(aliases[i]);
   1.681 +        aliasSet = Collections.unmodifiableSet(hs);
   1.682 +        return aliasSet;
   1.683 +    }
   1.684 +
   1.685 +    /**
   1.686 +     * Returns this charset's human-readable name for the default locale.
   1.687 +     *
   1.688 +     * <p> The default implementation of this method simply returns this
   1.689 +     * charset's canonical name.  Concrete subclasses of this class may
   1.690 +     * override this method in order to provide a localized display name. </p>
   1.691 +     *
   1.692 +     * @return  The display name of this charset in the default locale
   1.693 +     */
   1.694 +    public String displayName() {
   1.695 +        return name;
   1.696 +    }
   1.697 +
   1.698 +    /**
   1.699 +     * Tells whether or not this charset is registered in the <a
   1.700 +     * href="http://www.iana.org/assignments/character-sets">IANA Charset
   1.701 +     * Registry</a>.  </p>
   1.702 +     *
   1.703 +     * @return  <tt>true</tt> if, and only if, this charset is known by its
   1.704 +     *          implementor to be registered with the IANA
   1.705 +     */
   1.706 +    public final boolean isRegistered() {
   1.707 +        return !name.startsWith("X-") && !name.startsWith("x-");
   1.708 +    }
   1.709 +
   1.710 +    /**
   1.711 +     * Returns this charset's human-readable name for the given locale.
   1.712 +     *
   1.713 +     * <p> The default implementation of this method simply returns this
   1.714 +     * charset's canonical name.  Concrete subclasses of this class may
   1.715 +     * override this method in order to provide a localized display name. </p>
   1.716 +     *
   1.717 +     * @param  locale
   1.718 +     *         The locale for which the display name is to be retrieved
   1.719 +     *
   1.720 +     * @return  The display name of this charset in the given locale
   1.721 +     */
   1.722 +    public String displayName(Locale locale) {
   1.723 +        return name;
   1.724 +    }
   1.725 +
   1.726 +    /**
   1.727 +     * Tells whether or not this charset contains the given charset.
   1.728 +     *
   1.729 +     * <p> A charset <i>C</i> is said to <i>contain</i> a charset <i>D</i> if,
   1.730 +     * and only if, every character representable in <i>D</i> is also
   1.731 +     * representable in <i>C</i>.  If this relationship holds then it is
   1.732 +     * guaranteed that every string that can be encoded in <i>D</i> can also be
   1.733 +     * encoded in <i>C</i> without performing any replacements.
   1.734 +     *
   1.735 +     * <p> That <i>C</i> contains <i>D</i> does not imply that each character
   1.736 +     * representable in <i>C</i> by a particular byte sequence is represented
   1.737 +     * in <i>D</i> by the same byte sequence, although sometimes this is the
   1.738 +     * case.
   1.739 +     *
   1.740 +     * <p> Every charset contains itself.
   1.741 +     *
   1.742 +     * <p> This method computes an approximation of the containment relation:
   1.743 +     * If it returns <tt>true</tt> then the given charset is known to be
   1.744 +     * contained by this charset; if it returns <tt>false</tt>, however, then
   1.745 +     * it is not necessarily the case that the given charset is not contained
   1.746 +     * in this charset.
   1.747 +     *
   1.748 +     * @return  <tt>true</tt> if the given charset is contained in this charset
   1.749 +     */
   1.750 +    public abstract boolean contains(Charset cs);
   1.751 +
   1.752 +    /**
   1.753 +     * Constructs a new decoder for this charset. </p>
   1.754 +     *
   1.755 +     * @return  A new decoder for this charset
   1.756 +     */
   1.757 +    public abstract CharsetDecoder newDecoder();
   1.758 +
   1.759 +    /**
   1.760 +     * Constructs a new encoder for this charset. </p>
   1.761 +     *
   1.762 +     * @return  A new encoder for this charset
   1.763 +     *
   1.764 +     * @throws  UnsupportedOperationException
   1.765 +     *          If this charset does not support encoding
   1.766 +     */
   1.767 +    public abstract CharsetEncoder newEncoder();
   1.768 +
   1.769 +    /**
   1.770 +     * Tells whether or not this charset supports encoding.
   1.771 +     *
   1.772 +     * <p> Nearly all charsets support encoding.  The primary exceptions are
   1.773 +     * special-purpose <i>auto-detect</i> charsets whose decoders can determine
   1.774 +     * which of several possible encoding schemes is in use by examining the
   1.775 +     * input byte sequence.  Such charsets do not support encoding because
   1.776 +     * there is no way to determine which encoding should be used on output.
   1.777 +     * Implementations of such charsets should override this method to return
   1.778 +     * <tt>false</tt>. </p>
   1.779 +     *
   1.780 +     * @return  <tt>true</tt> if, and only if, this charset supports encoding
   1.781 +     */
   1.782 +    public boolean canEncode() {
   1.783 +        return true;
   1.784 +    }
   1.785 +
   1.786 +    /**
   1.787 +     * Convenience method that decodes bytes in this charset into Unicode
   1.788 +     * characters.
   1.789 +     *
   1.790 +     * <p> An invocation of this method upon a charset <tt>cs</tt> returns the
   1.791 +     * same result as the expression
   1.792 +     *
   1.793 +     * <pre>
   1.794 +     *     cs.newDecoder()
   1.795 +     *       .onMalformedInput(CodingErrorAction.REPLACE)
   1.796 +     *       .onUnmappableCharacter(CodingErrorAction.REPLACE)
   1.797 +     *       .decode(bb); </pre>
   1.798 +     *
   1.799 +     * except that it is potentially more efficient because it can cache
   1.800 +     * decoders between successive invocations.
   1.801 +     *
   1.802 +     * <p> This method always replaces malformed-input and unmappable-character
   1.803 +     * sequences with this charset's default replacement byte array.  In order
   1.804 +     * to detect such sequences, use the {@link
   1.805 +     * CharsetDecoder#decode(java.nio.ByteBuffer)} method directly.  </p>
   1.806 +     *
   1.807 +     * @param  bb  The byte buffer to be decoded
   1.808 +     *
   1.809 +     * @return  A char buffer containing the decoded characters
   1.810 +     */
   1.811 +    public final CharBuffer decode(ByteBuffer bb) {
   1.812 +        try {
   1.813 +            return ThreadLocalCoders.decoderFor(this)
   1.814 +                .onMalformedInput(CodingErrorAction.REPLACE)
   1.815 +                .onUnmappableCharacter(CodingErrorAction.REPLACE)
   1.816 +                .decode(bb);
   1.817 +        } catch (CharacterCodingException x) {
   1.818 +            throw new Error(x);         // Can't happen
   1.819 +        }
   1.820 +    }
   1.821 +
   1.822 +    /**
   1.823 +     * Convenience method that encodes Unicode characters into bytes in this
   1.824 +     * charset.
   1.825 +     *
   1.826 +     * <p> An invocation of this method upon a charset <tt>cs</tt> returns the
   1.827 +     * same result as the expression
   1.828 +     *
   1.829 +     * <pre>
   1.830 +     *     cs.newEncoder()
   1.831 +     *       .onMalformedInput(CodingErrorAction.REPLACE)
   1.832 +     *       .onUnmappableCharacter(CodingErrorAction.REPLACE)
   1.833 +     *       .encode(bb); </pre>
   1.834 +     *
   1.835 +     * except that it is potentially more efficient because it can cache
   1.836 +     * encoders between successive invocations.
   1.837 +     *
   1.838 +     * <p> This method always replaces malformed-input and unmappable-character
   1.839 +     * sequences with this charset's default replacement string.  In order to
   1.840 +     * detect such sequences, use the {@link
   1.841 +     * CharsetEncoder#encode(java.nio.CharBuffer)} method directly.  </p>
   1.842 +     *
   1.843 +     * @param  cb  The char buffer to be encoded
   1.844 +     *
   1.845 +     * @return  A byte buffer containing the encoded characters
   1.846 +     */
   1.847 +    public final ByteBuffer encode(CharBuffer cb) {
   1.848 +        try {
   1.849 +            return ThreadLocalCoders.encoderFor(this)
   1.850 +                .onMalformedInput(CodingErrorAction.REPLACE)
   1.851 +                .onUnmappableCharacter(CodingErrorAction.REPLACE)
   1.852 +                .encode(cb);
   1.853 +        } catch (CharacterCodingException x) {
   1.854 +            throw new Error(x);         // Can't happen
   1.855 +        }
   1.856 +    }
   1.857 +
   1.858 +    /**
   1.859 +     * Convenience method that encodes a string into bytes in this charset.
   1.860 +     *
   1.861 +     * <p> An invocation of this method upon a charset <tt>cs</tt> returns the
   1.862 +     * same result as the expression
   1.863 +     *
   1.864 +     * <pre>
   1.865 +     *     cs.encode(CharBuffer.wrap(s)); </pre>
   1.866 +     *
   1.867 +     * @param  str  The string to be encoded
   1.868 +     *
   1.869 +     * @return  A byte buffer containing the encoded characters
   1.870 +     */
   1.871 +    public final ByteBuffer encode(String str) {
   1.872 +        return encode(CharBuffer.wrap(str));
   1.873 +    }
   1.874 +
   1.875 +    /**
   1.876 +     * Compares this charset to another.
   1.877 +     *
   1.878 +     * <p> Charsets are ordered by their canonical names, without regard to
   1.879 +     * case. </p>
   1.880 +     *
   1.881 +     * @param  that
   1.882 +     *         The charset to which this charset is to be compared
   1.883 +     *
   1.884 +     * @return A negative integer, zero, or a positive integer as this charset
   1.885 +     *         is less than, equal to, or greater than the specified charset
   1.886 +     */
   1.887 +    public final int compareTo(Charset that) {
   1.888 +        return (name().compareToIgnoreCase(that.name()));
   1.889 +    }
   1.890 +
   1.891 +    /**
   1.892 +     * Computes a hashcode for this charset. </p>
   1.893 +     *
   1.894 +     * @return  An integer hashcode
   1.895 +     */
   1.896 +    public final int hashCode() {
   1.897 +        return name().hashCode();
   1.898 +    }
   1.899 +
   1.900 +    /**
   1.901 +     * Tells whether or not this object is equal to another.
   1.902 +     *
   1.903 +     * <p> Two charsets are equal if, and only if, they have the same canonical
   1.904 +     * names.  A charset is never equal to any other type of object.  </p>
   1.905 +     *
   1.906 +     * @return  <tt>true</tt> if, and only if, this charset is equal to the
   1.907 +     *          given object
   1.908 +     */
   1.909 +    public final boolean equals(Object ob) {
   1.910 +        if (!(ob instanceof Charset))
   1.911 +            return false;
   1.912 +        if (this == ob)
   1.913 +            return true;
   1.914 +        return name.equals(((Charset)ob).name());
   1.915 +    }
   1.916 +
   1.917 +    /**
   1.918 +     * Returns a string describing this charset. </p>
   1.919 +     *
   1.920 +     * @return  A string describing this charset
   1.921 +     */
   1.922 +    public final String toString() {
   1.923 +        return name();
   1.924 +    }
   1.925 +
   1.926 +}