Source for gnu.gcj.convert.BytesToCharsetAdaptor

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