Skip to content

Commit

Permalink
Oh boy
Browse files Browse the repository at this point in the history
  • Loading branch information
Stephan202 committed Nov 6, 2022
1 parent 89a45f9 commit dee6e94
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -355,6 +355,42 @@ Optional<T> after(Optional<T> optional) {
}
}

/**
* Avoid unnecessary {@link Optional} to {@link Stream} conversion when filtering a value of the
* former type.
*/
static final class OptionalFilter<T> {
@BeforeTemplate
Optional<T> before(Optional<T> optional, Predicate<? super T> predicate) {
return Refaster.anyOf(
optional.stream().filter(predicate).findFirst(),
optional.stream().filter(predicate).findAny());
}

@AfterTemplate
Optional<T> after(Optional<T> optional, Predicate<? super T> predicate) {
return optional.filter(predicate);
}
}

/**
* Avoid unnecessary {@link Optional} to {@link Stream} conversion when mapping a value of the
* former type.
*/
// XXX: If `StreamMapFirst` also simplifies `.findAny()` expressions, then this rule can be
// dropped in favour of `StreamMapFirst` and `OptionalIdentity`.
static final class OptionalMap<S, T> {
@BeforeTemplate
Optional<? extends T> before(Optional<S> optional, Function<? super S, ? extends T> function) {
return optional.stream().map(function).findAny();
}

@AfterTemplate
Optional<? extends T> after(Optional<S> optional, Function<? super S, ? extends T> function) {
return optional.map(function);
}
}

// XXX: Add a rule for:
// `optional.flatMap(x -> pred(x) ? Optional.empty() : Optional.of(x))` and variants.
// (Maybe canonicalize the inner expression. Maybe we rewrite already.)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -109,4 +109,14 @@ ImmutableSet<Optional<String>> testOptionalIdentity() {
Optional.of("baz").stream().min(String::compareTo),
Optional.of("qux").stream().max(String::compareTo));
}

ImmutableSet<Optional<String>> testOptionalFilter() {
return ImmutableSet.of(
Optional.of("foo").stream().filter(String::isEmpty).findFirst(),
Optional.of("bar").stream().filter(String::isEmpty).findAny());
}

Optional<String> testOptionalMap() {
return Optional.of(1).stream().map(String::valueOf).findAny();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -103,4 +103,13 @@ ImmutableSet<Optional<String>> testOptionalIdentity() {
return ImmutableSet.of(
Optional.of("foo"), Optional.of("bar"), Optional.of("baz"), Optional.of("qux"));
}

ImmutableSet<Optional<String>> testOptionalFilter() {
return ImmutableSet.of(
Optional.of("foo").filter(String::isEmpty), Optional.of("bar").filter(String::isEmpty));
}

Optional<String> testOptionalMap() {
return Optional.of(1).map(String::valueOf);
}
}

0 comments on commit dee6e94

Please sign in to comment.