CavalliumDBEngine/src/test/java/it/cavallium/dbengine/PriorityQueueAdaptor.java

82 lines
1.7 KiB
Java
Raw Normal View History

2021-10-14 15:55:58 +02:00
package it.cavallium.dbengine;
2022-06-30 15:06:10 +02:00
import it.cavallium.dbengine.database.DiscardingCloseable;
2021-10-14 15:55:58 +02:00
import it.cavallium.dbengine.lucene.PriorityQueue;
2022-06-30 13:54:55 +02:00
import it.cavallium.dbengine.utils.SimpleResource;
2021-10-14 15:55:58 +02:00
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
2022-06-15 18:36:22 +02:00
import java.util.Objects;
2021-10-14 15:55:58 +02:00
import org.apache.lucene.search.HitQueue;
import reactor.core.publisher.Flux;
2022-06-30 15:06:10 +02:00
public class PriorityQueueAdaptor<T> extends SimpleResource implements PriorityQueue<T>, DiscardingCloseable {
2021-10-14 15:55:58 +02:00
private final org.apache.lucene.util.PriorityQueue<T> hitQueue;
public PriorityQueueAdaptor(org.apache.lucene.util.PriorityQueue<T> hitQueue) {
this.hitQueue = hitQueue;
}
@Override
public void add(T element) {
hitQueue.add(element);
hitQueue.updateTop();
}
@Override
public T top() {
hitQueue.updateTop();
return hitQueue.top();
}
@Override
public T pop() {
var popped = hitQueue.pop();
hitQueue.updateTop();
return popped;
}
@Override
2022-06-15 18:36:22 +02:00
public void replaceTop(T oldTop, T newTop) {
assert Objects.equals(oldTop, hitQueue.top());
2021-10-14 15:55:58 +02:00
hitQueue.updateTop(newTop);
}
@Override
public long size() {
return hitQueue.size();
}
@Override
public void clear() {
hitQueue.clear();
}
@Override
public boolean remove(T element) {
var removed = hitQueue.remove(element);
hitQueue.updateTop();
return removed;
}
@Override
public Flux<T> iterate() {
List<T> items = new ArrayList<>(hitQueue.size());
T item;
while ((item = hitQueue.pop()) != null) {
items.add(item);
}
for (T t : items) {
hitQueue.insertWithOverflow(t);
}
return Flux.fromIterable(items);
}
@Override
2022-06-30 13:54:55 +02:00
protected void onClose() {
2021-10-14 15:55:58 +02:00
hitQueue.clear();
hitQueue.updateTop();
}
}