1 /* Copyright (C) 2005 Free Software Foundation
3 This file is part of libgcj.
5 This software is copyrighted work licensed under the terms of the
6 Libgcj License. Please consult the file "LIBGCJ_LICENSE" for
9 package gnu
.gcj
.convert
;
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
;
20 * Adaptor class that allow any {@link Charset} to be used
21 * as a BytesToUnicode converter.
23 public class BytesToCharsetAdaptor
extends BytesToUnicode
26 * The CharsetDecoder that does all the work.
28 private final CharsetDecoder decoder
;
31 * ByteBuffer wrapper for this.buf.
33 private ByteBuffer inBuf
;
36 * Create a new BytesToCharsetAdaptor for the given Charset.
38 * @param cs the Charset.
40 public BytesToCharsetAdaptor(Charset cs
)
42 this(cs
.newDecoder());
46 * Create a new BytesToCharsetAdaptor for the given CharsetDecoder.
48 * @param dec the CharsetDecoder.
50 public BytesToCharsetAdaptor(CharsetDecoder dec
)
53 // Use default replacments on bad input so that we don't have to
55 decoder
.onMalformedInput(CodingErrorAction
.REPLACE
);
56 decoder
.onUnmappableCharacter(CodingErrorAction
.REPLACE
);
60 * Return the decoder's name. The backing Charset's name is
65 public String
getName()
67 return EncodingHelper
.getOldCanonical(decoder
.charset().name());
70 public int read(char[] outbuffer
, int outpos
, int count
)
72 if (inBuf
== null || ! inBuf
.hasArray() || inBuf
.array() != inbuffer
)
73 inBuf
= ByteBuffer
.wrap(inbuffer
);
74 inBuf
.limit(inpos
+ inlength
);
75 inBuf
.position(inpos
);
77 CharBuffer outBuf
= CharBuffer
.wrap(outbuffer
, outpos
, count
);
78 decoder
.decode(inBuf
, outBuf
, false);
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
;
86 // These aren't cached.