|
| 1 | +package me.jellysquid.mods.hydrogen.common.dedup; |
| 2 | + |
| 3 | +import it.unimi.dsi.fastutil.Hash; |
| 4 | +import it.unimi.dsi.fastutil.objects.ObjectOpenCustomHashSet; |
| 5 | + |
| 6 | +import java.util.Objects; |
| 7 | + |
| 8 | +public class DeduplicationCache<T> { |
| 9 | + private final ObjectOpenCustomHashSet<T> pool; |
| 10 | + |
| 11 | + private int attemptedInsertions = 0; |
| 12 | + private int deduplicated = 0; |
| 13 | + |
| 14 | + public DeduplicationCache(Hash.Strategy<T> strategy) { |
| 15 | + this.pool = new ObjectOpenCustomHashSet<>(strategy); |
| 16 | + } |
| 17 | + |
| 18 | + public DeduplicationCache() { |
| 19 | + this.pool = new ObjectOpenCustomHashSet<>(new Hash.Strategy<T>() { |
| 20 | + @Override |
| 21 | + public int hashCode(T o) { |
| 22 | + return Objects.hashCode(o); |
| 23 | + } |
| 24 | + |
| 25 | + @Override |
| 26 | + public boolean equals(T a, T b) { |
| 27 | + return Objects.equals(a, b); |
| 28 | + } |
| 29 | + }); |
| 30 | + } |
| 31 | + |
| 32 | + public synchronized T deduplicate(T item) { |
| 33 | + this.attemptedInsertions++; |
| 34 | + |
| 35 | + T result = this.pool.addOrGet(item); |
| 36 | + |
| 37 | + if (result != item) { |
| 38 | + this.deduplicated++; |
| 39 | + } |
| 40 | + |
| 41 | + return result; |
| 42 | + } |
| 43 | + |
| 44 | + public synchronized void clearCache() { |
| 45 | + this.attemptedInsertions = 0; |
| 46 | + this.deduplicated = 0; |
| 47 | + |
| 48 | + this.pool.clear(); |
| 49 | + } |
| 50 | + |
| 51 | + @Override |
| 52 | + public synchronized String toString() { |
| 53 | + return String.format("DeduplicationCache ( %d/%d de-duplicated, %d pooled )", |
| 54 | + this.deduplicated, this.attemptedInsertions, this.pool.size()); |
| 55 | + } |
| 56 | +} |
0 commit comments