Skip to content

Commit

Permalink
Introduce Mono{JustOr}Empty Refaster rules
Browse files Browse the repository at this point in the history
  • Loading branch information
werli committed Dec 4, 2022
1 parent 5afa7e1 commit c46aaeb
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import org.jspecify.nullness.Nullable;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
Expand Down Expand Up @@ -59,6 +60,33 @@ Mono<T> after(Supplier<? extends T> supplier) {
}
}

/** Prefer {@link Mono#empty()} over more contrived alternatives. */
static final class MonoEmpty<T> {
@BeforeTemplate
Mono<T> before() {
return Mono.justOrEmpty(null);
}

@AfterTemplate
Mono<T> after() {
return Mono.empty();
}
}

/** Prefer {@link Mono#justOrEmpty(Optional)} over more contrived alternatives. */
static final class MonoJustOrEmpty<T> {
@BeforeTemplate
@SuppressWarnings("NullAway")
Mono<T> before(@Nullable T value) {
return Mono.justOrEmpty(Refaster.anyOf(Optional.of(value), Optional.ofNullable(value)));
}

@AfterTemplate
Mono<T> after(@Nullable T value) {
return Mono.justOrEmpty(value);
}
}

/** Prefer {@link Mono#justOrEmpty(Optional)} over more verbose alternatives. */
// XXX: If `optional` is a constant and effectively-final expression then the `Mono.defer` can be
// dropped. Should look into Refaster support for identifying this.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,15 @@ ImmutableSet<Mono<?>> testMonoFromSupplier() {
Mono.fromCallable(this::toString));
}

Mono<String> testMonoEmpty() {
return Mono.justOrEmpty(null);
}

ImmutableSet<Mono<Integer>> testMonoJustOrEmpty() {
return ImmutableSet.of(
Mono.justOrEmpty(Optional.of(1)), Mono.justOrEmpty(Optional.ofNullable(2)));
}

ImmutableSet<Mono<Integer>> testMonoFromOptional() {
return ImmutableSet.of(
Mono.fromCallable(() -> Optional.of(1).orElse(null)),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,14 @@ ImmutableSet<Mono<?>> testMonoFromSupplier() {
Mono.fromSupplier(this::toString));
}

Mono<String> testMonoEmpty() {
return Mono.empty();
}

ImmutableSet<Mono<Integer>> testMonoJustOrEmpty() {
return ImmutableSet.of(Mono.justOrEmpty(1), Mono.justOrEmpty(2));
}

ImmutableSet<Mono<Integer>> testMonoFromOptional() {
return ImmutableSet.of(
Mono.defer(() -> Mono.justOrEmpty(Optional.of(1))),
Expand Down

0 comments on commit c46aaeb

Please sign in to comment.