Don't re-wrap nullsafe/nonnull adapters if they are already one (#909)

* Don't re-wrap nullsafe/nonnull adapters if they are already one

nullSafe() is often called defensively, which can lead to a lot of layers of wrapping and checking. This avoids that overhead where possible.

* Add tests
This commit is contained in:
Zac Sweers
2019-09-12 14:14:49 -04:00
committed by GitHub
parent 98092d0727
commit 71cf745852
2 changed files with 16 additions and 0 deletions

View File

@@ -130,6 +130,9 @@ public abstract class JsonAdapter<T> {
* nulls.
*/
@CheckReturnValue public final JsonAdapter<T> nullSafe() {
if (this instanceof NullSafeJsonAdapter) {
return this;
}
return new NullSafeJsonAdapter<>(this);
}
@@ -141,6 +144,9 @@ public abstract class JsonAdapter<T> {
* handled elsewhere. This should only be used to fail on explicit nulls.
*/
@CheckReturnValue public final JsonAdapter<T> nonNull() {
if (this instanceof NonNullJsonAdapter) {
return this;
}
return new NonNullJsonAdapter<>(this);
}

View File

@@ -285,4 +285,14 @@ public final class JsonAdapterTest {
}.lenient().serializeNulls();
assertThat(adapter.fromJson("true true")).isEqualTo(true);
}
@Test public void nullSafeDoesntDuplicate() {
JsonAdapter<Boolean> adapter = new Moshi.Builder().build().adapter(Boolean.class).nullSafe();
assertThat(adapter.nullSafe()).isSameAs(adapter);
}
@Test public void nonNullDoesntDuplicate() {
JsonAdapter<Boolean> adapter = new Moshi.Builder().build().adapter(Boolean.class).nonNull();
assertThat(adapter.nonNull()).isSameAs(adapter);
}
}