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