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