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