com.github.elibracha.compare.ReferenceDiffCache Maven / Gradle / Ivy
package com.github.elibracha.compare;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import com.github.elibracha.model.DiffContext;
/** Created by adarsh.sharma on 07/01/18. */
public abstract class ReferenceDiffCache {
private Map refDiffMap;
public ReferenceDiffCache() {
this.refDiffMap = new HashMap<>();
}
private Optional getFromCache(CacheKey cacheKey) {
return Optional.ofNullable(refDiffMap.get(cacheKey));
}
private void addToCache(CacheKey cacheKey, D changed) {
refDiffMap.put(cacheKey, changed);
}
public Optional cachedDiff(
HashSet refSet,
C left,
C right,
String leftRef,
String rightRef,
DiffContext context) {
boolean areBothRefParameters = leftRef != null && rightRef != null;
if (areBothRefParameters) {
CacheKey key = new CacheKey(leftRef, rightRef, context);
Optional changedFromRef = getFromCache(key);
if (changedFromRef.isPresent()) {
return changedFromRef;
} else {
String refKey = getRefKey(leftRef, rightRef);
if (refSet.contains(refKey)) {
return Optional.empty();
} else {
refSet.add(refKey);
Optional changed = computeDiff(refSet, left, right, context);
addToCache(key, changed.orElse(null));
refSet.remove(refKey);
return changed;
}
}
} else {
return computeDiff(refSet, left, right, context);
}
}
protected String getRefKey(String leftRef, String rightRef) {
return leftRef + ":" + rightRef;
}
protected abstract Optional computeDiff(
HashSet refSet, C left, C right, DiffContext context);
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy