private void assertMatch(final String string, final int... bytes) { byte[] byteArray = new byte[bytes.length]; for (int i = 0; i < byteArray.length; i++) { byteArray[i] = (byte) bytes[i]; } // test string to bytes byte[] actualBytes = UTF8Util.convert(string); assertArrayEquals(byteArray, actualBytes); // test bytes to string String actualString = UTF8Util.convert(byteArray); assertEquals(string, actualString); }
/* * Converts unicodes to encoded \uxxxx and writes out any of the * characters in specialSaveChars with a preceding slash * * @param theString * the String needing convert. * @param dst * Save of the result * @param offset * the offset of result * @param escapeSpace * if <code>true</code>, escape Space * @param lengthFlag * Whether add one byte of length in the result. * <code>true</code> add one byte of length in the result * @param getLengthFlag * Calculate the length of result, if <code>true</code>, theString length that return. * @return if getLengthFlag = false, return offset of the result. * if getLengthFlag = true, the length of the sequence of characters represented by this * object. */ public static int saveConvert( String theString, byte[] dst, int offset, boolean escapeSpace, boolean lengthFlag, boolean getLengthFlag) { if (false == getLengthFlag && (null == dst || dst.length < (offset + (lengthFlag ? 1 : 0)) || dst.length < 1 || offset < 0)) { return -1; } if (null == theString) { theString = ""; } int length; byte[] outBuffer = null; if (getLengthFlag) { length = UTF8Util.char2ByteUTF8(theString, 0, theString.length(), null, 0, 0, true); } else { outBuffer = UTF8Util.string2BytesUTF8(theString); length = outBuffer.length; } if (length > 255) { length = 255; } if (getLengthFlag) { if (lengthFlag) { length = length + 1; } } else { if (dst.length >= offset + length + (lengthFlag ? 1 : 0)) { if (lengthFlag) { dst[offset] = (byte) (length & 0xFF); offset++; } System.arraycopy(outBuffer, 0, dst, offset, length); offset += length; length = offset; } else { length = -1; } } outBuffer = null; return length; }
/* * Converts encoded \uxxxx to unicode chars and changes special saved * chars to their original forms * * @param s * the byte arrary needing convert. * @param offset * the offset of byte arrary * @param lengthFlag * Whether add one byte of length in the result. * <code>true</code> add one byte of length in the result * @return the convert result of the byte arrary. */ public static String loadConvert(byte[] s, int offset, boolean lengthFlag) throws IllegalArgumentException { if (null == s || (offset + (lengthFlag ? 1 : 0)) > s.length) throw new IllegalArgumentException("invalid byte arrary"); int len = (s.length - offset); if (lengthFlag) { len = s[offset] & 0xFF; offset++; } return UTF8Util.bytes2StringUTF8(s, offset, len, true); }
private void assertSurvivesRoundTrip(final String original) { String roundtripped = UTF8Util.convert(UTF8Util.convert(original)); assertEquals(original, roundtripped); }