mirror of
https://github.com/fankes/moshi.git
synced 2025-10-20 08:29:22 +08:00
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:
@@ -130,6 +130,9 @@ public abstract class JsonAdapter<T> {
|
|||||||
* nulls.
|
* nulls.
|
||||||
*/
|
*/
|
||||||
@CheckReturnValue public final JsonAdapter<T> nullSafe() {
|
@CheckReturnValue public final JsonAdapter<T> nullSafe() {
|
||||||
|
if (this instanceof NullSafeJsonAdapter) {
|
||||||
|
return this;
|
||||||
|
}
|
||||||
return new NullSafeJsonAdapter<>(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.
|
* handled elsewhere. This should only be used to fail on explicit nulls.
|
||||||
*/
|
*/
|
||||||
@CheckReturnValue public final JsonAdapter<T> nonNull() {
|
@CheckReturnValue public final JsonAdapter<T> nonNull() {
|
||||||
|
if (this instanceof NonNullJsonAdapter) {
|
||||||
|
return this;
|
||||||
|
}
|
||||||
return new NonNullJsonAdapter<>(this);
|
return new NonNullJsonAdapter<>(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -285,4 +285,14 @@ public final class JsonAdapterTest {
|
|||||||
}.lenient().serializeNulls();
|
}.lenient().serializeNulls();
|
||||||
assertThat(adapter.fromJson("true true")).isEqualTo(true);
|
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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user