From 5a46cd6bd588425bf77b74a6d295a6dfcc7f8baf Mon Sep 17 00:00:00 2001 From: Eric Cochran Date: Thu, 20 Sep 2018 21:20:11 -0700 Subject: [PATCH] Use BufferedSource.indexOf instead of loops. (#677) Cleanup of a rare code path for block comments in lenient readers. --- .../com/squareup/moshi/JsonUtf8Reader.java | 24 +++++++------------ 1 file changed, 8 insertions(+), 16 deletions(-) diff --git a/moshi/src/main/java/com/squareup/moshi/JsonUtf8Reader.java b/moshi/src/main/java/com/squareup/moshi/JsonUtf8Reader.java index 14e12a5..71d8ddc 100644 --- a/moshi/src/main/java/com/squareup/moshi/JsonUtf8Reader.java +++ b/moshi/src/main/java/com/squareup/moshi/JsonUtf8Reader.java @@ -31,6 +31,7 @@ final class JsonUtf8Reader extends JsonReader { private static final ByteString UNQUOTED_STRING_TERMINALS = ByteString.encodeUtf8("{}[]:, \n\t\r\f/\\;#="); private static final ByteString LINEFEED_OR_CARRIAGE_RETURN = ByteString.encodeUtf8("\n\r"); + private static final ByteString CLOSING_BLOCK_COMMENT = ByteString.encodeUtf8("*/"); private static final int PEEKED_NONE = 0; private static final int PEEKED_BEGIN_OBJECT = 1; @@ -990,11 +991,9 @@ final class JsonUtf8Reader extends JsonReader { // skip a /* c-style comment */ buffer.readByte(); // '/' buffer.readByte(); // '*' - if (!skipTo("*/")) { + if (!skipToEndOfBlockComment()) { throw syntaxError("Unterminated comment"); } - buffer.readByte(); // '*' - buffer.readByte(); // '/' p = 0; continue; @@ -1043,20 +1042,13 @@ final class JsonUtf8Reader extends JsonReader { } /** - * @param toFind a string to search for. Must not contain a newline. + * Skips through the next closing block comment. */ - private boolean skipTo(String toFind) throws IOException { - outer: - for (; source.request(toFind.length()); ) { - for (int c = 0; c < toFind.length(); c++) { - if (buffer.getByte(c) != toFind.charAt(c)) { - buffer.readByte(); - continue outer; - } - } - return true; - } - return false; + private boolean skipToEndOfBlockComment() throws IOException { + long index = source.indexOf(CLOSING_BLOCK_COMMENT); + boolean found = index != -1; + buffer.skip(found ? index + CLOSING_BLOCK_COMMENT.size() : buffer.size()); + return found; } @Override public String toString() {