public static int encode(final CharsetEncoder ce, final char[] ca, final int off, final int len, final byte[] targetArray) { if (len == 0) { return 0; } if (ce instanceof ArrayEncoder) { return ((ArrayEncoder) ce).encode(ca, off, len, targetArray); } else { ce.reset(); ByteBuffer bb = ByteBuffer.wrap(targetArray); CharBuffer cb = CharBuffer.wrap(ca, off, len); try { CoderResult cr = ce.encode(cb, bb, true); if (!cr.isUnderflow()) { cr.throwException(); } cr = ce.flush(bb); if (!cr.isUnderflow()) { cr.throwException(); } } catch (CharacterCodingException x) { throw new InternalError("Should never throw a CharacterCodingException, probably a JVM issue", x); } return bb.position(); } }
public static int encode(final CharsetEncoder ce, final char[] ca, final int off, final int len, final byte[] targetArray) { if (len == 0) { return 0; } if (ce instanceof ArrayEncoder) { return ((ArrayEncoder) ce).encode(ca, off, len, targetArray); } else { ce.reset(); ByteBuffer bb = ByteBuffer.wrap(targetArray); CharBuffer cb = CharBuffer.wrap(ca, off, len); try { CoderResult cr = ce.encode(cb, bb, true); if (!cr.isUnderflow()) { cr.throwException(); } cr = ce.flush(bb); if (!cr.isUnderflow()) { cr.throwException(); } } catch (CharacterCodingException x) { throw new InternalError("Should never throw a CharacterCodingException, probably a JVM issue", x); } return bb.position(); } }
@Substitute byte[] getBytes(String s) { CharsetEncoder ce = encoder().reset(); char[] ca = s.toCharArray(); int len = (int)(ca.length * ce.maxBytesPerChar()); byte[] ba = new byte[len]; if (len == 0) return ba; // UTF-8 only for now. Other ArrayDeocder only handles // CodingErrorAction.REPLACE mode. if (isUTF8 && ce instanceof ArrayEncoder) { int blen = ((ArrayEncoder)ce).encode(ca, 0, ca.length, ba); if (blen == -1) // malformed throw new IllegalArgumentException("MALFORMED"); return Arrays.copyOf(ba, blen); } ByteBuffer bb = ByteBuffer.wrap(ba); CharBuffer cb = CharBuffer.wrap(ca); CoderResult cr = ce.encode(cb, bb, true); if (!cr.isUnderflow()) throw new IllegalArgumentException(cr.toString()); cr = ce.flush(bb); if (!cr.isUnderflow()) throw new IllegalArgumentException(cr.toString()); if (bb.position() == ba.length) // defensive copy? return ba; else return Arrays.copyOf(ba, bb.position()); }