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

reduce cost of NotFoundAny construction #345

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
3 changes: 2 additions & 1 deletion src/main/java/com/jsoniter/any/Any.java
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,8 @@ public int size() {

public Any mustBeValid() {
if(this instanceof NotFoundAny) {
throw ((NotFoundAny) this).exception;
((NotFoundAny) this).throwException();
return null;
} else {
return this;
}
Expand Down
41 changes: 32 additions & 9 deletions src/main/java/com/jsoniter/any/NotFoundAny.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,21 +11,28 @@

class NotFoundAny extends Any {

protected final JsonException exception;
private Object[] keys;
private int idx;
private Object obj, key;
private final int exceptionMode;

public NotFoundAny(Object[] keys, int idx, Object obj) {
this.exception = new JsonException(String.format("Value not found: failed to get path %s, because #%s section of the path ( %s ) not found in %s",
Arrays.toString(keys), idx, keys[idx], obj));
this.keys = keys;
this.idx = idx;
this.obj = obj;
exceptionMode = 0;
}

public NotFoundAny(int index, Object obj) {
this.exception = new JsonException(String.format("Value not found: failed to get index %s from %s",
index, obj));
this.idx = index;
this.obj = obj;
exceptionMode = 1;
}

public NotFoundAny(Object key, Object obj) {
this.exception = new JsonException(String.format("Value not found: failed to get key %s from %s",
key, obj));
this.key = key;
this.obj = obj;
exceptionMode = 2;
}

@Override
Expand All @@ -35,12 +42,28 @@ public ValueType valueType() {

@Override
public Object object() {
throw exception;
throwException();
return null;
}

void throwException() {
switch (exceptionMode) {
case 0:
throw new JsonException(String.format("Value not found: failed to get path %s, because #%s section of the path ( %s ) not found in %s",
Arrays.toString(keys), idx, keys[idx], obj));
case 1:
throw new JsonException(String.format("Value not found: failed to get index %s from %s",
idx, obj));
case 2:
throw new JsonException(String.format("Value not found: failed to get key %s from %s",
key, obj));
}
throw new JsonException();
}

@Override
public void writeTo(JsonStream stream) throws IOException {
throw exception;
throwException();
}

@Override
Expand Down