blob: 0fbdd0b28c7ccce91fb025f4674398a2b6d319c8 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
|
package com.yahoo.document.json;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import java.io.IOException;
import java.util.function.Supplier;
/**
* A {@link TokenBuffer} which only buffers tokens when needed, i.e., when peeking.
*
* @author jonmv
*/
public class LazyTokenBuffer extends TokenBuffer {
private final JsonParser parser;
public LazyTokenBuffer(JsonParser parser) {
this.parser = parser;
try { addFromParser(parser); }
catch (IOException e) { throw new IllegalArgumentException("failed parsing document JSON", e); }
if (JsonToken.START_OBJECT != current())
throw new IllegalArgumentException("expected start of JSON object, but got " + current());
updateNesting(current());
}
void advance() {
super.advance();
if (tokens.isEmpty() && nesting() > 0) tokens.add(nextToken()); // Fill current token if needed and possible.
}
@Override
public Supplier<Token> lookahead() {
return new Supplier<>() {
int localNesting = nesting();
Supplier<Token> buffered = LazyTokenBuffer.super.lookahead();
@Override public Token get() {
if (localNesting == 0)
return null;
Token token = buffered.get();
if (token == null) {
token = nextToken();
tokens.add(token);
}
localNesting += nestingOffset(token.token);
return token;
}
};
}
private Token nextToken() {
try {
JsonToken token = parser.nextValue();
if (token == null)
throw new IllegalStateException("no more JSON tokens");
return new Token(token, parser.getCurrentName(), parser.getText());
}
catch (IOException e) {
throw new IllegalArgumentException("failed reading document JSON", e);
}
}
}
|