Skip to content

Commit 9d7175f

Browse files
committed
improved reader close in tokenizer
1 parent 0b4a726 commit 9d7175f

File tree

2 files changed

+23
-4
lines changed

2 files changed

+23
-4
lines changed

src/main/java/com/igormaznitsa/prologparser/PrologParser.java

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,8 @@ public abstract class PrologParser implements Iterable<PrologTerm>, Closeable {
7575
private static final Koi7CharOpMap OPERATORS_SUBBLOCK;
7676
private static final Koi7CharOpMap OPERATORS_SUBBLOCK_CURLY;
7777

78+
private volatile boolean autoCloseReaderFlag;
79+
7880
static {
7981
META_OP_MAP = ofOps();
8082

@@ -106,6 +108,11 @@ public PrologParser(final Reader source, final ParserContext context) {
106108
this.parserFlags = context == null ? FLAG_NONE : context.getFlags();
107109
}
108110

111+
public PrologParser autoCloseReader(){
112+
this.autoCloseReaderFlag = true;
113+
return this;
114+
}
115+
109116
public static Op findBaseMetaOperator(final String text, final OpAssoc type) {
110117
if (text.length() != 1) {
111118
return null;
@@ -612,6 +619,6 @@ public Stream<PrologTerm> stream() {
612619

613620
@Override
614621
public void close() throws IOException {
615-
this.tokenizer.close();
622+
this.tokenizer.close(this.autoCloseReaderFlag);
616623
}
617624
}

src/main/java/com/igormaznitsa/prologparser/tokenizer/Tokenizer.java

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@
3737
import com.igormaznitsa.prologparser.utils.StringUtils;
3838

3939
import java.io.IOException;
40+
import java.io.PushbackReader;
4041
import java.io.Reader;
4142
import java.math.BigInteger;
4243

@@ -166,10 +167,21 @@ public void push(final char ch) {
166167
}
167168
}
168169

169-
public void close() throws IOException {
170+
public void close(final boolean closeReader) throws IOException {
170171
this.lastPushedTerm = null;
171-
this.strBuf.clear();
172-
this.reader.close();
172+
try {
173+
if (this.reader instanceof PushbackReader) {
174+
final PushbackReader pbReader = (PushbackReader) this.reader;
175+
while (!this.strBuf.isEmpty()) {
176+
pbReader.unread(this.strBuf.pop());
177+
}
178+
}
179+
} finally {
180+
this.strBuf.clear();
181+
if (closeReader) {
182+
this.reader.close();
183+
}
184+
}
173185
}
174186

175187
public boolean hasOperatorStartsWith(final String operatorNameStartSubstring) {

0 commit comments

Comments
 (0)