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