Skip to content

Commit e23980f

Browse files
authored
Add CloudCache#keyExtractingView (#20)
1 parent 614b0a2 commit e23980f

1 file changed

Lines changed: 40 additions & 0 deletions

File tree

  • cloud-processors-common/src/main/java/org/incendo/cloud/processors/cache

cloud-processors-common/src/main/java/org/incendo/cloud/processors/cache/CloudCache.java

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,10 +24,13 @@
2424
package org.incendo.cloud.processors.cache;
2525

2626
import java.util.Optional;
27+
import java.util.function.Function;
2728
import org.apiguardian.api.API;
2829
import org.checkerframework.checker.nullness.qual.NonNull;
2930
import org.checkerframework.checker.nullness.qual.Nullable;
3031

32+
import static java.util.Objects.requireNonNull;
33+
3134
/**
3235
* Something that caches values.
3336
*
@@ -89,4 +92,41 @@ public interface CloudCache<K, V> {
8992
default @NonNull Optional<V> get(final @NonNull K key) {
9093
return Optional.ofNullable(this.getIfPresent(key));
9194
}
95+
96+
/**
97+
* Returns a view of this cache with an adapted key type.
98+
*
99+
* @param keyExtractor key extractor
100+
* @param <K1> key type for the view
101+
* @return new view
102+
*/
103+
default <K1> @NonNull CloudCache<K1, V> keyExtractingView(final @NonNull Function<K1, K> keyExtractor) {
104+
requireNonNull(keyExtractor, "keyExtractor");
105+
return new CloudCache<>() {
106+
@Override
107+
public void delete(final @NonNull K1 key) {
108+
CloudCache.this.delete(keyExtractor.apply(key));
109+
}
110+
111+
@Override
112+
public void put(final @NonNull K1 key, final @NonNull V value) {
113+
CloudCache.this.put(keyExtractor.apply(key), value);
114+
}
115+
116+
@Override
117+
public @Nullable V getIfPresent(final @NonNull K1 key) {
118+
return CloudCache.this.getIfPresent(keyExtractor.apply(key));
119+
}
120+
121+
@Override
122+
public @Nullable V popIfPresent(final @NonNull K1 key) {
123+
return CloudCache.this.popIfPresent(keyExtractor.apply(key));
124+
}
125+
126+
@Override
127+
public @NonNull Optional<V> get(final @NonNull K1 key) {
128+
return CloudCache.this.get(keyExtractor.apply(key));
129+
}
130+
};
131+
}
92132
}

0 commit comments

Comments
 (0)