Skip to content

Commit a2e87ca

Browse files
committed
optimize read true/false/null
1 parent 692b7b5 commit a2e87ca

File tree

2 files changed

+24
-16
lines changed

2 files changed

+24
-16
lines changed

src/main/java/com/jsoniter/JsonIterator.java

Lines changed: 13 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -141,26 +141,25 @@ public final String currentBuffer() {
141141

142142
public final boolean readNull() throws IOException {
143143
byte c = IterImpl.nextToken(this);
144-
if (c == 'n') {
145-
IterImpl.skipUntilBreak(this);
146-
return true;
144+
if (c != 'n') {
145+
unreadByte();
146+
return false;
147147
}
148-
unreadByte();
149-
return false;
148+
IterImpl.skipFixedBytes(this, 3); // null
149+
return true;
150150
}
151151

152152
public final boolean readBoolean() throws IOException {
153153
byte c = IterImpl.nextToken(this);
154-
switch (c) {
155-
case 't':
156-
IterImpl.skipFixedBytes(this, 3); // true
157-
return true;
158-
case 'f':
159-
IterImpl.skipFixedBytes(this, 4); // false
160-
return false;
161-
default:
162-
throw reportError("readBoolean", "expect t or f, found: " + c);
154+
if ('t' == c) {
155+
IterImpl.skipFixedBytes(this, 3); // true
156+
return true;
157+
}
158+
if ('f' == c) {
159+
IterImpl.skipFixedBytes(this, 4); // false
160+
return false;
163161
}
162+
throw reportError("readBoolean", "expect t or f, found: " + c);
164163
}
165164

166165
public final short readShort() throws IOException {

src/test/java/com/jsoniter/TestBoolean.java

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,13 +7,22 @@
77

88
public class TestBoolean extends TestCase {
99
@org.junit.experimental.categories.Category(StreamingCategory.class)
10-
public void test() throws IOException {
11-
JsonIterator iter = JsonIterator.parse(new ByteArrayInputStream("[true,false,true]".getBytes()), 4);
10+
public void test_streaming() throws IOException {
11+
JsonIterator iter = JsonIterator.parse(new ByteArrayInputStream("[true,false,null,true]".getBytes()), 3);
1212
iter.readArray();
1313
assertTrue(iter.readBoolean());
1414
iter.readArray();
1515
assertFalse(iter.readBoolean());
1616
iter.readArray();
17+
assertTrue(iter.readNull());
18+
iter.readArray();
1719
assertTrue(iter.readBoolean());
1820
}
21+
22+
public void test_non_streaming() throws IOException {
23+
assertTrue(JsonIterator.parse("true").readBoolean());
24+
assertFalse(JsonIterator.parse("false").readBoolean());
25+
assertTrue(JsonIterator.parse("null").readNull());
26+
assertFalse(JsonIterator.parse("false").readNull());
27+
}
1928
}

0 commit comments

Comments
 (0)