use of sun.nio.cs.ArrayEncoder in project Bytecoder by mirkosertic.
the class StringCoding method encode.
static byte[] encode(Charset cs, byte coder, byte[] val) {
if (cs == UTF_8) {
return encodeUTF8(coder, val);
} else if (cs == ISO_8859_1) {
return encode8859_1(coder, val);
} else if (cs == US_ASCII) {
return encodeASCII(coder, val);
}
CharsetEncoder ce = cs.newEncoder();
// fastpath for ascii compatible
if (coder == LATIN1 && (((ce instanceof ArrayEncoder) && ((ArrayEncoder) ce).isASCIICompatible() && !hasNegatives(val, 0, val.length)))) {
return Arrays.copyOf(val, val.length);
}
// assume LATIN1=0/UTF16=1;
int len = val.length >> coder;
int en = scale(len, ce.maxBytesPerChar());
byte[] ba = new byte[en];
if (len == 0) {
return ba;
}
boolean isTrusted = cs.getClass().getClassLoader0() == null || System.getSecurityManager() == null;
ce.onMalformedInput(CodingErrorAction.REPLACE).onUnmappableCharacter(CodingErrorAction.REPLACE).reset();
if (ce instanceof ArrayEncoder) {
if (!isTrusted) {
val = Arrays.copyOf(val, val.length);
}
int blen = (coder == LATIN1) ? ((ArrayEncoder) ce).encodeFromLatin1(val, 0, len, ba) : ((ArrayEncoder) ce).encodeFromUTF16(val, 0, len, ba);
if (blen != -1) {
return safeTrim(ba, blen, isTrusted);
}
}
char[] ca = (coder == LATIN1) ? StringLatin1.toChars(val) : StringUTF16.toChars(val);
ByteBuffer bb = ByteBuffer.wrap(ba);
CharBuffer cb = CharBuffer.wrap(ca, 0, 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 Error(x);
}
return safeTrim(ba, bb.position(), isTrusted);
}
use of sun.nio.cs.ArrayEncoder in project spf4j by zolyfarkas.
the class Strings method encode.
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();
}
}
Aggregations