/** * Encode a valid Unicode codepoint as a sequence of UTF-8 bytes into a new allocated array. * * @param codepoint Unicode codepoint to encode * @return number of bytes written * @throws IndexOutOfBoundsException if there is insufficient room for the encoded data in the given array */ public static byte[] encode(int codepoint) { byte[] destination = new byte[codePointAsUtf8Length(codepoint)]; encode(codepoint, destination, 0); return destination; }
/** * Encode a valid Unicode codepoint as a sequence of UTF-8 bytes into an * OutputStream. * * @param codepoint * Unicode codepoint to encode * @param destination * buffer to write into * @return number of bytes written * @throws IOException * propagated from stream */ public static int encode(int codepoint, OutputStream destination) throws IOException { byte firstByte = firstByte(codepoint); int toWrite = codePointAsUtf8Length(codepoint); int leftToWrite = toWrite - 1; destination.write(firstByte); while (leftToWrite-- > 0) { destination.write(trailingOctet(codepoint, leftToWrite)); } return toWrite; }
/** * Encode a valid Unicode codepoint as a sequence of UTF-8 bytes into a * ByteBuffer. * * @param codepoint * Unicode codepoint to encode * @param destination * buffer to write into * @throws BufferOverflowException * if the buffer's limit is met while writing (propagated from * the ByteBuffer) * @throws ReadOnlyBufferException * if the buffer is read only (propagated from the ByteBuffer) */ public static void encode(int codepoint, ByteBuffer destination) { byte firstByte = firstByte(codepoint); int leftToWrite = codePointAsUtf8Length(codepoint) - 1; destination.put(firstByte); while (leftToWrite-- > 0) { destination.put(trailingOctet(codepoint, leftToWrite)); } }
/** * Encode a valid Unicode codepoint as a sequence of UTF-8 bytes into an array. * * @param codepoint Unicode codepoint to encode * @param destination array to write into * @param offset index of first byte written * @return index of the first byte after the last byte written (i.e. offset plus number of bytes written) * @throws IndexOutOfBoundsException if there is insufficient room for the encoded data in the given array */ public static int encode(int codepoint, byte[] destination, int offset) { int writeOffset = offset; byte firstByte = firstByte(codepoint); int leftToWrite = codePointAsUtf8Length(codepoint) - 1; destination[writeOffset++] = firstByte; while (leftToWrite-- > 0) { destination[writeOffset++] = trailingOctet(codepoint, leftToWrite); } return writeOffset; }