Skip to content

Commit

Permalink
Simplified hanlding of surrogate pairs in the loop
Browse files Browse the repository at this point in the history
  • Loading branch information
DavyLandman committed Sep 19, 2024
1 parent a7cf69a commit 206676f
Showing 1 changed file with 14 additions and 15 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -1442,7 +1442,7 @@ public void write(Writer w) throws IOException {
public Reader asReader() {
return new Reader() {
private final OfInt chars = iterator();
private char endedWithHalfSurrogate = 0;
private char queuedLowSurrogate = 0;

@Override
public int read(char[] cbuf, int off, int len) throws IOException {
Expand All @@ -1454,12 +1454,15 @@ public int read(char[] cbuf, int off, int len) throws IOException {
}

int pos = off;
if (endedWithHalfSurrogate != 0) {
cbuf[pos++] = endedWithHalfSurrogate;
endedWithHalfSurrogate = 0;
}
int endPos = off + len;
char lowSurrogate = queuedLowSurrogate;
queuedLowSurrogate = 0;
while (pos < endPos) {
if (lowSurrogate != 0) {
cbuf[pos++] = lowSurrogate;
lowSurrogate = 0;
continue;
}
if (!chars.hasNext()) {
break;
}
Expand All @@ -1468,31 +1471,27 @@ public int read(char[] cbuf, int off, int len) throws IOException {
cbuf[pos++] = (char)nextChar;
} else {
cbuf[pos++] = Character.highSurrogate(nextChar);
char lowSide = Character.lowSurrogate(nextChar);
if (pos < endPos) {
cbuf[pos++] = lowSide;
} else {
endedWithHalfSurrogate = lowSide;
}
lowSurrogate = Character.lowSurrogate(nextChar);
}
}
queuedLowSurrogate = lowSurrogate;
int written = pos - off;
return written == 0 ? /* EOF */ -1 : written;
}

@Override
public int read() throws IOException {
if (endedWithHalfSurrogate != 0) {
int result = endedWithHalfSurrogate;
endedWithHalfSurrogate = 0;
if (queuedLowSurrogate != 0) {
int result = queuedLowSurrogate;
queuedLowSurrogate = 0;
return result;
}
if (chars.hasNext()) {
int nextChar = chars.nextInt();
if (Character.isBmpCodePoint(nextChar)) {
return nextChar;
} else {
endedWithHalfSurrogate = Character.lowSurrogate(nextChar);
queuedLowSurrogate = Character.lowSurrogate(nextChar);
return Character.highSurrogate(nextChar);
}
}
Expand Down

0 comments on commit 206676f

Please sign in to comment.