Apache Lucene open-source search software
LUCENE-3069: API refactoring on Pulsing PF
Han Jiang980ea4db598d
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempFSTOrdPulsing41PostingsFormat.java b/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempFSTOrdPulsing41PostingsFormat.javanew file mode 100644index 00000000000..c3f7d4ec795--- /dev/null+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempFSTOrdPulsing41PostingsFormat.java@@ -0,0 +1,78 @@+package org.apache.lucene.codecs.temp;++/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.io.IOException;++import org.apache.lucene.codecs.FieldsConsumer;+import org.apache.lucene.codecs.FieldsProducer;+import org.apache.lucene.codecs.PostingsFormat;+import org.apache.lucene.codecs.TempPostingsReaderBase;+import org.apache.lucene.codecs.TempPostingsWriterBase;+import org.apache.lucene.index.SegmentReadState;+import org.apache.lucene.index.SegmentWriteState;+import org.apache.lucene.util.IOUtils;++/** TempFSTOrd + Pulsing41+ * @lucene.experimental */++public class TempFSTOrdPulsing41PostingsFormat extends PostingsFormat {+ private final TempPostingsBaseFormat wrappedPostingsBaseFormat;++ public TempFSTOrdPulsing41PostingsFormat() {+ super("TempFSTOrdPulsing41");+ this.wrappedPostingsBaseFormat = new TempPostingsBaseFormat();+ }++ @Override+ public FieldsConsumer fieldsConsumer(SegmentWriteState state) throws IOException {+ TempPostingsWriterBase docsWriter = null;+ TempPostingsWriterBase pulsingWriter = null;++ boolean success = false;+ try {+ docsWriter = wrappedPostingsBaseFormat.postingsWriterBase(state);+ pulsingWriter = new TempPulsingPostingsWriter(state, 1, docsWriter);+ FieldsConsumer ret = new TempFSTOrdTermsWriter(state, pulsingWriter);+ success = true;+ return ret;+ } finally {+ if (!success) {+ IOUtils.closeWhileHandlingException(docsWriter, pulsingWriter);+ }+ }+ }++ @Override+ public FieldsProducer fieldsProducer(SegmentReadState state) throws IOException {+ TempPostingsReaderBase docsReader = null;+ TempPostingsReaderBase pulsingReader = null;+ boolean success = false;+ try {+ docsReader = wrappedPostingsBaseFormat.postingsReaderBase(state);+ pulsingReader = new TempPulsingPostingsReader(state, docsReader);+ FieldsProducer ret = new TempFSTOrdTermsReader(state, pulsingReader);+ success = true;+ return ret;+ } finally {+ if (!success) {+ IOUtils.closeWhileHandlingException(docsReader, pulsingReader);+ }+ }+ }+}diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempFSTPulsing41PostingsFormat.java b/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempFSTPulsing41PostingsFormat.javanew file mode 100644index 00000000000..e5131646a21--- /dev/null+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempFSTPulsing41PostingsFormat.java@@ -0,0 +1,79 @@+package org.apache.lucene.codecs.temp;++/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.io.IOException;++import org.apache.lucene.codecs.FieldsConsumer;+import org.apache.lucene.codecs.FieldsProducer;+import org.apache.lucene.codecs.PostingsFormat;+import org.apache.lucene.codecs.TempPostingsReaderBase;+import org.apache.lucene.codecs.TempPostingsWriterBase;+import org.apache.lucene.index.SegmentReadState;+import org.apache.lucene.index.SegmentWriteState;+import org.apache.lucene.util.IOUtils;++/** TempFST + Pulsing41, test only, since+ * FST does no delta encoding here!+ * @lucene.experimental */++public class TempFSTPulsing41PostingsFormat extends PostingsFormat {+ private final TempPostingsBaseFormat wrappedPostingsBaseFormat;++ public TempFSTPulsing41PostingsFormat() {+ super("TempFSTPulsing41");+ this.wrappedPostingsBaseFormat = new TempPostingsBaseFormat();+ }++ @Override+ public FieldsConsumer fieldsConsumer(SegmentWriteState state) throws IOException {+ TempPostingsWriterBase docsWriter = null;+ TempPostingsWriterBase pulsingWriter = null;++ boolean success = false;+ try {+ docsWriter = wrappedPostingsBaseFormat.postingsWriterBase(state);+ pulsingWriter = new TempPulsingPostingsWriter(state, 1, docsWriter);+ FieldsConsumer ret = new TempFSTTermsWriter(state, pulsingWriter);+ success = true;+ return ret;+ } finally {+ if (!success) {+ IOUtils.closeWhileHandlingException(docsWriter, pulsingWriter);+ }+ }+ }++ @Override+ public FieldsProducer fieldsProducer(SegmentReadState state) throws IOException {+ TempPostingsReaderBase docsReader = null;+ TempPostingsReaderBase pulsingReader = null;+ boolean success = false;+ try {+ docsReader = wrappedPostingsBaseFormat.postingsReaderBase(state);+ pulsingReader = new TempPulsingPostingsReader(state, docsReader);+ FieldsProducer ret = new TempFSTTermsReader(state, pulsingReader);+ success = true;+ return ret;+ } finally {+ if (!success) {+ IOUtils.closeWhileHandlingException(docsReader, pulsingReader);+ }+ }+ }+}diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempPulsing41PostingsFormat.java b/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempPulsing41PostingsFormat.javanew file mode 100644index 00000000000..5d90face596--- /dev/null+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempPulsing41PostingsFormat.java@@ -0,0 +1,46 @@+package org.apache.lucene.codecs.temp;++/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import org.apache.lucene.codecs.BlockTreeTermsWriter;+import org.apache.lucene.codecs.lucene41.Lucene41PostingsBaseFormat;+import org.apache.lucene.codecs.lucene41.Lucene41PostingsFormat; // javadocs+import org.apache.lucene.codecs.temp.TempPostingsBaseFormat;++/**+ * Concrete pulsing implementation over {@link Lucene41PostingsFormat}.+ *+ * @lucene.experimental+ */+public class TempPulsing41PostingsFormat extends TempPulsingPostingsFormat {++ /** Inlines docFreq=1 terms, otherwise uses the normal "Lucene41" format. */+ public TempPulsing41PostingsFormat() {+ this(1);+ }++ /** Inlines docFreq=<code>freqCutoff</code> terms, otherwise uses the normal "Lucene41" format. */+ public TempPulsing41PostingsFormat(int freqCutoff) {+ this(freqCutoff, BlockTreeTermsWriter.DEFAULT_MIN_BLOCK_SIZE, BlockTreeTermsWriter.DEFAULT_MAX_BLOCK_SIZE);+ }++ /** Inlines docFreq=<code>freqCutoff</code> terms, otherwise uses the normal "Lucene41" format. */+ public TempPulsing41PostingsFormat(int freqCutoff, int minBlockSize, int maxBlockSize) {+ super("TempPulsing41", new TempPostingsBaseFormat(), freqCutoff, minBlockSize, maxBlockSize);+ }+}diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempPulsingPostingsFormat.java b/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempPulsingPostingsFormat.javanew file mode 100644index 00000000000..a112a11aa24--- /dev/null+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempPulsingPostingsFormat.java@@ -0,0 +1,119 @@+package org.apache.lucene.codecs.temp;++/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.io.IOException;++import org.apache.lucene.codecs.temp.TempBlockTreeTermsReader;+import org.apache.lucene.codecs.temp.TempBlockTreeTermsWriter;+import org.apache.lucene.codecs.FieldsConsumer;+import org.apache.lucene.codecs.FieldsProducer;+import org.apache.lucene.codecs.TempPostingsBaseFormat;+import org.apache.lucene.codecs.PostingsFormat;+import org.apache.lucene.codecs.TempPostingsReaderBase;+import org.apache.lucene.codecs.TempPostingsWriterBase;+import org.apache.lucene.index.SegmentReadState;+import org.apache.lucene.index.SegmentWriteState;+import org.apache.lucene.util.IOUtils;++/** This postings format "inlines" the postings for terms that have+ * low docFreq. It wraps another postings format, which is used for+ * writing the non-inlined terms.+ *+ * @lucene.experimental */++public abstract class TempPulsingPostingsFormat extends PostingsFormat {++ private final int freqCutoff;+ private final int minBlockSize;+ private final int maxBlockSize;+ private final TempPostingsBaseFormat wrappedPostingsBaseFormat;++ public TempPulsingPostingsFormat(String name, TempPostingsBaseFormat wrappedPostingsBaseFormat, int freqCutoff) {+ this(name, wrappedPostingsBaseFormat, freqCutoff, TempBlockTreeTermsWriter.DEFAULT_MIN_BLOCK_SIZE, TempBlockTreeTermsWriter.DEFAULT_MAX_BLOCK_SIZE);+ }++ /** Terms with freq <= freqCutoff are inlined into terms+ * dict. */+ public TempPulsingPostingsFormat(String name, TempPostingsBaseFormat wrappedPostingsBaseFormat, int freqCutoff, int minBlockSize, int maxBlockSize) {+ super(name);+ this.freqCutoff = freqCutoff;+ this.minBlockSize = minBlockSize;+ assert minBlockSize > 1;+ this.maxBlockSize = maxBlockSize;+ this.wrappedPostingsBaseFormat = wrappedPostingsBaseFormat;+ }++ @Override+ public String toString() {+ return getName() + "(freqCutoff=" + freqCutoff + " minBlockSize=" + minBlockSize + " maxBlockSize=" + maxBlockSize + ")";+ }++ @Override+ public FieldsConsumer fieldsConsumer(SegmentWriteState state) throws IOException {+ TempPostingsWriterBase docsWriter = null;++ // Terms that have <= freqCutoff number of docs are+ // "pulsed" (inlined):+ TempPostingsWriterBase pulsingWriter = null;++ // Terms dict+ boolean success = false;+ try {+ docsWriter = wrappedPostingsBaseFormat.postingsWriterBase(state);++ // Terms that have <= freqCutoff number of docs are+ // "pulsed" (inlined):+ pulsingWriter = new TempPulsingPostingsWriter(state, freqCutoff, docsWriter);+ FieldsConsumer ret = new TempBlockTreeTermsWriter(state, pulsingWriter, minBlockSize, maxBlockSize);+ success = true;+ return ret;+ } finally {+ if (!success) {+ IOUtils.closeWhileHandlingException(docsWriter, pulsingWriter);+ }+ }+ }++ @Override+ public FieldsProducer fieldsProducer(SegmentReadState state) throws IOException {+ TempPostingsReaderBase docsReader = null;+ TempPostingsReaderBase pulsingReader = null;++ boolean success = false;+ try {+ docsReader = wrappedPostingsBaseFormat.postingsReaderBase(state);+ pulsingReader = new TempPulsingPostingsReader(state, docsReader);+ FieldsProducer ret = new TempBlockTreeTermsReader(+ state.directory, state.fieldInfos, state.segmentInfo,+ pulsingReader,+ state.context,+ state.segmentSuffix);+ success = true;+ return ret;+ } finally {+ if (!success) {+ IOUtils.closeWhileHandlingException(docsReader, pulsingReader);+ }+ }+ }++ public int getFreqCutoff() {+ return freqCutoff;+ }+}diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempPulsingPostingsReader.java b/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempPulsingPostingsReader.javanew file mode 100644index 00000000000..583007509e2--- /dev/null+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempPulsingPostingsReader.java@@ -0,0 +1,660 @@+package org.apache.lucene.codecs.temp;++/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.io.IOException;+import java.util.IdentityHashMap;+import java.util.Map;+import java.util.TreeMap;++import org.apache.lucene.codecs.BlockTermState;+import org.apache.lucene.codecs.CodecUtil;+import org.apache.lucene.codecs.TempPostingsReaderBase;+import org.apache.lucene.index.DocsAndPositionsEnum;+import org.apache.lucene.index.DocsEnum;+import org.apache.lucene.index.IndexFileNames;+import org.apache.lucene.index.FieldInfo;+import org.apache.lucene.index.FieldInfo.IndexOptions;+import org.apache.lucene.index.SegmentReadState;+import org.apache.lucene.index.TermState;+import org.apache.lucene.store.ByteArrayDataInput;+import org.apache.lucene.store.DataInput;+import org.apache.lucene.store.IndexInput;+import org.apache.lucene.util.ArrayUtil;+import org.apache.lucene.util.Attribute;+import org.apache.lucene.util.AttributeImpl;+import org.apache.lucene.util.AttributeSource;+import org.apache.lucene.util.Bits;+import org.apache.lucene.util.BytesRef;+import org.apache.lucene.util.IOUtils;++/** Concrete class that reads the current doc/freq/skip+ * postings format+ * @lucene.experimental */++// TODO: -- should we switch "hasProx" higher up? and+// create two separate docs readers, one that also reads+// prox and one that doesn't?++public class TempPulsingPostingsReader extends TempPostingsReaderBase {++ // Fallback reader for non-pulsed terms:+ final TempPostingsReaderBase wrappedPostingsReader;+ final SegmentReadState segmentState;+ int maxPositions;+ int version;+ TreeMap<Integer, Integer> fields;++ public TempPulsingPostingsReader(SegmentReadState state, TempPostingsReaderBase wrappedPostingsReader) {+ this.wrappedPostingsReader = wrappedPostingsReader;+ this.segmentState = state;+ }++ @Override+ public void init(IndexInput termsIn) throws IOException {+ version = CodecUtil.checkHeader(termsIn, TempPulsingPostingsWriter.CODEC,+ TempPulsingPostingsWriter.VERSION_START,+ TempPulsingPostingsWriter.VERSION_CURRENT);+ // nocommit: here open file to load field summary+ maxPositions = termsIn.readVInt();+ wrappedPostingsReader.init(termsIn);+ if (version >= TempPulsingPostingsWriter.VERSION_META_ARRAY) {+ fields = new TreeMap<Integer, Integer>();+ String summaryFileName = IndexFileNames.segmentFileName(segmentState.segmentInfo.name, segmentState.segmentSuffix, TempPulsingPostingsWriter.SUMMARY_EXTENSION);+ IndexInput in = null;+ try {+ in = segmentState.directory.openInput(summaryFileName, segmentState.context);+ CodecUtil.checkHeader(in, TempPulsingPostingsWriter.CODEC, version,+ TempPulsingPostingsWriter.VERSION_CURRENT);+ int numField = in.readVInt();+ for (int i = 0; i < numField; i++) {+ int fieldNum = in.readVInt();+ int longsSize = in.readVInt();+ fields.put(fieldNum, longsSize);+ }+ } finally {+ IOUtils.closeWhileHandlingException(in);+ }+ } else {+ assert false;+ fields = null;+ }+ }++ private static class PulsingTermState extends BlockTermState {+ private boolean absolute = false;+ private long[] longs;+ private byte[] postings;+ private int postingsSize; // -1 if this term was not inlined+ private BlockTermState wrappedTermState;++ @Override+ public PulsingTermState clone() {+ PulsingTermState clone;+ clone = (PulsingTermState) super.clone();+ if (postingsSize != -1) {+ clone.postings = new byte[postingsSize];+ System.arraycopy(postings, 0, clone.postings, 0, postingsSize);+ } else {+ assert wrappedTermState != null;+ clone.wrappedTermState = (BlockTermState) wrappedTermState.clone();+ clone.absolute = absolute;+ if (longs != null) {+ clone.longs = new long[longs.length];+ System.arraycopy(longs, 0, clone.longs, 0, longs.length);+ }+ }+ return clone;+ }++ @Override+ public void copyFrom(TermState _other) {+ super.copyFrom(_other);+ PulsingTermState other = (PulsingTermState) _other;+ postingsSize = other.postingsSize;+ if (other.postingsSize != -1) {+ if (postings == null || postings.length < other.postingsSize) {+ postings = new byte[ArrayUtil.oversize(other.postingsSize, 1)];+ }+ System.arraycopy(other.postings, 0, postings, 0, other.postingsSize);+ } else {+ wrappedTermState.copyFrom(other.wrappedTermState);+ }+ }++ @Override+ public String toString() {+ if (postingsSize == -1) {+ return "PulsingTermState: not inlined: wrapped=" + wrappedTermState;+ } else {+ return "PulsingTermState: inlined size=" + postingsSize + " " + super.toString();+ }+ }+ }++ @Override+ public BlockTermState newTermState() throws IOException {+ PulsingTermState state = new PulsingTermState();+ state.wrappedTermState = wrappedPostingsReader.newTermState();+ return state;+ }++ @Override+ public void decodeTerm(long[] empty, DataInput in, FieldInfo fieldInfo, BlockTermState _termState, boolean absolute) throws IOException {+ //System.out.println("PR nextTerm");+ PulsingTermState termState = (PulsingTermState) _termState;+ assert empty.length == 0;+ termState.absolute = termState.absolute || absolute;+ // if we have positions, its total TF, otherwise its computed based on docFreq.+ long count = fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0 ? termState.totalTermFreq : termState.docFreq;+ //System.out.println(" count=" + count + " threshold=" + maxPositions);++ // term dict have no chance to init this+ // nocommit: nuke this?+ if (termState.termBlockOrd == 0) {+ termState.wrappedTermState.termBlockOrd = 0;+ }+ if (count <= maxPositions) {+ // Inlined into terms dict -- just read the byte[] blob in,+ // but don't decode it now (we only decode when a DocsEnum+ // or D&PEnum is pulled):+ termState.postingsSize = in.readVInt();+ if (termState.postings == null || termState.postings.length < termState.postingsSize) {+ termState.postings = new byte[ArrayUtil.oversize(termState.postingsSize, 1)];+ }+ // TODO: sort of silly to copy from one big byte[]+ // (the blob holding all inlined terms' blobs for+ // current term block) into another byte[] (just the+ // blob for this term)...+ in.readBytes(termState.postings, 0, termState.postingsSize);+ //System.out.println(" inlined bytes=" + termState.postingsSize);+ termState.absolute = absolute ? true : termState.absolute;+ } else {+ //System.out.println(" not inlined");+ final int longsSize = fields.get(fieldInfo.number);+ if (termState.longs == null) {+ termState.longs = new long[longsSize];+ } else {+ assert termState.longs.length == longsSize;+ }+ for (int i = 0; i < longsSize; i++) {+ termState.longs[i] = in.readVLong();+ }+ termState.postingsSize = -1;+ termState.wrappedTermState.docFreq = termState.docFreq;+ termState.wrappedTermState.totalTermFreq = termState.totalTermFreq;+ wrappedPostingsReader.decodeTerm(termState.longs, in, fieldInfo, termState.wrappedTermState, termState.absolute);+ termState.wrappedTermState.termBlockOrd++;+ termState.absolute = false;+ }+ }++ @Override+ public DocsEnum docs(FieldInfo field, BlockTermState _termState, Bits liveDocs, DocsEnum reuse, int flags) throws IOException {+ PulsingTermState termState = (PulsingTermState) _termState;+ if (termState.postingsSize != -1) {+ PulsingDocsEnum postings;+ if (reuse instanceof PulsingDocsEnum) {+ postings = (PulsingDocsEnum) reuse;+ if (!postings.canReuse(field)) {+ postings = new PulsingDocsEnum(field);+ }+ } else {+ // the 'reuse' is actually the wrapped enum+ PulsingDocsEnum previous = (PulsingDocsEnum) getOther(reuse);+ if (previous != null && previous.canReuse(field)) {+ postings = previous;+ } else {+ postings = new PulsingDocsEnum(field);+ }+ }+ if (reuse != postings) {+ setOther(postings, reuse); // postings.other = reuse+ }+ return postings.reset(liveDocs, termState);+ } else {+ if (reuse instanceof PulsingDocsEnum) {+ DocsEnum wrapped = wrappedPostingsReader.docs(field, termState.wrappedTermState, liveDocs, getOther(reuse), flags);+ setOther(wrapped, reuse); // wrapped.other = reuse+ return wrapped;+ } else {+ return wrappedPostingsReader.docs(field, termState.wrappedTermState, liveDocs, reuse, flags);+ }+ }+ }++ @Override+ public DocsAndPositionsEnum docsAndPositions(FieldInfo field, BlockTermState _termState, Bits liveDocs, DocsAndPositionsEnum reuse,+ int flags) throws IOException {++ final PulsingTermState termState = (PulsingTermState) _termState;++ if (termState.postingsSize != -1) {+ PulsingDocsAndPositionsEnum postings;+ if (reuse instanceof PulsingDocsAndPositionsEnum) {+ postings = (PulsingDocsAndPositionsEnum) reuse;+ if (!postings.canReuse(field)) {+ postings = new PulsingDocsAndPositionsEnum(field);+ }+ } else {+ // the 'reuse' is actually the wrapped enum+ PulsingDocsAndPositionsEnum previous = (PulsingDocsAndPositionsEnum) getOther(reuse);+ if (previous != null && previous.canReuse(field)) {+ postings = previous;+ } else {+ postings = new PulsingDocsAndPositionsEnum(field);+ }+ }+ if (reuse != postings) {+ setOther(postings, reuse); // postings.other = reuse+ }+ return postings.reset(liveDocs, termState);+ } else {+ if (reuse instanceof PulsingDocsAndPositionsEnum) {+ DocsAndPositionsEnum wrapped = wrappedPostingsReader.docsAndPositions(field, termState.wrappedTermState, liveDocs, (DocsAndPositionsEnum) getOther(reuse),+ flags);+ setOther(wrapped, reuse); // wrapped.other = reuse+ return wrapped;+ } else {+ return wrappedPostingsReader.docsAndPositions(field, termState.wrappedTermState, liveDocs, reuse, flags);+ }+ }+ }++ private static class PulsingDocsEnum extends DocsEnum {+ private byte[] postingsBytes;+ private final ByteArrayDataInput postings = new ByteArrayDataInput();+ private final IndexOptions indexOptions;+ private final boolean storePayloads;+ private final boolean storeOffsets;+ private Bits liveDocs;+ private int docID = -1;+ private int accum;+ private int freq;+ private int payloadLength;+ private int cost;++ public PulsingDocsEnum(FieldInfo fieldInfo) {+ indexOptions = fieldInfo.getIndexOptions();+ storePayloads = fieldInfo.hasPayloads();+ storeOffsets = indexOptions.compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0;+ }++ public PulsingDocsEnum reset(Bits liveDocs, PulsingTermState termState) {+ //System.out.println("PR docsEnum termState=" + termState + " docFreq=" + termState.docFreq);+ assert termState.postingsSize != -1;++ // Must make a copy of termState's byte[] so that if+ // app does TermsEnum.next(), this DocsEnum is not affected+ if (postingsBytes == null) {+ postingsBytes = new byte[termState.postingsSize];+ } else if (postingsBytes.length < termState.postingsSize) {+ postingsBytes = ArrayUtil.grow(postingsBytes, termState.postingsSize);+ }+ System.arraycopy(termState.postings, 0, postingsBytes, 0, termState.postingsSize);+ postings.reset(postingsBytes, 0, termState.postingsSize);+ docID = -1;+ accum = 0;+ freq = 1;+ cost = termState.docFreq;+ payloadLength = 0;+ this.liveDocs = liveDocs;+ return this;+ }++ boolean canReuse(FieldInfo fieldInfo) {+ return indexOptions == fieldInfo.getIndexOptions() && storePayloads == fieldInfo.hasPayloads();+ }++ @Override+ public int nextDoc() throws IOException {+ //System.out.println("PR nextDoc this= "+ this);+ while(true) {+ if (postings.eof()) {+ //System.out.println("PR END");+ return docID = NO_MORE_DOCS;+ }++ final int code = postings.readVInt();+ //System.out.println(" read code=" + code);+ if (indexOptions == IndexOptions.DOCS_ONLY) {+ accum += code;+ } else {+ accum += code >>> 1; // shift off low bit+ if ((code & 1) != 0) { // if low bit is set+ freq = 1; // freq is one+ } else {+ freq = postings.readVInt(); // else read freq+ }++ if (indexOptions.compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0) {+ // Skip positions+ if (storePayloads) {+ for(int pos=0;pos<freq;pos++) {+ final int posCode = postings.readVInt();+ if ((posCode & 1) != 0) {+ payloadLength = postings.readVInt();+ }+ if (storeOffsets && (postings.readVInt() & 1) != 0) {+ // new offset length+ postings.readVInt();+ }+ if (payloadLength != 0) {+ postings.skipBytes(payloadLength);+ }+ }+ } else {+ for(int pos=0;pos<freq;pos++) {+ // TODO: skipVInt+ postings.readVInt();+ if (storeOffsets && (postings.readVInt() & 1) != 0) {+ // new offset length+ postings.readVInt();+ }+ }+ }+ }+ }++ if (liveDocs == null || liveDocs.get(accum)) {+ return (docID = accum);+ }+ }+ }++ @Override+ public int freq() throws IOException {+ return freq;+ }++ @Override+ public int docID() {+ return docID;+ }++ @Override+ public int advance(int target) throws IOException {+ return docID = slowAdvance(target);+ }++ @Override+ public long cost() {+ return cost;+ }+ }++ private static class PulsingDocsAndPositionsEnum extends DocsAndPositionsEnum {+ private byte[] postingsBytes;+ private final ByteArrayDataInput postings = new ByteArrayDataInput();+ private final boolean storePayloads;+ private final boolean storeOffsets;+ // note: we could actually reuse across different options, if we passed this to reset()+ // and re-init'ed storeOffsets accordingly (made it non-final)+ private final IndexOptions indexOptions;++ private Bits liveDocs;+ private int docID = -1;+ private int accum;+ private int freq;+ private int posPending;+ private int position;+ private int payloadLength;+ private BytesRef payload;+ private int startOffset;+ private int offsetLength;++ private boolean payloadRetrieved;+ private int cost;++ public PulsingDocsAndPositionsEnum(FieldInfo fieldInfo) {+ indexOptions = fieldInfo.getIndexOptions();+ storePayloads = fieldInfo.hasPayloads();+ storeOffsets = indexOptions.compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0;+ }++ boolean canReuse(FieldInfo fieldInfo) {+ return indexOptions == fieldInfo.getIndexOptions() && storePayloads == fieldInfo.hasPayloads();+ }++ public PulsingDocsAndPositionsEnum reset(Bits liveDocs, PulsingTermState termState) {+ assert termState.postingsSize != -1;+ if (postingsBytes == null) {+ postingsBytes = new byte[termState.postingsSize];+ } else if (postingsBytes.length < termState.postingsSize) {+ postingsBytes = ArrayUtil.grow(postingsBytes, termState.postingsSize);+ }+ System.arraycopy(termState.postings, 0, postingsBytes, 0, termState.postingsSize);+ postings.reset(postingsBytes, 0, termState.postingsSize);+ this.liveDocs = liveDocs;+ payloadLength = 0;+ posPending = 0;+ docID = -1;+ accum = 0;+ cost = termState.docFreq;+ startOffset = storeOffsets ? 0 : -1; // always return -1 if no offsets are stored+ offsetLength = 0;+ //System.out.println("PR d&p reset storesPayloads=" + storePayloads + " bytes=" + bytes.length + " this=" + this);+ return this;+ }++ @Override+ public int nextDoc() throws IOException {+ //System.out.println("PR d&p nextDoc this=" + this);++ while(true) {+ //System.out.println(" cycle skip posPending=" + posPending);++ skipPositions();++ if (postings.eof()) {+ //System.out.println("PR END");+ return docID = NO_MORE_DOCS;+ }++ final int code = postings.readVInt();+ accum += code >>> 1; // shift off low bit+ if ((code & 1) != 0) { // if low bit is set+ freq = 1; // freq is one+ } else {+ freq = postings.readVInt(); // else read freq+ }+ posPending = freq;+ startOffset = storeOffsets ? 0 : -1; // always return -1 if no offsets are stored++ if (liveDocs == null || liveDocs.get(accum)) {+ //System.out.println(" return docID=" + docID + " freq=" + freq);+ position = 0;+ return (docID = accum);+ }+ }+ }++ @Override+ public int freq() throws IOException {+ return freq;+ }++ @Override+ public int docID() {+ return docID;+ }++ @Override+ public int advance(int target) throws IOException {+ return docID = slowAdvance(target);+ }++ @Override+ public int nextPosition() throws IOException {+ //System.out.println("PR d&p nextPosition posPending=" + posPending + " vs freq=" + freq);++ assert posPending > 0;+ posPending--;++ if (storePayloads) {+ if (!payloadRetrieved) {+ //System.out.println("PR skip payload=" + payloadLength);+ postings.skipBytes(payloadLength);+ }+ final int code = postings.readVInt();+ //System.out.println("PR code=" + code);+ if ((code & 1) != 0) {+ payloadLength = postings.readVInt();+ //System.out.println("PR new payload len=" + payloadLength);+ }+ position += code >>> 1;+ payloadRetrieved = false;+ } else {+ position += postings.readVInt();+ }++ if (storeOffsets) {+ int offsetCode = postings.readVInt();+ if ((offsetCode & 1) != 0) {+ // new offset length+ offsetLength = postings.readVInt();+ }+ startOffset += offsetCode >>> 1;+ }++ //System.out.println("PR d&p nextPos return pos=" + position + " this=" + this);+ return position;+ }++ @Override+ public int startOffset() {+ return startOffset;+ }++ @Override+ public int endOffset() {+ return startOffset + offsetLength;+ }++ private void skipPositions() throws IOException {+ while(posPending != 0) {+ nextPosition();+ }+ if (storePayloads && !payloadRetrieved) {+ //System.out.println(" skip payload len=" + payloadLength);+ postings.skipBytes(payloadLength);+ payloadRetrieved = true;+ }+ }++ @Override+ public BytesRef getPayload() throws IOException {+ //System.out.println("PR getPayload payloadLength=" + payloadLength + " this=" + this);+ if (payloadRetrieved) {+ return payload;+ } else if (storePayloads && payloadLength > 0) {+ payloadRetrieved = true;+ if (payload == null) {+ payload = new BytesRef(payloadLength);+ } else {+ payload.grow(payloadLength);+ }+ postings.readBytes(payload.bytes, 0, payloadLength);+ payload.length = payloadLength;+ return payload;+ } else {+ return null;+ }+ }++ @Override+ public long cost() {+ return cost;+ }+ }++ @Override+ public void close() throws IOException {+ wrappedPostingsReader.close();+ }++ /** for a docsenum, gets the 'other' reused enum.+ * Example: Pulsing(Standard).+ * when doing a term range query you are switching back and forth+ * between Pulsing and Standard+ *+ * The way the reuse works is that Pulsing.other = Standard and+ * Standard.other = Pulsing.+ */+ private DocsEnum getOther(DocsEnum de) {+ if (de == null) {+ return null;+ } else {+ final AttributeSource atts = de.attributes();+ return atts.addAttribute(PulsingEnumAttribute.class).enums().get(this);+ }+ }++ /**+ * for a docsenum, sets the 'other' reused enum.+ * see getOther for an example.+ */+ private DocsEnum setOther(DocsEnum de, DocsEnum other) {+ final AttributeSource atts = de.attributes();+ return atts.addAttribute(PulsingEnumAttribute.class).enums().put(this, other);+ }++ /**+ * A per-docsenum attribute that stores additional reuse information+ * so that pulsing enums can keep a reference to their wrapped enums,+ * and vice versa. this way we can always reuse.+ *+ * @lucene.internal */+ public static interface PulsingEnumAttribute extends Attribute {+ public Map<TempPulsingPostingsReader,DocsEnum> enums();+ }++ /**+ * Implementation of {@link PulsingEnumAttribute} for reuse of+ * wrapped postings readers underneath pulsing.+ *+ * @lucene.internal */+ public static final class PulsingEnumAttributeImpl extends AttributeImpl implements PulsingEnumAttribute {+ // we could store 'other', but what if someone 'chained' multiple postings readers,+ // this could cause problems?+ // TODO: we should consider nuking this map and just making it so if you do this,+ // you don't reuse? and maybe pulsingPostingsReader should throw an exc if it wraps+ // another pulsing, because this is just stupid and wasteful.+ // we still have to be careful in case someone does Pulsing(Stomping(Pulsing(...+ private final Map<TempPulsingPostingsReader,DocsEnum> enums =+ new IdentityHashMap<TempPulsingPostingsReader,DocsEnum>();++ @Override+ public Map<TempPulsingPostingsReader,DocsEnum> enums() {+ return enums;+ }++ @Override+ public void clear() {+ // our state is per-docsenum, so this makes no sense.+ // its best not to clear, in case a wrapped enum has a per-doc attribute or something+ // and is calling clearAttributes(), so they don't nuke the reuse information!+ }++ @Override+ public void copyTo(AttributeImpl target) {+ // this makes no sense for us, because our state is per-docsenum.+ // we don't want to copy any stuff over to another docsenum ever!+ }+ }+}diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempPulsingPostingsWriter.java b/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempPulsingPostingsWriter.javanew file mode 100644index 00000000000..55490c359c9--- /dev/null+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/temp/TempPulsingPostingsWriter.java@@ -0,0 +1,456 @@+package org.apache.lucene.codecs.temp;++/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.io.IOException;+import java.util.List;+import java.util.ArrayList;++import org.apache.lucene.codecs.BlockTermState;+import org.apache.lucene.codecs.CodecUtil;+import org.apache.lucene.codecs.TempPostingsWriterBase;+import org.apache.lucene.codecs.TermStats;+import org.apache.lucene.index.FieldInfo;+import org.apache.lucene.index.FieldInfo.IndexOptions;+import org.apache.lucene.index.IndexFileNames;+import org.apache.lucene.index.SegmentWriteState;+import org.apache.lucene.store.DataOutput;+import org.apache.lucene.store.IndexOutput;+import org.apache.lucene.store.RAMOutputStream;+import org.apache.lucene.util.BytesRef;+import org.apache.lucene.util.IOUtils;++// TODO: we now inline based on total TF of the term,+// but it might be better to inline by "net bytes used"+// so that a term that has only 1 posting but a huge+// payload would not be inlined. Though this is+// presumably rare in practice...++/**+ * Writer for the pulsing format.+ * <p>+ * Wraps another postings implementation and decides+ * (based on total number of occurrences), whether a terms+ * postings should be inlined into the term dictionary,+ * or passed through to the wrapped writer.+ *+ * @lucene.experimental */+public final class TempPulsingPostingsWriter extends TempPostingsWriterBase {++ final static String CODEC = "TempPulsedPostingsWriter";++ // recording field summary+ final static String SUMMARY_EXTENSION = "smy";++ // To add a new version, increment from the last one, and+ // change VERSION_CURRENT to point to your new version:+ final static int VERSION_START = 0;++ final static int VERSION_META_ARRAY = 0;++ final static int VERSION_CURRENT = VERSION_META_ARRAY;++ private SegmentWriteState segmentState;+ private IndexOutput termsOut;++ private List<FieldMetaData> fields;++ private IndexOptions indexOptions;+ private boolean storePayloads;++ // information for wrapped PF, in current field+ private int longsSize;+ private long[] longs;+ boolean absolute;++ private static class PulsingTermState extends BlockTermState {+ private byte[] bytes;+ private BlockTermState wrappedState;+ @Override+ public String toString() {+ if (bytes != null) {+ return "inlined";+ } else {+ return "not inlined wrapped=" + wrappedState;+ }+ }+ }++ // one entry per position+ private final Position[] pending;+ private int pendingCount = 0; // -1 once we've hit too many positions+ private Position currentDoc; // first Position entry of current doc++ private static final class Position {+ BytesRef payload;+ int termFreq; // only incremented on first position for a given doc+ int pos;+ int docID;+ int startOffset;+ int endOffset;+ }++ private static final class FieldMetaData {+ int fieldNumber;+ int longsSize;+ FieldMetaData(int number, int size) {+ fieldNumber = number;+ longsSize = size;+ }+ }++ // TODO: -- lazy init this? ie, if every single term+ // was inlined (eg for a "primary key" field) then we+ // never need to use this fallback? Fallback writer for+ // non-inlined terms:+ final TempPostingsWriterBase wrappedPostingsWriter;++ /** If the total number of positions (summed across all docs+ * for this term) is <= maxPositions, then the postings are+ * inlined into terms dict */+ public TempPulsingPostingsWriter(SegmentWriteState state, int maxPositions, TempPostingsWriterBase wrappedPostingsWriter) {++ pending = new Position[maxPositions];+ for(int i=0;i<maxPositions;i++) {+ pending[i] = new Position();+ }+ fields = new ArrayList<FieldMetaData>();++ // We simply wrap another postings writer, but only call+ // on it when tot positions is >= the cutoff:+ this.wrappedPostingsWriter = wrappedPostingsWriter;+ this.segmentState = state;+ }++ @Override+ public void init(IndexOutput termsOut) throws IOException {+ this.termsOut = termsOut;+ CodecUtil.writeHeader(termsOut, CODEC, VERSION_CURRENT);+ termsOut.writeVInt(pending.length); // encode maxPositions in header+ wrappedPostingsWriter.init(termsOut);+ }++ @Override+ public BlockTermState newTermState() throws IOException {+ PulsingTermState state = new PulsingTermState();+ state.wrappedState = wrappedPostingsWriter.newTermState();+ return state;+ }++ @Override+ public void startTerm() {+ //if (DEBUG) System.out.println("PW startTerm");+ assert pendingCount == 0;+ }++ // TODO: -- should we NOT reuse across fields? would+ // be cleaner++ // Currently, this instance is re-used across fields, so+ // our parent calls setField whenever the field changes+ @Override+ public int setField(FieldInfo fieldInfo) {+ this.indexOptions = fieldInfo.getIndexOptions();+ //if (DEBUG) System.out.println("PW field=" + fieldInfo.name + " indexOptions=" + indexOptions);+ storePayloads = fieldInfo.hasPayloads();+ absolute = false;+ longsSize = wrappedPostingsWriter.setField(fieldInfo);+ longs = new long[longsSize];+ fields.add(new FieldMetaData(fieldInfo.number, longsSize));+ return 0;+ //DEBUG = BlockTreeTermsWriter.DEBUG;+ }++ private boolean DEBUG;++ @Override+ public void startDoc(int docID, int termDocFreq) throws IOException {+ assert docID >= 0: "got docID=" + docID;++ /*+ if (termID != -1) {+ if (docID == 0) {+ baseDocID = termID;+ } else if (baseDocID + docID != termID) {+ throw new RuntimeException("WRITE: baseDocID=" + baseDocID + " docID=" + docID + " termID=" + termID);+ }+ }+ */++ //if (DEBUG) System.out.println("PW doc=" + docID);++ if (pendingCount == pending.length) {+ push();+ //if (DEBUG) System.out.println("PW: wrapped.finishDoc");+ wrappedPostingsWriter.finishDoc();+ }++ if (pendingCount != -1) {+ assert pendingCount < pending.length;+ currentDoc = pending[pendingCount];+ currentDoc.docID = docID;+ if (indexOptions == IndexOptions.DOCS_ONLY) {+ pendingCount++;+ } else if (indexOptions == IndexOptions.DOCS_AND_FREQS) {+ pendingCount++;+ currentDoc.termFreq = termDocFreq;+ } else {+ currentDoc.termFreq = termDocFreq;+ }+ } else {+ // We've already seen too many docs for this term --+ // just forward to our fallback writer+ wrappedPostingsWriter.startDoc(docID, termDocFreq);+ }+ }++ @Override+ public void addPosition(int position, BytesRef payload, int startOffset, int endOffset) throws IOException {++ //if (DEBUG) System.out.println("PW pos=" + position + " payload=" + (payload == null ? "null" : payload.length + " bytes"));+ if (pendingCount == pending.length) {+ push();+ }++ if (pendingCount == -1) {+ // We've already seen too many docs for this term --+ // just forward to our fallback writer+ wrappedPostingsWriter.addPosition(position, payload, startOffset, endOffset);+ } else {+ // buffer up+ final Position pos = pending[pendingCount++];+ pos.pos = position;+ pos.startOffset = startOffset;+ pos.endOffset = endOffset;+ pos.docID = currentDoc.docID;+ if (payload != null && payload.length > 0) {+ if (pos.payload == null) {+ pos.payload = BytesRef.deepCopyOf(payload);+ } else {+ pos.payload.copyBytes(payload);+ }+ } else if (pos.payload != null) {+ pos.payload.length = 0;+ }+ }+ }++ @Override+ public void finishDoc() throws IOException {+ // if (DEBUG) System.out.println("PW finishDoc");+ if (pendingCount == -1) {+ wrappedPostingsWriter.finishDoc();+ }+ }++ private final RAMOutputStream buffer = new RAMOutputStream();++ // private int baseDocID;++ /** Called when we are done adding docs to this term */+ @Override+ public void finishTerm(BlockTermState _state) throws IOException {+ PulsingTermState state = (PulsingTermState) _state;++ // if (DEBUG) System.out.println("PW finishTerm docCount=" + stats.docFreq + " pendingCount=" + pendingCount + " pendingTerms.size()=" + pendingTerms.size());++ assert pendingCount > 0 || pendingCount == -1;++ if (pendingCount == -1) {+ state.wrappedState.docFreq = state.docFreq;+ state.wrappedState.totalTermFreq = state.totalTermFreq;+ state.bytes = null;+ wrappedPostingsWriter.finishTerm(state.wrappedState);+ } else {+ // There were few enough total occurrences for this+ // term, so we fully inline our postings data into+ // terms dict, now:++ // TODO: it'd be better to share this encoding logic+ // in some inner codec that knows how to write a+ // single doc / single position, etc. This way if a+ // given codec wants to store other interesting+ // stuff, it could use this pulsing codec to do so++ if (indexOptions.compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0) {+ int lastDocID = 0;+ int pendingIDX = 0;+ int lastPayloadLength = -1;+ int lastOffsetLength = -1;+ while(pendingIDX < pendingCount) {+ final Position doc = pending[pendingIDX];++ final int delta = doc.docID - lastDocID;+ lastDocID = doc.docID;++ // if (DEBUG) System.out.println(" write doc=" + doc.docID + " freq=" + doc.termFreq);++ if (doc.termFreq == 1) {+ buffer.writeVInt((delta<<1)|1);+ } else {+ buffer.writeVInt(delta<<1);+ buffer.writeVInt(doc.termFreq);+ }++ int lastPos = 0;+ int lastOffset = 0;+ for(int posIDX=0;posIDX<doc.termFreq;posIDX++) {+ final Position pos = pending[pendingIDX++];+ assert pos.docID == doc.docID;+ final int posDelta = pos.pos - lastPos;+ lastPos = pos.pos;+ // if (DEBUG) System.out.println(" write pos=" + pos.pos);+ final int payloadLength = pos.payload == null ? 0 : pos.payload.length;+ if (storePayloads) {+ if (payloadLength != lastPayloadLength) {+ buffer.writeVInt((posDelta << 1)|1);+ buffer.writeVInt(payloadLength);+ lastPayloadLength = payloadLength;+ } else {+ buffer.writeVInt(posDelta << 1);+ }+ } else {+ buffer.writeVInt(posDelta);+ }++ if (indexOptions.compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0) {+ //System.out.println("write=" + pos.startOffset + "," + pos.endOffset);+ int offsetDelta = pos.startOffset - lastOffset;+ int offsetLength = pos.endOffset - pos.startOffset;+ if (offsetLength != lastOffsetLength) {+ buffer.writeVInt(offsetDelta << 1 | 1);+ buffer.writeVInt(offsetLength);+ } else {+ buffer.writeVInt(offsetDelta << 1);+ }+ lastOffset = pos.startOffset;+ lastOffsetLength = offsetLength;+ }++ if (payloadLength > 0) {+ assert storePayloads;+ buffer.writeBytes(pos.payload.bytes, 0, pos.payload.length);+ }+ }+ }+ } else if (indexOptions == IndexOptions.DOCS_AND_FREQS) {+ int lastDocID = 0;+ for(int posIDX=0;posIDX<pendingCount;posIDX++) {+ final Position doc = pending[posIDX];+ final int delta = doc.docID - lastDocID;+ assert doc.termFreq != 0;+ if (doc.termFreq == 1) {+ buffer.writeVInt((delta<<1)|1);+ } else {+ buffer.writeVInt(delta<<1);+ buffer.writeVInt(doc.termFreq);+ }+ lastDocID = doc.docID;+ }+ } else if (indexOptions == IndexOptions.DOCS_ONLY) {+ int lastDocID = 0;+ for(int posIDX=0;posIDX<pendingCount;posIDX++) {+ final Position doc = pending[posIDX];+ buffer.writeVInt(doc.docID - lastDocID);+ lastDocID = doc.docID;+ }+ }++ state.bytes = new byte[(int) buffer.getFilePointer()];+ buffer.writeTo(state.bytes, 0);+ buffer.reset();+ }+ pendingCount = 0;+ }++ @Override+ public void encodeTerm(long[] empty, DataOutput out, FieldInfo fieldInfo, BlockTermState _state, boolean absolute) throws IOException {+ PulsingTermState state = (PulsingTermState)_state;+ assert empty.length == 0;+ this.absolute = this.absolute || absolute;+ if (state.bytes == null) {+ assert longsSize > 0;+ wrappedPostingsWriter.encodeTerm(longs, buffer, fieldInfo, state.wrappedState, this.absolute);+ for (int i = 0; i < longsSize; i++) {+ out.writeVLong(longs[i]);+ }+ buffer.writeTo(out);+ buffer.reset();+ this.absolute = false;+ } else {+ out.writeVInt(state.bytes.length);+ out.writeBytes(state.bytes, 0, state.bytes.length);+ this.absolute = absolute ? true : this.absolute;+ }+ }++ @Override+ public void close() throws IOException {+ wrappedPostingsWriter.close();+ assert (VERSION_CURRENT >= VERSION_META_ARRAY);+ String summaryFileName = IndexFileNames.segmentFileName(segmentState.segmentInfo.name, segmentState.segmentSuffix, SUMMARY_EXTENSION);+ IndexOutput out = null;+ try {+ out = segmentState.directory.createOutput(summaryFileName, segmentState.context);+ CodecUtil.writeHeader(out, CODEC, VERSION_CURRENT);+ out.writeVInt(fields.size());+ for (FieldMetaData field : fields) {+ out.writeVInt(field.fieldNumber);+ out.writeVInt(field.longsSize);+ }+ out.close();+ } finally {+ IOUtils.closeWhileHandlingException(out);+ }+ }++ // Pushes pending positions to the wrapped codec+ private void push() throws IOException {+ // if (DEBUG) System.out.println("PW now push @ " + pendingCount + " wrapped=" + wrappedPostingsWriter);+ assert pendingCount == pending.length;++ wrappedPostingsWriter.startTerm();++ // Flush all buffered docs+ if (indexOptions.compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0) {+ Position doc = null;+ for(Position pos : pending) {+ if (doc == null) {+ doc = pos;+ // if (DEBUG) System.out.println("PW: wrapped.startDoc docID=" + doc.docID + " tf=" + doc.termFreq);+ wrappedPostingsWriter.startDoc(doc.docID, doc.termFreq);+ } else if (doc.docID != pos.docID) {+ assert pos.docID > doc.docID;+ // if (DEBUG) System.out.println("PW: wrapped.finishDoc");+ wrappedPostingsWriter.finishDoc();+ doc = pos;+ // if (DEBUG) System.out.println("PW: wrapped.startDoc docID=" + doc.docID + " tf=" + doc.termFreq);+ wrappedPostingsWriter.startDoc(doc.docID, doc.termFreq);+ }+ // if (DEBUG) System.out.println("PW: wrapped.addPos pos=" + pos.pos);+ wrappedPostingsWriter.addPosition(pos.pos, pos.payload, pos.startOffset, pos.endOffset);+ }+ //wrappedPostingsWriter.finishDoc();+ } else {+ for(Position doc : pending) {+ wrappedPostingsWriter.startDoc(doc.docID, indexOptions == IndexOptions.DOCS_ONLY ? 0 : doc.termFreq);+ }+ }+ pendingCount = -1;+ }+}diff --git a/lucene/codecs/src/resources/META-INF/services/org.apache.lucene.codecs.PostingsFormat b/lucene/codecs/src/resources/META-INF/services/org.apache.lucene.codecs.PostingsFormatindex 3eaa2cf456f..a9e93dd674a 100644--- a/lucene/codecs/src/resources/META-INF/services/org.apache.lucene.codecs.PostingsFormat+++ b/lucene/codecs/src/resources/META-INF/services/org.apache.lucene.codecs.PostingsFormat@@ -19,3 +19,6 @@ org.apache.lucene.codecs.memory.MemoryPostingsFormatorg.apache.lucene.codecs.bloom.BloomFilteringPostingsFormatorg.apache.lucene.codecs.memory.DirectPostingsFormatorg.apache.lucene.codecs.temp.TempBlockPostingsFormat+org.apache.lucene.codecs.temp.TempPulsing41PostingsFormat+org.apache.lucene.codecs.temp.TempFSTPulsing41PostingsFormat+org.apache.lucene.codecs.temp.TempFSTOrdPulsing41PostingsFormatdiff --git a/lucene/core/src/java/org/apache/lucene/codecs/TempPostingsBaseFormat.java b/lucene/core/src/java/org/apache/lucene/codecs/TempPostingsBaseFormat.javanew file mode 100644index 00000000000..4b3470fd18e--- /dev/null+++ b/lucene/core/src/java/org/apache/lucene/codecs/TempPostingsBaseFormat.java@@ -0,0 +1,55 @@+package org.apache.lucene.codecs;++/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.io.IOException;++import org.apache.lucene.index.SegmentWriteState;+import org.apache.lucene.index.SegmentReadState;++/**+ * Provides a {@link PostingsReaderBase} and {@link+ * PostingsWriterBase}.+ *+ * @lucene.experimental */++// TODO: find a better name; this defines the API that the+// terms dict impls use to talk to a postings impl.+// TermsDict + PostingsReader/WriterBase == PostingsConsumer/Producer++// can we clean this up and do this some other way?+// refactor some of these classes and use covariant return?+public abstract class TempPostingsBaseFormat {++ /** Unique name that's used to retrieve this codec when+ * reading the index */+ public final String name;++ /** Sole constructor. */+ protected TempPostingsBaseFormat(String name) {+ this.name = name;+ }++ /** Creates the {@link PostingsReaderBase} for this+ * format. */+ public abstract TempPostingsReaderBase postingsReaderBase(SegmentReadState state) throws IOException;++ /** Creates the {@link PostingsWriterBase} for this+ * format. */+ public abstract TempPostingsWriterBase postingsWriterBase(SegmentWriteState state) throws IOException;+}diff --git a/lucene/core/src/java/org/apache/lucene/codecs/temp/TempFSTOrdTermsReader.java b/lucene/core/src/java/org/apache/lucene/codecs/temp/TempFSTOrdTermsReader.javaindex f8f35699baf..0fa434143fa 100644--- a/lucene/core/src/java/org/apache/lucene/codecs/temp/TempFSTOrdTermsReader.java+++ b/lucene/core/src/java/org/apache/lucene/codecs/temp/TempFSTOrdTermsReader.java@@ -100,7 +100,7 @@ public class TempFSTOrdTermsReader extends FieldsProducer {checkFieldSummary(state.segmentInfo, current, previous);}} finally {- IOUtils.close(indexIn, blockIn);+ IOUtils.closeWhileHandlingException(indexIn, blockIn);}}@@ -323,7 +323,7 @@ public class TempFSTOrdTermsReader extends FieldsProducer {if (metaBlockOrd != oldBlockOrd) {refillMetadata();}- metaBytesReader.reset(metaBytesBlock, bytesStart[upto], bytesLength[upto]);+ metaBytesReader.setPosition(bytesStart[upto]);postingsReader.decodeTerm(longs[upto], metaBytesReader, fieldInfo, state, true);}diff --git a/lucene/core/src/java/org/apache/lucene/codecs/temp/TempFSTOrdTermsWriter.java b/lucene/core/src/java/org/apache/lucene/codecs/temp/TempFSTOrdTermsWriter.javaindex a3b2a2575c9..ed9ccb7d0e9 100644--- a/lucene/core/src/java/org/apache/lucene/codecs/temp/TempFSTOrdTermsWriter.java+++ b/lucene/core/src/java/org/apache/lucene/codecs/temp/TempFSTOrdTermsWriter.java@@ -223,10 +223,10 @@ public class TempFSTOrdTermsWriter extends FieldsConsumer {state.docFreq = stats.docFreq;state.totalTermFreq = stats.totalTermFreq;postingsWriter.finishTerm(state);- postingsWriter.encodeTerm(longs, metaBytesOut, fieldInfo, state, false);+ postingsWriter.encodeTerm(longs, metaBytesOut, fieldInfo, state, true);for (int i = 0; i < longsSize; i++) {- metaLongsOut.writeVLong(longs[i]);- lastLongs[i] += longs[i];+ metaLongsOut.writeVLong(longs[i] - lastLongs[i]);+ lastLongs[i] = longs[i];}metaLongsOut.writeVLong(metaBytesOut.getFilePointer() - lastMetaBytesFP);diff --git a/lucene/core/src/java/org/apache/lucene/codecs/temp/TempFSTTermsReader.java b/lucene/core/src/java/org/apache/lucene/codecs/temp/TempFSTTermsReader.javaindex 9e6ec4882b4..83032b76ed6 100644--- a/lucene/core/src/java/org/apache/lucene/codecs/temp/TempFSTTermsReader.java+++ b/lucene/core/src/java/org/apache/lucene/codecs/temp/TempFSTTermsReader.java@@ -94,7 +94,7 @@ public class TempFSTTermsReader extends FieldsProducer {success = true;} finally {if (!success) {- in.close();+ IOUtils.closeWhileHandlingException(in);}}}diff --git a/lucene/core/src/java/org/apache/lucene/codecs/temp/TempPostingsBaseFormat.java b/lucene/core/src/java/org/apache/lucene/codecs/temp/TempPostingsBaseFormat.javanew file mode 100644index 00000000000..821313fc679--- /dev/null+++ b/lucene/core/src/java/org/apache/lucene/codecs/temp/TempPostingsBaseFormat.java@@ -0,0 +1,50 @@+package org.apache.lucene.codecs.temp;++/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.io.IOException;++import org.apache.lucene.codecs.TempPostingsReaderBase;+import org.apache.lucene.codecs.TempPostingsWriterBase;+import org.apache.lucene.index.SegmentReadState;+import org.apache.lucene.index.SegmentWriteState;++/**+ * Provides a {@link PostingsReaderBase} and {@link+ * PostingsWriterBase}.+ *+ * @lucene.experimental */++// TODO: should these also be named / looked up via SPI?+public final class TempPostingsBaseFormat extends org.apache.lucene.codecs.TempPostingsBaseFormat {++ /** Sole constructor. */+ public TempPostingsBaseFormat() {+ super("Temp");+ }++ @Override+ public TempPostingsReaderBase postingsReaderBase(SegmentReadState state) throws IOException {+ return new TempPostingsReader(state.directory, state.fieldInfos, state.segmentInfo, state.context, state.segmentSuffix);+ }++ @Override+ public TempPostingsWriterBase postingsWriterBase(SegmentWriteState state) throws IOException {+ return new TempPostingsWriter(state);+ }+}diff --git a/lucene/core/src/java/org/apache/lucene/codecs/temp/TempPostingsWriter.java b/lucene/core/src/java/org/apache/lucene/codecs/temp/TempPostingsWriter.javaindex 6bc0953c3e3..16168b73cb7 100644--- a/lucene/core/src/java/org/apache/lucene/codecs/temp/TempPostingsWriter.java+++ b/lucene/core/src/java/org/apache/lucene/codecs/temp/TempPostingsWriter.java@@ -200,6 +200,10 @@ public final class TempPostingsWriter extends TempPostingsWriterBase {long skipOffset = -1;long lastPosBlockOffset = -1;int singletonDocID = -1;+ @Override+ public String toString() {+ return super.toString() + " docStartFP=" + docTermStartFP + " posStartFP=" + posTermStartFP + " payStartFP=" + payTermStartFP + " lastPosBlockOffset=" + lastPosBlockOffset + " singletonDocID=" + singletonDocID;+ }}@Overridediff --git a/lucene/core/src/java/org/apache/lucene/store/RAMOutputStream.java b/lucene/core/src/java/org/apache/lucene/store/RAMOutputStream.javaindex 39dccf6a86c..67f39ef3971 100644--- a/lucene/core/src/java/org/apache/lucene/store/RAMOutputStream.java+++ b/lucene/core/src/java/org/apache/lucene/store/RAMOutputStream.java@@ -51,7 +51,7 @@ public class RAMOutputStream extends IndexOutput {}/** Copy the current contents of this buffer to the named output. */- public void writeTo(IndexOutput out) throws IOException {+ public void writeTo(DataOutput out) throws IOException {flush();final long end = file.length;long pos = 0;