Created
February 16, 2015 16:01
-
-
Save jpountz/6c3e7ff25c57a2ca7d52 to your computer and use it in GitHub Desktop.
IntArrayDocIdSet.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.IOException; | |
import java.util.Arrays; | |
import org.apache.lucene.search.DocIdSet; | |
import org.apache.lucene.search.DocIdSetIterator; | |
import org.apache.lucene.util.ArrayUtil; | |
import org.apache.lucene.util.RamUsageEstimator; | |
public class IntArrayDocIdSet extends DocIdSet { | |
private static final long BASE_RAM_BYTES_USED = RamUsageEstimator.shallowSizeOfInstance(IntArrayDocIdSet.class); | |
public static class Builder { | |
private int[] docIDs = new int[0]; | |
int off; | |
public void add(int docID) { | |
if (off > 0 && docID <= docIDs[off - 1]) { | |
throw new IllegalArgumentException(); | |
} | |
if (off == docIDs.length) { | |
docIDs = ArrayUtil.grow(docIDs); | |
} | |
docIDs[off++] = docID; | |
} | |
public IntArrayDocIdSet build() { | |
add(DocIdSetIterator.NO_MORE_DOCS); | |
final IntArrayDocIdSet set = new IntArrayDocIdSet(Arrays.copyOf(docIDs, off)); | |
docIDs = null; | |
return set; | |
} | |
} | |
private final int[] docIDs; | |
public IntArrayDocIdSet(int[] docIDs) { | |
this.docIDs = docIDs; | |
} | |
@Override | |
public long ramBytesUsed() { | |
return BASE_RAM_BYTES_USED + RamUsageEstimator.sizeOf(docIDs); | |
} | |
@Override | |
public DocIdSetIterator iterator() throws IOException { | |
return new Iterator(docIDs); | |
} | |
private static class Iterator extends DocIdSetIterator { | |
private final int[] docIDs; | |
int i; | |
public Iterator(int[] docIDs) { | |
this.docIDs = docIDs; | |
i = -1; | |
} | |
@Override | |
public int docID() { | |
if (i == -1) { | |
return -1; | |
} | |
return docIDs[i]; | |
} | |
@Override | |
public int nextDoc() throws IOException { | |
return docIDs[++i]; | |
} | |
@Override | |
public int advance(int target) throws IOException { | |
int lo = i + 1; | |
int hi = lo + 1; | |
while (hi < docIDs.length && docIDs[hi] < target) { | |
final int diff = hi - lo; | |
lo = hi; | |
hi += 2 * diff; | |
} | |
hi = Math.min(hi, docIDs.length); | |
i = Arrays.binarySearch(docIDs, lo, hi, target); | |
if (i < 0) { | |
i = -1 - i; | |
} | |
return docIDs[i]; | |
} | |
@Override | |
public long cost() { | |
return docIDs.length - 1; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment