package org.apache.lucene.facet.taxonomy;
import java.io.IOException;
import org.apache.lucene.facet.FacetsConfig;
import org.apache.lucene.index.BinaryDocValues;
import org.apache.lucene.index.DocValues;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.IntsRef;
public class DocValuesOrdinalsReader extends OrdinalsReader {
private final String field;
public DocValuesOrdinalsReader() {
this(FacetsConfig.DEFAULT_INDEX_FIELD_NAME);
}
public DocValuesOrdinalsReader(String field) {
this.field = field;
}
@Override
public OrdinalsSegmentReader getReader(LeafReaderContext context) throws IOException {
BinaryDocValues values0 = context.reader().getBinaryDocValues(field);
if (values0 == null) {
values0 = DocValues.emptyBinary();
}
final BinaryDocValues values = values0;
return new OrdinalsSegmentReader() {
private int lastDocID;
@Override
public void get(int docID, IntsRef ordinals) throws IOException {
if (docID < lastDocID) {
throw new AssertionError("docs out of order: lastDocID=" + lastDocID + " vs docID=" + docID);
}
lastDocID = docID;
if (docID > values.docID()) {
values.advance(docID);
}
final BytesRef bytes;
if (values.docID() == docID) {
bytes = values.binaryValue();
} else {
bytes = new BytesRef(BytesRef.EMPTY_BYTES);
}
decode(bytes, ordinals);
}
};
}
@Override
public String getIndexFieldName() {
return field;
}
protected void decode(BytesRef buf, IntsRef ordinals) {
if (ordinals.ints.length < buf.length) {
ordinals.ints = ArrayUtil.grow(ordinals.ints, buf.length);
}
ordinals.offset = 0;
ordinals.length = 0;
int upto = buf.offset + buf.length;
int value = 0;
int offset = buf.offset;
int prev = 0;
while (offset < upto) {
byte b = buf.bytes[offset++];
if (b >= 0) {
ordinals.ints[ordinals.length] = ((value << 7) | b) + prev;
value = 0;
prev = ordinals.ints[ordinals.length];
ordinals.length++;
} else {
value = (value << 7) | (b & 0x7F);
}
}
}
}