1. /*
  2. * @(#)Charset-X-Coder.java 1.37 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. // -- This file was mechanically generated: Do not edit! -- //
  8. package java.nio.charset;
  9. import java.nio.Buffer;
  10. import java.nio.ByteBuffer;
  11. import java.nio.CharBuffer;
  12. import java.nio.BufferOverflowException;
  13. import java.nio.BufferUnderflowException;
  14. import java.lang.ref.WeakReference;
  15. import java.nio.charset.CoderMalfunctionError; // javadoc
  16. /**
  17. * An engine that can transform a sequence of sixteen-bit Unicode characters into a sequence of
  18. * bytes in a specific charset.
  19. *
  20. * <a name="steps">
  21. *
  22. * <p> The input character sequence is provided in a character buffer or a series
  23. * of such buffers. The output byte sequence is written to a byte buffer
  24. * or a series of such buffers. An encoder should always be used by making
  25. * the following sequence of method invocations, hereinafter referred to as an
  26. * <i>encoding operation</i>:
  27. *
  28. * <ol>
  29. *
  30. * <li><p> Reset the encoder via the {@link #reset reset} method, unless it
  31. * has not been used before; </p></li>
  32. *
  33. * <li><p> Invoke the {@link #encode encode} method zero or more times, as
  34. * long as additional input may be available, passing <tt>false</tt> for the
  35. * <tt>endOfInput</tt> argument and filling the input buffer and flushing the
  36. * output buffer between invocations; </p></li>
  37. *
  38. * <li><p> Invoke the {@link #encode encode} method one final time, passing
  39. * <tt>true</tt> for the <tt>endOfInput</tt> argument; and then </p></li>
  40. *
  41. * <li><p> Invoke the {@link #flush flush} method so that the encoder can
  42. * flush any internal state to the output buffer. </p></li>
  43. *
  44. * </ol>
  45. *
  46. * Each invocation of the {@link #encode encode} method will encode as many
  47. * characters as possible from the input buffer, writing the resulting bytes
  48. * to the output buffer. The {@link #encode encode} method returns when more
  49. * input is required, when there is not enough room in the output buffer, or
  50. * when an encoding error has occurred. In each case a {@link CoderResult}
  51. * object is returned to describe the reason for termination. An invoker can
  52. * examine this object and fill the input buffer, flush the output buffer, or
  53. * attempt to recover from an encoding error, as appropriate, and try again.
  54. *
  55. * <a name="ce">
  56. *
  57. * <p> There are two general types of encoding errors. If the input character
  58. * sequence is not a legal sixteen-bit Unicode sequence then the input is considered <i>malformed</i>. If
  59. * the input character sequence is legal but cannot be mapped to a valid
  60. * byte sequence in the given charset then an <i>unmappable character</i> has been encountered.
  61. *
  62. * <a name="cae">
  63. *
  64. * <p> How an encoding error is handled depends upon the action requested for
  65. * that type of error, which is described by an instance of the {@link
  66. * CodingErrorAction} class. The possible error actions are to {@link
  67. * CodingErrorAction#IGNORE </code>ignore<code>} the erroneous input, {@link
  68. * CodingErrorAction#REPORT </code>report<code>} the error to the invoker via
  69. * the returned {@link CoderResult} object, or {@link CodingErrorAction#REPLACE
  70. * </code>replace<code>} the erroneous input with the current value of the
  71. * replacement byte array. The replacement
  72. *
  73. * is initially set to the encoder's default replacement, which often
  74. * (but not always) has the initial value <tt>{</tt> <tt>(byte)'?'</tt> <tt>}</tt>
  75. *
  76. * its value may be changed via the {@link #replaceWith(byte[])
  77. * replaceWith} method.
  78. *
  79. * <p> The default action for malformed-input and unmappable-character errors
  80. * is to {@link CodingErrorAction#REPORT </code>report<code>} them. The
  81. * malformed-input error action may be changed via the {@link
  82. * #onMalformedInput(CodingErrorAction) onMalformedInput} method; the
  83. * unmappable-character action may be changed via the {@link
  84. * #onUnmappableCharacter(CodingErrorAction) onUnmappableCharacter} method.
  85. *
  86. * <p> This class is designed to handle many of the details of the encoding
  87. * process, including the implementation of error actions. An encoder for a
  88. * specific charset, which is a concrete subclass of this class, need only
  89. * implement the abstract {@link #encodeLoop encodeLoop} method, which
  90. * encapsulates the basic encoding loop. A subclass that maintains internal
  91. * state should, additionally, override the {@link #flush flush} and {@link
  92. * #reset reset} methods.
  93. *
  94. * <p> Instances of this class are not safe for use by multiple concurrent
  95. * threads. </p>
  96. *
  97. *
  98. * @version 1.37, 03/01/23
  99. * @author Mark Reinhold
  100. * @author JSR-51 Expert Group
  101. * @since 1.4
  102. *
  103. * @see ByteBuffer
  104. * @see CharBuffer
  105. * @see Charset
  106. * @see CharsetDecoder
  107. */
  108. public abstract class CharsetEncoder {
  109. private final Charset charset;
  110. private final float averageBytesPerChar;
  111. private final float maxBytesPerChar;
  112. private byte[] replacement;
  113. private CodingErrorAction malformedInputAction
  114. = CodingErrorAction.REPORT;
  115. private CodingErrorAction unmappableCharacterAction
  116. = CodingErrorAction.REPORT;
  117. // Internal states
  118. //
  119. private static final int ST_RESET = 0;
  120. private static final int ST_CODING = 1;
  121. private static final int ST_END = 2;
  122. private static final int ST_FLUSHED = 3;
  123. private int state = ST_RESET;
  124. private static String stateNames[]
  125. = { "RESET", "CODING", "CODING_END", "FLUSHED" };
  126. /**
  127. * Initializes a new encoder. The new encoder will have the given
  128. * bytes-per-char and replacement values. </p>
  129. *
  130. * @param averageBytesPerChar
  131. * A positive float value indicating the expected number of
  132. * bytes that will be produced for each input character
  133. *
  134. * @param maxBytesPerChar
  135. * A positive float value indicating the maximum number of
  136. * bytes that will be produced for each input character
  137. *
  138. * @param replacement
  139. * The initial replacement; must not be <tt>null</tt>, must have
  140. * non-zero length, must not be longer than maxBytesPerChar,
  141. * and must be {@link #isLegalReplacement </code>legal<code>}
  142. *
  143. * @throws IllegalArgumentException
  144. * If the preconditions on the parameters do not hold
  145. */
  146. protected
  147. CharsetEncoder(Charset cs,
  148. float averageBytesPerChar,
  149. float maxBytesPerChar,
  150. byte[] replacement)
  151. {
  152. this.charset = cs;
  153. if (averageBytesPerChar <= 0.0f)
  154. throw new IllegalArgumentException("Non-positive "
  155. + "averageBytesPerChar");
  156. if (maxBytesPerChar <= 0.0f)
  157. throw new IllegalArgumentException("Non-positive "
  158. + "maxBytesPerChar");
  159. this.replacement = replacement;
  160. this.averageBytesPerChar = averageBytesPerChar;
  161. this.maxBytesPerChar = maxBytesPerChar;
  162. replaceWith(replacement);
  163. }
  164. /**
  165. * Initializes a new encoder. The new encoder will have the given
  166. * bytes-per-char values and its replacement will be the
  167. * byte array <tt>{</tt> <tt>(byte)'?'</tt> <tt>}</tt>. </p>
  168. *
  169. * @param averageBytesPerChar
  170. * A positive float value indicating the expected number of
  171. * bytes that will be produced for each input character
  172. *
  173. * @param maxBytesPerChar
  174. * A positive float value indicating the maximum number of
  175. * bytes that will be produced for each input character
  176. *
  177. * @throws IllegalArgumentException
  178. * If the preconditions on the parameters do not hold
  179. */
  180. protected CharsetEncoder(Charset cs,
  181. float averageBytesPerChar,
  182. float maxBytesPerChar)
  183. {
  184. this(cs,
  185. averageBytesPerChar, maxBytesPerChar,
  186. new byte[] { (byte)'?' });
  187. }
  188. /**
  189. * Returns the charset that created this encoder. </p>
  190. *
  191. * @return This encoder's charset
  192. */
  193. public final Charset charset() {
  194. return charset;
  195. }
  196. /**
  197. * Returns this encoder's replacement value. </p>
  198. *
  199. * @return This encoder's current replacement,
  200. * which is never <tt>null</tt> and is never empty
  201. */
  202. public final byte[] replacement() {
  203. return replacement;
  204. }
  205. /**
  206. * Changes this encoder's replacement value.
  207. *
  208. * <p> This method invokes the {@link #implReplaceWith implReplaceWith}
  209. * method, passing the new replacement, after checking that the new
  210. * replacement is acceptable. </p>
  211. *
  212. * @param newReplacement
  213. *
  214. * The new replacement; must not be <tt>null</tt>, must have
  215. * non-zero length, must not be longer than the value returned by
  216. * the {@link #maxBytesPerChar maxBytesPerChar} method, and
  217. * must be {@link #isLegalReplacement </code>legal<code>}
  218. *
  219. * @return This encoder
  220. *
  221. * @throws IllegalArgumentException
  222. * If the preconditions on the parameter do not hold
  223. */
  224. public final CharsetEncoder replaceWith(byte[] newReplacement) {
  225. if (newReplacement == null)
  226. throw new IllegalArgumentException("Null replacement");
  227. int len = newReplacement.length;
  228. if (len == 0)
  229. throw new IllegalArgumentException("Empty replacement");
  230. if (len > maxBytesPerChar)
  231. throw new IllegalArgumentException("Replacement too long");
  232. if (!isLegalReplacement(newReplacement))
  233. throw new IllegalArgumentException("Illegal replacement");
  234. this.replacement = newReplacement;
  235. implReplaceWith(newReplacement);
  236. return this;
  237. }
  238. /**
  239. * Reports a change to this encoder's replacement value.
  240. *
  241. * <p> The default implementation of this method does nothing. This method
  242. * should be overridden by encoders that require notification of changes to
  243. * the replacement. </p>
  244. *
  245. * @param newReplacement
  246. */
  247. protected void implReplaceWith(byte[] newReplacement) {
  248. }
  249. private WeakReference cachedDecoder = null;
  250. /**
  251. * Tells whether or not the given byte array is a legal replacement value
  252. * for this encoder.
  253. *
  254. * <p> A replacement is legal if, and only if, it is a legal sequence of
  255. * bytes in this encoder's charset; that is, it must be possible to decode
  256. * the replacement into one or more sixteen-bit Unicode characters.
  257. *
  258. * <p> The default implementation of this method is not very efficient; it
  259. * should generally be overridden to improve performance. </p>
  260. *
  261. * @param repl The byte array to be tested
  262. *
  263. * @return <tt>true</tt> if, and only if, the given byte array
  264. * is a legal replacement value for this encoder
  265. */
  266. public boolean isLegalReplacement(byte[] repl) {
  267. WeakReference wr = cachedDecoder;
  268. CharsetDecoder dec = null;
  269. if ((wr == null) || ((dec = (CharsetDecoder)wr.get()) == null)) {
  270. dec = charset().newDecoder();
  271. dec.onMalformedInput(CodingErrorAction.REPORT);
  272. dec.onUnmappableCharacter(CodingErrorAction.REPORT);
  273. cachedDecoder = new WeakReference(dec);
  274. } else {
  275. dec.reset();
  276. }
  277. ByteBuffer bb = ByteBuffer.wrap(repl);
  278. CharBuffer cb = CharBuffer.allocate((int)(bb.remaining()
  279. * dec.maxCharsPerByte()));
  280. CoderResult cr = dec.decode(bb, cb, true);
  281. return !cr.isError();
  282. }
  283. /**
  284. * Returns this encoder's current action for malformed-input errors. </p>
  285. *
  286. * @return The current malformed-input action, which is never <tt>null</tt>
  287. */
  288. public CodingErrorAction malformedInputAction() {
  289. return malformedInputAction;
  290. }
  291. /**
  292. * Changes this encoder's action for malformed-input errors. </p>
  293. *
  294. * <p> This method invokes the {@link #implOnMalformedInput
  295. * implOnMalformedInput} method, passing the new action. </p>
  296. *
  297. * @param newAction The new action; must not be <tt>null</tt>
  298. *
  299. * @return This encoder
  300. *
  301. * @throws IllegalArgumentException
  302. * If the precondition on the parameter does not hold
  303. */
  304. public final CharsetEncoder onMalformedInput(CodingErrorAction newAction) {
  305. if (newAction == null)
  306. throw new IllegalArgumentException("Null action");
  307. malformedInputAction = newAction;
  308. implOnMalformedInput(newAction);
  309. return this;
  310. }
  311. /**
  312. * Reports a change to this encoder's malformed-input action.
  313. *
  314. * <p> The default implementation of this method does nothing. This method
  315. * should be overridden by encoders that require notification of changes to
  316. * the malformed-input action. </p>
  317. */
  318. protected void implOnMalformedInput(CodingErrorAction newAction) { }
  319. /**
  320. * Returns this encoder's current action for unmappable-character errors.
  321. * </p>
  322. *
  323. * @return The current unmappable-character action, which is never
  324. * <tt>null</tt>
  325. */
  326. public CodingErrorAction unmappableCharacterAction() {
  327. return unmappableCharacterAction;
  328. }
  329. /**
  330. * Changes this encoder's action for unmappable-character errors.
  331. *
  332. * <p> This method invokes the {@link #implOnUnmappableCharacter
  333. * implOnUnmappableCharacter} method, passing the new action. </p>
  334. *
  335. * @param newAction The new action; must not be <tt>null</tt>
  336. *
  337. * @return This encoder
  338. *
  339. * @throws IllegalArgumentException
  340. * If the precondition on the parameter does not hold
  341. */
  342. public final CharsetEncoder onUnmappableCharacter(CodingErrorAction
  343. newAction)
  344. {
  345. if (newAction == null)
  346. throw new IllegalArgumentException("Null action");
  347. unmappableCharacterAction = newAction;
  348. implOnUnmappableCharacter(newAction);
  349. return this;
  350. }
  351. /**
  352. * Reports a change to this encoder's unmappable-character action.
  353. *
  354. * <p> The default implementation of this method does nothing. This method
  355. * should be overridden by encoders that require notification of changes to
  356. * the unmappable-character action. </p>
  357. */
  358. protected void implOnUnmappableCharacter(CodingErrorAction newAction) { }
  359. /**
  360. * Returns the average number of bytes that will be produced for each
  361. * character of input. This heuristic value may be used to estimate the size
  362. * of the output buffer required for a given input sequence. </p>
  363. *
  364. * @return The average number of bytes produced
  365. * per character of input
  366. */
  367. public final float averageBytesPerChar() {
  368. return averageBytesPerChar;
  369. }
  370. /**
  371. * Returns the maximum number of bytes that will be produced for each
  372. * character of input. This value may be used to compute the worst-case size
  373. * of the output buffer required for a given input sequence. </p>
  374. *
  375. * @return The maximum number of bytes that will be produced per
  376. * character of input
  377. */
  378. public final float maxBytesPerChar() {
  379. return maxBytesPerChar;
  380. }
  381. /**
  382. * Encodes as many characters as possible from the given input buffer,
  383. * writing the results to the given output buffer.
  384. *
  385. * <p> The buffers are read from, and written to, starting at their current
  386. * positions. At most {@link Buffer#remaining in.remaining()} characters
  387. * will be read and at most {@link Buffer#remaining out.remaining()}
  388. * bytes will be written. The buffers' positions will be advanced to
  389. * reflect the characters read and the bytes written, but their marks and
  390. * limits will not be modified.
  391. *
  392. * <p> In addition to reading characters from the input buffer and writing
  393. * bytes to the output buffer, this method returns a {@link CoderResult}
  394. * object to describe its reason for termination:
  395. *
  396. * <ul>
  397. *
  398. * <li><p> {@link CoderResult#UNDERFLOW} indicates that as much of the
  399. * input buffer as possible has been encoded. If there are no characters
  400. * remaining and the invoker has no further input then the encoding
  401. * operation is complete. Otherwise there is insufficient input for the
  402. * operation to proceed, so this method should be invoked again with
  403. * further input. </p></li>
  404. *
  405. * <li><p> {@link CoderResult#OVERFLOW} indicates that the output buffer
  406. * is full. This method should be invoked again with a non-full output
  407. * buffer. </p></li>
  408. *
  409. * <li><p> A {@link CoderResult#malformedForLength
  410. * </code>malformed-input<code>} result indicates that a malformed-input
  411. * error has been detected. The malformed characters begin at the input
  412. * buffer's (possibly incremented) position; the number of malformed
  413. * characters may be determined by invoking the result object's {@link
  414. * CoderResult#length length} method. This case applies only if the
  415. * {@link #onMalformedInput </code>malformed action<code>} of this encoder
  416. * is {@link CodingErrorAction#REPORT}; otherwise the malformed input
  417. * will be ignored or replaced, as requested. </p></li>
  418. *
  419. * <li><p> An {@link CoderResult#unmappableForLength
  420. * </code>unmappable-character<code>} result indicates that an
  421. * unmappable-character error has been detected. The characters that
  422. * encode the unmappable character begin at the input buffer's (possibly
  423. * incremented) position; the number of such characters may be determined
  424. * by invoking the result object's {@link CoderResult#length length}
  425. * method. This case applies only if the {@link #onUnmappableCharacter
  426. * </code>unmappable action<code>} of this encoder is {@link
  427. * CodingErrorAction#REPORT}; otherwise the unmappable character will be
  428. * ignored or replaced, as requested. </p></li>
  429. *
  430. * </ul>
  431. *
  432. * In any case, if this method is to be reinvoked in the same encoding
  433. * operation then care should be taken to preserve any characters remaining
  434. * in the input buffer so that they are available to the next invocation.
  435. *
  436. * <p> The <tt>endOfInput</tt> parameter advises this method as to whether
  437. * the invoker can provide further input beyond that contained in the given
  438. * input buffer. If there is a possibility of providing additional input
  439. * then the invoker should pass <tt>false</tt> for this parameter; if there
  440. * is no possibility of providing further input then the invoker should
  441. * pass <tt>true</tt>. It is not erroneous, and in fact it is quite
  442. * common, to pass <tt>false</tt> in one invocation and later discover that
  443. * no further input was actually available. It is critical, however, that
  444. * the final invocation of this method in a sequence of invocations always
  445. * pass <tt>true</tt> so that any remaining unencoded input will be treated
  446. * as being malformed.
  447. *
  448. * <p> This method works by invoking the {@link #encodeLoop encodeLoop}
  449. * method, interpreting its results, handling error conditions, and
  450. * reinvoking it as necessary. </p>
  451. *
  452. *
  453. * @param in
  454. * The input character buffer
  455. *
  456. * @param out
  457. * The output byte buffer
  458. *
  459. * @param endOfInput
  460. * <tt>true</tt> if, and only if, the invoker can provide no
  461. * additional input characters beyond those in the given buffer
  462. *
  463. * @return A coder-result object describing the reason for termination
  464. *
  465. * @throws IllegalStateException
  466. * If a encoding operation is already in progress and the previous
  467. * step was an invocation neither of the {@link #reset reset}
  468. * method, nor of this method with a value of <tt>false</tt> for
  469. * the <tt>endOfInput</tt> parameter, nor of this method with a
  470. * value of <tt>true</tt> for the <tt>endOfInput</tt> parameter
  471. * but a return value indicating an incomplete encoding operation
  472. *
  473. * @throws CoderMalfunctionError
  474. * If an invocation of the encodeLoop method threw
  475. * an unexpected exception
  476. */
  477. public final CoderResult encode(CharBuffer in, ByteBuffer out,
  478. boolean endOfInput)
  479. {
  480. int newState = endOfInput ? ST_END : ST_CODING;
  481. if ((state != ST_RESET) && (state != ST_CODING)
  482. && !(endOfInput && (state == ST_END)))
  483. throwIllegalStateException(state, newState);
  484. state = newState;
  485. for (;;) {
  486. CoderResult cr;
  487. try {
  488. cr = encodeLoop(in, out);
  489. } catch (BufferUnderflowException x) {
  490. throw new CoderMalfunctionError(x);
  491. } catch (BufferOverflowException x) {
  492. throw new CoderMalfunctionError(x);
  493. }
  494. if (cr.isOverflow())
  495. return cr;
  496. if (cr.isUnderflow()) {
  497. if (endOfInput && in.hasRemaining()) {
  498. cr = CoderResult.malformedForLength(in.remaining());
  499. // Fall through to malformed-input case
  500. } else {
  501. return cr;
  502. }
  503. }
  504. CodingErrorAction action = null;
  505. if (cr.isMalformed())
  506. action = malformedInputAction;
  507. else if (cr.isUnmappable())
  508. action = unmappableCharacterAction;
  509. else
  510. assert false : cr.toString();
  511. if (action == CodingErrorAction.REPORT)
  512. return cr;
  513. if (action == CodingErrorAction.REPLACE) {
  514. if (out.remaining() < replacement.length)
  515. return CoderResult.OVERFLOW;
  516. out.put(replacement);
  517. }
  518. if ((action == CodingErrorAction.IGNORE)
  519. || (action == CodingErrorAction.REPLACE)) {
  520. // Skip erroneous input either way
  521. in.position(in.position() + cr.length());
  522. continue;
  523. }
  524. assert false;
  525. }
  526. }
  527. /**
  528. * Flushes this encoder.
  529. *
  530. * <p> Some encoders maintain internal state and may need to write some
  531. * final bytes to the output buffer once the overall input sequence has
  532. * been read.
  533. *
  534. * <p> Any additional output is written to the output buffer beginning at
  535. * its current position. At most {@link Buffer#remaining out.remaining()}
  536. * bytes will be written. The buffer's position will be advanced
  537. * appropriately, but its mark and limit will not be modified.
  538. *
  539. * <p> If this method completes successfully then it returns {@link
  540. * CoderResult#UNDERFLOW}. If there is insufficient room in the output
  541. * buffer then it returns {@link CoderResult#OVERFLOW}. If this happens
  542. * then this method must be invoked again, with an output buffer that has
  543. * more room, in order to complete the current <a href="#steps">encoding
  544. * operation</a>.
  545. *
  546. * <p> This method invokes the {@link #implFlush implFlush} method to
  547. * perform the actual flushing operation. </p>
  548. *
  549. * @param out
  550. * The output byte buffer
  551. *
  552. * @return A coder-result object, either {@link CoderResult#UNDERFLOW} or
  553. * {@link CoderResult#OVERFLOW}
  554. *
  555. * @throws IllegalStateException
  556. * If the previous step of the current encoding operation was an
  557. * invocation neither of the {@link #reset reset} method nor of
  558. * the three-argument {@link
  559. * #encode(CharBuffer,ByteBuffer,boolean) encode} method
  560. * with a value of <tt>true</tt> for the <tt>endOfInput</tt>
  561. * parameter
  562. */
  563. public final CoderResult flush(ByteBuffer out) {
  564. if (state != ST_END)
  565. throwIllegalStateException(state, ST_FLUSHED);
  566. state = ST_FLUSHED;
  567. return implFlush(out);
  568. }
  569. /**
  570. * Flushes this encoder.
  571. *
  572. * <p> The default implementation of this method does nothing, and always
  573. * returns {@link CoderResult#UNDERFLOW}. This method should be overridden
  574. * by encoders that may need to write final bytes to the output buffer
  575. * once the entire input sequence has been read. </p>
  576. *
  577. * @param out
  578. * The output byte buffer
  579. *
  580. * @return A coder-result object, either {@link CoderResult#UNDERFLOW} or
  581. * {@link CoderResult#OVERFLOW}
  582. */
  583. protected CoderResult implFlush(ByteBuffer out) {
  584. return CoderResult.UNDERFLOW;
  585. }
  586. /**
  587. * Resets this encoder, clearing any internal state.
  588. *
  589. * <p> This method resets charset-independent state and also invokes the
  590. * {@link #implReset() implReset} method in order to perform any
  591. * charset-specific reset actions. </p>
  592. *
  593. * @return This encoder
  594. *
  595. */
  596. public final CharsetEncoder reset() {
  597. implReset();
  598. state = ST_RESET;
  599. return this;
  600. }
  601. /**
  602. * Resets this encoder, clearing any charset-specific internal state.
  603. *
  604. * <p> The default implementation of this method does nothing. This method
  605. * should be overridden by encoders that maintain internal state. </p>
  606. */
  607. protected void implReset() { }
  608. /**
  609. * Encodes one or more characters into one or more bytes.
  610. *
  611. * <p> This method encapsulates the basic encoding loop, encoding as many
  612. * characters as possible until it either runs out of input, runs out of room
  613. * in the output buffer, or encounters a encoding error. This method is
  614. * invoked by the {@link #encode encode} method, which handles result
  615. * interpretation and error recovery.
  616. *
  617. * <p> The buffers are read from, and written to, starting at their current
  618. * positions. At most {@link Buffer#remaining in.remaining()} characters
  619. * will be read, and at most {@link Buffer#remaining out.remaining()}
  620. * bytes will be written. The buffers' positions will be advanced to
  621. * reflect the characters read and the bytes written, but their marks and
  622. * limits will not be modified.
  623. *
  624. * <p> This method returns a {@link CoderResult} object to describe its
  625. * reason for termination, in the same manner as the {@link #encode encode}
  626. * method. Most implementations of this method will handle encoding errors
  627. * by returning an appropriate result object for interpretation by the
  628. * {@link #encode encode} method. An optimized implementation may instead
  629. * examine the relevant error action and implement that action itself.
  630. *
  631. * <p> An implementation of this method may perform arbitrary lookahead by
  632. * returning {@link CoderResult#UNDERFLOW} until it receives sufficient
  633. * input. </p>
  634. *
  635. * @param in
  636. * The input character buffer
  637. *
  638. * @param out
  639. * The output byte buffer
  640. *
  641. * @return A coder-result object describing the reason for termination
  642. */
  643. protected abstract CoderResult encodeLoop(CharBuffer in,
  644. ByteBuffer out);
  645. /**
  646. * Convenience method that encodes the remaining content of a single input
  647. * character buffer into a newly-allocated byte buffer.
  648. *
  649. * <p> This method implements an entire <a href="#steps">encoding
  650. * operation</a> that is, it resets this encoder, then it encodes the
  651. * characters in the given character buffer, and finally it flushes this
  652. * encoder. This method should therefore not be invoked if a encoding
  653. * operation is already in progress. </p>
  654. *
  655. * @param in
  656. * The input character buffer
  657. *
  658. * @return A newly-allocated byte buffer containing the result of the
  659. * encoding operation. The buffer's position will be zero and its
  660. * limit will follow the last byte written.
  661. *
  662. * @throws IllegalStateException
  663. * If an encoding operation is already in progress
  664. *
  665. * @throws MalformedInputException
  666. * If the character sequence starting at the input buffer's current
  667. * position is not a legal sixteen-bit Unicode sequence and the current malformed-input action
  668. * is {@link CodingErrorAction#REPORT}
  669. *
  670. * @throws UnmappableCharacterException
  671. * If the character sequence starting at the input buffer's current
  672. * position cannot be mapped to an equivalent byte sequence and
  673. * the current unmappable-character action is {@link
  674. * CodingErrorAction#REPORT}
  675. */
  676. public final ByteBuffer encode(CharBuffer in)
  677. throws CharacterCodingException
  678. {
  679. int n = (int)(in.remaining() * averageBytesPerChar());
  680. ByteBuffer out = ByteBuffer.allocate(n);
  681. if (n == 0)
  682. return out;
  683. reset();
  684. for (;;) {
  685. CoderResult cr;
  686. if (in.hasRemaining())
  687. cr = encode(in, out, true);
  688. else
  689. cr = flush(out);
  690. if (cr.isUnderflow())
  691. break;
  692. if (cr.isOverflow()) {
  693. n *= 2;
  694. ByteBuffer o = ByteBuffer.allocate(n);
  695. out.flip();
  696. o.put(out);
  697. out = o;
  698. continue;
  699. }
  700. cr.throwException();
  701. }
  702. out.flip();
  703. return out;
  704. }
  705. private boolean canEncode(CharBuffer cb) {
  706. if (state == ST_FLUSHED)
  707. reset();
  708. else if (state != ST_RESET)
  709. throwIllegalStateException(state, ST_CODING);
  710. CodingErrorAction ma = malformedInputAction();
  711. CodingErrorAction ua = unmappableCharacterAction();
  712. try {
  713. onMalformedInput(CodingErrorAction.REPORT);
  714. onUnmappableCharacter(CodingErrorAction.REPORT);
  715. encode(cb);
  716. } catch (CharacterCodingException x) {
  717. return false;
  718. } finally {
  719. onMalformedInput(ma);
  720. onUnmappableCharacter(ua);
  721. reset();
  722. }
  723. return true;
  724. }
  725. /**
  726. * Tells whether or not this encoder can encode the given character.
  727. *
  728. * <p> This method returns <tt>false</tt> if the given character is a
  729. * surrogate character; such characters can be interpreted only when they
  730. * are members of a pair consisting of a high surrogate followed by a low
  731. * surrogate. The {@link #canEncode(java.lang.CharSequence)
  732. * canEncode(CharSequence)} method may be used to test whether or not a
  733. * character sequence can be encoded.
  734. *
  735. * <p> This method may modify this encoder's state; it should therefore not
  736. * be invoked if an <a href="#steps">encoding operation</a> is already in
  737. * progress.
  738. *
  739. * <p> The default implementation of this method is not very efficient; it
  740. * should generally be overridden to improve performance. </p>
  741. *
  742. * @return <tt>true</tt> if, and only if, this encoder can encode
  743. * the given character
  744. *
  745. * @throws IllegalStateException
  746. * If an encoding operation is already in progress
  747. */
  748. public boolean canEncode(char c) {
  749. CharBuffer cb = CharBuffer.allocate(1);
  750. cb.put(c);
  751. cb.flip();
  752. return canEncode(cb);
  753. }
  754. /**
  755. * Tells whether or not this encoder can encode the given character
  756. * sequence.
  757. *
  758. * <p> If this method returns <tt>false</tt> for a particular character
  759. * sequence then more information about why the sequence cannot be encoded
  760. * may be obtained by performing a full <a href="#steps">encoding
  761. * operation</a>.
  762. *
  763. * <p> This method may modify this encoder's state; it should therefore not
  764. * be invoked if an encoding operation is already in progress.
  765. *
  766. * <p> The default implementation of this method is not very efficient; it
  767. * should generally be overridden to improve performance. </p>
  768. *
  769. * @return <tt>true</tt> if, and only if, this encoder can encode
  770. * the given character without throwing any exceptions and without
  771. * performing any replacements
  772. *
  773. * @throws IllegalStateException
  774. * If an encoding operation is already in progress
  775. */
  776. public boolean canEncode(CharSequence cs) {
  777. CharBuffer cb;
  778. if (cs instanceof CharBuffer)
  779. cb = ((CharBuffer)cs).duplicate();
  780. else
  781. cb = CharBuffer.wrap(cs.toString());
  782. return canEncode(cb);
  783. }
  784. private void throwIllegalStateException(int from, int to) {
  785. throw new IllegalStateException("Current state = " + stateNames[from]
  786. + ", new state = " + stateNames[to]);
  787. }
  788. }