BytesToCharsetAdaptor.java 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /* Copyright (C) 2005, 2007 Free Software Foundation
  2. This file is part of libgcj.
  3. This software is copyrighted work licensed under the terms of the
  4. Libgcj License. Please consult the file "LIBGCJ_LICENSE" for
  5. details. */
  6. package gnu.gcj.convert;
  7. import java.nio.ByteBuffer;
  8. import java.nio.CharBuffer;
  9. import java.nio.charset.Charset;
  10. import java.nio.charset.CharsetDecoder;
  11. import java.nio.charset.CodingErrorAction;
  12. import java.nio.charset.CoderResult;
  13. import gnu.java.nio.charset.EncodingHelper;
  14. /**
  15. * Adaptor class that allow any {@link Charset} to be used
  16. * as a BytesToUnicode converter.
  17. */
  18. public class BytesToCharsetAdaptor extends BytesToUnicode
  19. {
  20. /**
  21. * The CharsetDecoder that does all the work.
  22. */
  23. private final CharsetDecoder decoder;
  24. /**
  25. * ByteBuffer wrapper for this.buf.
  26. */
  27. private ByteBuffer inBuf;
  28. /**
  29. * Create a new BytesToCharsetAdaptor for the given Charset.
  30. *
  31. * @param cs the Charset.
  32. */
  33. public BytesToCharsetAdaptor(Charset cs)
  34. {
  35. this(cs.newDecoder());
  36. }
  37. /**
  38. * Create a new BytesToCharsetAdaptor for the given CharsetDecoder.
  39. *
  40. * @param dec the CharsetDecoder.
  41. */
  42. public BytesToCharsetAdaptor(CharsetDecoder dec)
  43. {
  44. decoder = dec;
  45. // Use default replacments on bad input so that we don't have to
  46. // deal with errors.
  47. decoder.onMalformedInput(CodingErrorAction.REPLACE);
  48. decoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
  49. }
  50. /**
  51. * Return the decoder's name. The backing Charset's name is
  52. * returned.
  53. *
  54. * @return The name.
  55. */
  56. public String getName()
  57. {
  58. return EncodingHelper.getOldCanonical(decoder.charset().name());
  59. }
  60. public int read(char[] outbuffer, int outpos, int count)
  61. {
  62. if (inBuf == null || ! inBuf.hasArray() || inBuf.array() != inbuffer)
  63. inBuf = ByteBuffer.wrap(inbuffer);
  64. inBuf.limit(inlength);
  65. inBuf.position(inpos);
  66. CharBuffer outBuf = CharBuffer.wrap(outbuffer, outpos, count);
  67. decoder.decode(inBuf, outBuf, false);
  68. // Update this.inpos to reflect the bytes consumed.
  69. inpos = inBuf.position();
  70. // Return the number of characters that were written to outbuffer.
  71. return outBuf.position() - outpos;
  72. }
  73. // These aren't cached.
  74. public void done()
  75. {
  76. }
  77. }