{@inheritDoc}
Note that this method might return CoderResult.OVERFLOW
,
even though there is sufficient space available in the output buffer.
This is done to force the broken implementation of
{@link java.nio.charset.CharsetEncoder#encode(CharBuffer)} to call flush
(the buggy method is final
, thus cannot be overridden).
However, String.getBytes() fails if CoderResult.OVERFLOW is returned,
since this assumes it always allocates sufficient bytes (maxBytesPerChar
* nr_of_chars). Thus, as an extra check, the size of the input buffer is
compared against the size of the output buffer. A static variable is used
to indicate if a broken java version is used.
It is not possible to directly write the last few bytes, since more bytes
might be waiting to be encoded then those available in the input buffer.
while (in.hasRemaining()) {
if (out.remaining() < 4)
return CoderResult.OVERFLOW;
char ch = in.get();
if (cs.canEncodeDirectly(ch)) {
unshift(out, ch);
out.put((byte)ch);
} else if (!base64mode && ch == shift) {
out.put(shift);
out.put(unshift);
} else
encodeBase64(ch, out);
}
/*
* <HACK type="ugly"> These lines are required to trick JDK 1.5 and
* earlier into flushing when using Charset.encode(String),
* Charset.encode(CharBuffer) or CharsetEncoder.encode(CharBuffer)
* Without them, the last few bytes may be missing.
*/
if (base64mode && useUglyHackToForceCallToFlushInJava5
&& out.limit() != MAX_BYTES_PER_CHAR * in.limit())
return CoderResult.OVERFLOW;
/* </HACK> */
return CoderResult.UNDERFLOW;