wdk
wdk

Reputation: 373

Process next character (full unicode code point) streaming from Java input stream

I need to parse UTF-8 input streaming character by character (UTF-8 code point, not Java's char). What is the best approach?

Update of question to make it more clear (thanks @skomisa): So the following non streaming:

private static String replaceNonBPMWithUnknownCharacter(final String input) {
    StringBuilder result = new StringBuilder(input.length());
    input.codePoints().forEach((codePoint) -> {
        if (isBmpCodePoint(codePoint)) {
            result.append('\ufffd');
        } else {
            result.append(isBmpCodePoint(codePoint) ? toChars(codePoint) : REPLACEMENT_CHAR);
        }
    });
    return result.toString();
}


String result = replaceNonBPMWithUnknownCharacter("\uD83D\uDE0E? X")

I would like to have a streaming version, e.g:

InputStream stream = replaceNonBPMWithUnknownCharacter(new ByteArrayInputStream("\uD83D\uDE0E? Y".getBytes(UTF_8)))

Which uses as less as possible cpu and memory. Following question is similair but is non-streaming: Read next character (full unicode code point) from Java input stream.

Most important: How do I read a codepoint from the stream? (so how can I convert a stream of bytes from which I know they are UTF-8 encoded to a stream of codepoints).

Upvotes: 2

Views: 574

Answers (1)

skomisa
skomisa

Reputation: 17363

First note that:

  • A UTF-8 character can be made up of a 1, 2, 3 or 4 byte sequence.
  • The number of bytes in the character is determined by certain bit settings in the first (or only) byte. See the Table 3.6 UTF-8 Bit Distribution in the Unicode Specification for details.

So the overall approach is:

  • Read the first byte and examine its bit pattern to determine how many bytes are in the first character.
  • Read any subsequent bytes needed for the first character.
  • Create a String based on the bytes that comprise that character, and then call String.codePointAt() to obtain its code point.
  • Add that code point to a List<Integer>.
  • Repeat all the previous steps for subsequent bytes until EOF.
  • Return the List<Integer> as a stream of code points.

Here's the code, using some random Unicode characters of variable byte length for data:

import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
import static java.nio.charset.StandardCharsets.UTF_8;

public class Main {

    public static void main(String[] args) {
        String text = "¢\uD841\uDF31\u30918औWあش";
        Stream<Integer> codePoints = Main.processByteStream(new ByteArrayInputStream(text.getBytes(UTF_8)));
        codePoints.forEach(System.out::println);
    }

    /**
     * Processes a stream of bytes, and returns a Stream of Unicode codepoints
     * associated with the characters derived from that byte stream.
     *
     * @param bais ByteArrayInputStream to be processed.
     * @return A stream of Unicode codepoints derived from UTF-8 characters in the supplied stream.
     */
    private static Stream<Integer> processByteStream(ByteArrayInputStream bais) {

        int nextByte = 0;
        byte b = 0;
        byte[] utf8Bytes = null;
        int byteCount = 0;
        List<Integer> codePoints = new ArrayList<>();

        while ((nextByte = bais.read()) != -1) {
            b = (byte) nextByte;
            byteCount = Main.getByteCount(b);
            utf8Bytes = new byte[byteCount];
            utf8Bytes[0] = (byte) nextByte;
            for (int i = 1; i < byteCount; i++) { // Get any subsequent bytes for this UTF-8 character.
                nextByte = bais.read();
                utf8Bytes[i] = (byte) nextByte;
            }
            int codePoint = new String(utf8Bytes, StandardCharsets.UTF_8).codePointAt(0);
            codePoints.add(codePoint);
        }
        return codePoints.stream();
    }

    /**
     * Returns the number of bytes in a UTF-8 character based on the bit pattern
     * of the supplied byte. The only valid values are 1, 2 3 or 4. If the
     * byte has an invalid bit pattern an IllegalArgumentException is thrown.
     *
     * @param b The first byte of a UTF-8 character.
     * @return The number of bytes for this UTF-* character.
     * @throws IllegalArgumentException if the bit pattern is invalid.
     */
    private static int getByteCount(byte b) throws IllegalArgumentException {
        if ((b >= 0)) return 1;                                             // Pattern is 0xxxxxxx.
        if ((b >= (byte) 0b11000000) && (b <= (byte) 0b11011111)) return 2; // Pattern is 110xxxxx.
        if ((b >= (byte) 0b11100000) && (b <= (byte) 0b11101111)) return 3; // Pattern is 1110xxxx.
        if ((b >= (byte) 0b11110000) && (b <= (byte) 0b11110111)) return 4; // Pattern is 11110xxx.
        throw new IllegalArgumentException(); // Invalid first byte for UTF-8 character.
    }
}

Here's the output from running it. It just lists the code points in the returned Stream<Integer>:

C:\Java\openJDK\jdk-11.0.2\bin\java.exe -javaagent:C:\Users\johndoe\AppData\Local\JetBrains\Toolbox\apps\IDEA-U\ch-0\191.4738.6\lib\idea_rt.jar=60544:C:\Users\johndoe\AppData\Local\JetBrains\Toolbox\apps\IDEA-U\ch-0\191.4738.6\bin -Dfile.encoding=UTF-8 -classpath C:\Users\johndoe\IdeaProjects\Codepoint\out\production\Codepoint Main
162
132913
12433
56
2324
87
12354
1588

Process finished with exit code 0

Notes:

  • It's possible to derive a code point directly from the bytes of the character but it is a convoluted process. Calling String.codePointAt() is a less efficient but cleaner alternative approach.
  • I was unable to generate invalid data. It seems that any invalid bytes somehow get translated to U+FFFD (decimal 65533), the replacement character, so throwing the IllegalArgumentException is possibly not necessary.

Upvotes: 2

Related Questions