Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reuse StringBuilder in KVTextReader #280

Merged
merged 2 commits into from
Sep 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 9 additions & 11 deletions src/main/java/in/dragonbra/javasteam/types/KVTextReader.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,9 @@
import in.dragonbra.javasteam.util.Passable;
import in.dragonbra.javasteam.util.Strings;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PushbackInputStream;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.Map;
import java.util.TreeMap;
Expand All @@ -20,6 +18,8 @@ public class KVTextReader extends PushbackInputStream {

public static final Map<Character, Character> ESCAPED_MAPPING;

private final StringBuilder sb = new StringBuilder(128);

static {
Map<Character, Character> escapedMapping = new TreeMap<>();

Expand Down Expand Up @@ -141,8 +141,7 @@ public String readToken(Passable<Boolean> wasQuoted, Passable<Boolean> wasCondit
// "
read();

ByteArrayOutputStream baos = new ByteArrayOutputStream();

sb.setLength(0);
while (!endOfStream()) {
if (peek() == '\\') {
read();
Expand All @@ -154,7 +153,7 @@ public String readToken(Passable<Boolean> wasQuoted, Passable<Boolean> wasCondit
replacedChar = escapedChar;
}

baos.write(replacedChar);
sb.append((char) replacedChar);

continue;
}
Expand All @@ -163,14 +162,13 @@ public String readToken(Passable<Boolean> wasQuoted, Passable<Boolean> wasCondit
break;
}

baos.write(read());
sb.append((char) read());
}

// "
read();

// convert the output stream as an utf-8 supported string.
return baos.toString(StandardCharsets.UTF_8);
return sb.toString();
}

if (next == '{' || next == '}') {
Expand All @@ -180,7 +178,7 @@ public String readToken(Passable<Boolean> wasQuoted, Passable<Boolean> wasCondit

boolean bConditionalStart = false;
int count = 0;
StringBuilder ret = new StringBuilder();
sb.setLength(0);

while (!endOfStream()) {
next = (char) peek();
Expand All @@ -202,14 +200,14 @@ public String readToken(Passable<Boolean> wasQuoted, Passable<Boolean> wasCondit
}

if (count < 1023) {
ret.append(next);
sb.append(next);
} else {
throw new IOException("ReadToken overflow");
}

read();
}
return ret.toString();
return sb.toString();
}

private boolean endOfStream() {
Expand Down
Loading
Loading