Skip to content

Commit

Permalink
Merge pull request #280 from LossyDragon/kvtr-stringbuilder
Browse files Browse the repository at this point in the history
Reuse StringBuilder in KVTextReader
  • Loading branch information
LossyDragon authored Sep 30, 2024
2 parents 0ab4f96 + b422a4c commit ad5ea0b
Show file tree
Hide file tree
Showing 2 changed files with 208 additions and 152 deletions.
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

0 comments on commit ad5ea0b

Please sign in to comment.