Skip to content

Apache Lucene open-source search software

LUCENE-9027: Use SIMD instructions to decode postings. (#973)

Adrien Grand7755cdf03fc2
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txt
index f752a5df4dc..96fbd4cd43b 100644
--- a/lucene/CHANGES.txt
+++ b/lucene/CHANGES.txt
@@ -111,6 +111,8 @@ Optimizations
* LUCENE-8920: The denser arcs of FST now index labels with a bitset in order
to provide near constant time access. (Bruno Roustant, Mike Sokolov via Adrien Grand)
+* LUCENE-9027: Use SIMD instructions to decode postings. (Adrien Grand)
+
Bug Fixes
* LUCENE-9001: Fix race condition in SetOnce. (Przemko Robakowski)
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene50/ForUtil.java b/lucene/backward-codecs/src/java/org/apache/lucene/codecs/lucene50/ForUtil.java
similarity index 100%
rename from lucene/core/src/java/org/apache/lucene/codecs/lucene50/ForUtil.java
rename to lucene/backward-codecs/src/java/org/apache/lucene/codecs/lucene50/ForUtil.java
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene50/Lucene50PostingsFormat.java b/lucene/backward-codecs/src/java/org/apache/lucene/codecs/lucene50/Lucene50PostingsFormat.java
similarity index 94%
rename from lucene/core/src/java/org/apache/lucene/codecs/lucene50/Lucene50PostingsFormat.java
rename to lucene/backward-codecs/src/java/org/apache/lucene/codecs/lucene50/Lucene50PostingsFormat.java
index 960615a5cd7..8a6ac794802 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene50/Lucene50PostingsFormat.java
+++ b/lucene/backward-codecs/src/java/org/apache/lucene/codecs/lucene50/Lucene50PostingsFormat.java
@@ -25,7 +25,6 @@ import org.apache.lucene.codecs.FieldsProducer;
import org.apache.lucene.codecs.MultiLevelSkipListWriter;
import org.apache.lucene.codecs.PostingsFormat;
import org.apache.lucene.codecs.PostingsReaderBase;
-import org.apache.lucene.codecs.PostingsWriterBase;
import org.apache.lucene.codecs.blocktree.BlockTreeTermsReader;
import org.apache.lucene.codecs.blocktree.BlockTreeTermsWriter;
import org.apache.lucene.index.IndexOptions;
@@ -350,7 +349,7 @@ import org.apache.lucene.util.packed.PackedInts;
* @lucene.experimental
*/
-public final class Lucene50PostingsFormat extends PostingsFormat {
+public class Lucene50PostingsFormat extends PostingsFormat {
/**
* Filename extension for document number, frequencies, and skip data.
@@ -386,9 +385,6 @@ public final class Lucene50PostingsFormat extends PostingsFormat {
final static int VERSION_IMPACT_SKIP_DATA = 1;
final static int VERSION_CURRENT = VERSION_IMPACT_SKIP_DATA;
- private final int minTermBlockSize;
- private final int maxTermBlockSize;
-
/**
* Fixed packed block size, number of integers encoded in
* a single packed block.
@@ -400,18 +396,12 @@ public final class Lucene50PostingsFormat extends PostingsFormat {
/** Creates {@code Lucene50PostingsFormat} with default
* settings. */
public Lucene50PostingsFormat() {
- this(BlockTreeTermsWriter.DEFAULT_MIN_BLOCK_SIZE, BlockTreeTermsWriter.DEFAULT_MAX_BLOCK_SIZE, BlockTreeTermsReader.FSTLoadMode.AUTO);
+ this(BlockTreeTermsReader.FSTLoadMode.AUTO);
}
- /** Creates {@code Lucene50PostingsFormat} with custom
- * values for {@code minBlockSize} and {@code
- * maxBlockSize} passed to block terms dictionary.
- * @see BlockTreeTermsWriter#BlockTreeTermsWriter(SegmentWriteState,PostingsWriterBase,int,int) */
- public Lucene50PostingsFormat(int minTermBlockSize, int maxTermBlockSize, BlockTreeTermsReader.FSTLoadMode loadMode) {
+ /** Creates {@code Lucene50PostingsFormat}. */
+ public Lucene50PostingsFormat(BlockTreeTermsReader.FSTLoadMode loadMode) {
super("Lucene50");
- BlockTreeTermsWriter.validateSettings(minTermBlockSize, maxTermBlockSize);
- this.minTermBlockSize = minTermBlockSize;
- this.maxTermBlockSize = maxTermBlockSize;
this.fstLoadMode = loadMode;
}
@@ -422,20 +412,7 @@ public final class Lucene50PostingsFormat extends PostingsFormat {
@Override
public FieldsConsumer fieldsConsumer(SegmentWriteState state) throws IOException {
- PostingsWriterBase postingsWriter = new Lucene50PostingsWriter(state);
- boolean success = false;
- try {
- FieldsConsumer ret = new BlockTreeTermsWriter(state,
- postingsWriter,
- minTermBlockSize,
- maxTermBlockSize);
- success = true;
- return ret;
- } finally {
- if (!success) {
- IOUtils.closeWhileHandlingException(postingsWriter);
- }
- }
+ throw new UnsupportedOperationException("Old formats can't be used for writing");
}
@Override
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene50/Lucene50PostingsReader.java b/lucene/backward-codecs/src/java/org/apache/lucene/codecs/lucene50/Lucene50PostingsReader.java
similarity index 100%
rename from lucene/core/src/java/org/apache/lucene/codecs/lucene50/Lucene50PostingsReader.java
rename to lucene/backward-codecs/src/java/org/apache/lucene/codecs/lucene50/Lucene50PostingsReader.java
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene50/Lucene50ScoreSkipReader.java b/lucene/backward-codecs/src/java/org/apache/lucene/codecs/lucene50/Lucene50ScoreSkipReader.java
similarity index 100%
rename from lucene/core/src/java/org/apache/lucene/codecs/lucene50/Lucene50ScoreSkipReader.java
rename to lucene/backward-codecs/src/java/org/apache/lucene/codecs/lucene50/Lucene50ScoreSkipReader.java
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene50/Lucene50SkipReader.java b/lucene/backward-codecs/src/java/org/apache/lucene/codecs/lucene50/Lucene50SkipReader.java
similarity index 100%
rename from lucene/core/src/java/org/apache/lucene/codecs/lucene50/Lucene50SkipReader.java
rename to lucene/backward-codecs/src/java/org/apache/lucene/codecs/lucene50/Lucene50SkipReader.java
diff --git a/lucene/backward-codecs/src/java/org/apache/lucene/codecs/lucene50/package.html b/lucene/backward-codecs/src/java/org/apache/lucene/codecs/lucene50/package.html
new file mode 100644
index 00000000000..352cef4bf9a
--- /dev/null
+++ b/lucene/backward-codecs/src/java/org/apache/lucene/codecs/lucene50/package.html
@@ -0,0 +1,25 @@
+<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
+<!--
+ 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.
+-->
+<html>
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
+</head>
+<body>
+Lucene 5.0 file format.
+</body>
+</html>
diff --git a/lucene/backward-codecs/src/java/org/apache/lucene/codecs/lucene80/Lucene80Codec.java b/lucene/backward-codecs/src/java/org/apache/lucene/codecs/lucene80/Lucene80Codec.java
new file mode 100644
index 00000000000..bc4e5f360d8
--- /dev/null
+++ b/lucene/backward-codecs/src/java/org/apache/lucene/codecs/lucene80/Lucene80Codec.java
@@ -0,0 +1,131 @@
+/*
+ * 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.
+ */
+package org.apache.lucene.codecs.lucene80;
+
+import org.apache.lucene.codecs.Codec;
+import org.apache.lucene.codecs.CompoundFormat;
+import org.apache.lucene.codecs.DocValuesFormat;
+import org.apache.lucene.codecs.FieldInfosFormat;
+import org.apache.lucene.codecs.LiveDocsFormat;
+import org.apache.lucene.codecs.NormsFormat;
+import org.apache.lucene.codecs.PointsFormat;
+import org.apache.lucene.codecs.PostingsFormat;
+import org.apache.lucene.codecs.SegmentInfoFormat;
+import org.apache.lucene.codecs.StoredFieldsFormat;
+import org.apache.lucene.codecs.TermVectorsFormat;
+import org.apache.lucene.codecs.lucene50.Lucene50CompoundFormat;
+import org.apache.lucene.codecs.lucene50.Lucene50LiveDocsFormat;
+import org.apache.lucene.codecs.lucene50.Lucene50StoredFieldsFormat;
+import org.apache.lucene.codecs.lucene50.Lucene50TermVectorsFormat;
+import org.apache.lucene.codecs.lucene60.Lucene60FieldInfosFormat;
+import org.apache.lucene.codecs.lucene60.Lucene60PointsFormat;
+import org.apache.lucene.codecs.lucene70.Lucene70SegmentInfoFormat;
+import org.apache.lucene.codecs.perfield.PerFieldDocValuesFormat;
+import org.apache.lucene.codecs.perfield.PerFieldPostingsFormat;
+
+/**
+ * Implements the Lucene 8.0 index format.
+ * <p>
+ *
+ * @see org.apache.lucene.codecs.lucene80 package documentation for file format details.
+ *
+ * @lucene.experimental
+ */
+public class Lucene80Codec extends Codec {
+ private final TermVectorsFormat vectorsFormat = new Lucene50TermVectorsFormat();
+ private final FieldInfosFormat fieldInfosFormat = new Lucene60FieldInfosFormat();
+ private final SegmentInfoFormat segmentInfosFormat = new Lucene70SegmentInfoFormat();
+ private final LiveDocsFormat liveDocsFormat = new Lucene50LiveDocsFormat();
+ private final CompoundFormat compoundFormat = new Lucene50CompoundFormat();
+
+ private final PostingsFormat postingsFormat = new PerFieldPostingsFormat() {
+ @Override
+ public PostingsFormat getPostingsFormatForField(String field) {
+ throw new UnsupportedOperationException("Old codecs can't be used for writing");
+ }
+ };
+
+ private final DocValuesFormat docValuesFormat = new PerFieldDocValuesFormat() {
+ @Override
+ public DocValuesFormat getDocValuesFormatForField(String field) {
+ return defaultDVFormat;
+ }
+ };
+ private final DocValuesFormat defaultDVFormat = DocValuesFormat.forName("Lucene80");
+
+ private final StoredFieldsFormat storedFieldsFormat;
+
+ /**
+ * Instantiates a new codec.
+ */
+ public Lucene80Codec() {
+ super("Lucene80");
+ this.storedFieldsFormat = new Lucene50StoredFieldsFormat();
+ }
+
+ @Override
+ public final StoredFieldsFormat storedFieldsFormat() {
+ return storedFieldsFormat;
+ }
+
+ @Override
+ public final TermVectorsFormat termVectorsFormat() {
+ return vectorsFormat;
+ }
+
+ @Override
+ public final PostingsFormat postingsFormat() {
+ return postingsFormat;
+ }
+
+ @Override
+ public final FieldInfosFormat fieldInfosFormat() {
+ return fieldInfosFormat;
+ }
+
+ @Override
+ public final SegmentInfoFormat segmentInfoFormat() {
+ return segmentInfosFormat;
+ }
+
+ @Override
+ public final LiveDocsFormat liveDocsFormat() {
+ return liveDocsFormat;
+ }
+
+ @Override
+ public final CompoundFormat compoundFormat() {
+ return compoundFormat;
+ }
+
+ @Override
+ public final PointsFormat pointsFormat() {
+ return new Lucene60PointsFormat();
+ }
+
+ @Override
+ public final DocValuesFormat docValuesFormat() {
+ return docValuesFormat;
+ }
+
+ private final NormsFormat normsFormat = new Lucene80NormsFormat();
+
+ @Override
+ public final NormsFormat normsFormat() {
+ return normsFormat;
+ }
+}
diff --git a/lucene/backward-codecs/src/java/org/apache/lucene/codecs/lucene80/package.html b/lucene/backward-codecs/src/java/org/apache/lucene/codecs/lucene80/package.html
new file mode 100644
index 00000000000..9d64473d6d5
--- /dev/null
+++ b/lucene/backward-codecs/src/java/org/apache/lucene/codecs/lucene80/package.html
@@ -0,0 +1,25 @@
+<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
+<!--
+ 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.
+-->
+<html>
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
+</head>
+<body>
+Lucene 8.0 file format.
+</body>
+</html>
diff --git a/lucene/backward-codecs/src/resources/META-INF/services/org.apache.lucene.codecs.Codec b/lucene/backward-codecs/src/resources/META-INF/services/org.apache.lucene.codecs.Codec
index 773c168280b..bcd180b102e 100644
--- a/lucene/backward-codecs/src/resources/META-INF/services/org.apache.lucene.codecs.Codec
+++ b/lucene/backward-codecs/src/resources/META-INF/services/org.apache.lucene.codecs.Codec
@@ -14,3 +14,4 @@
# limitations under the License.
org.apache.lucene.codecs.lucene70.Lucene70Codec
+org.apache.lucene.codecs.lucene80.Lucene80Codec
diff --git a/lucene/backward-codecs/src/resources/META-INF/services/org.apache.lucene.codecs.PostingsFormat b/lucene/backward-codecs/src/resources/META-INF/services/org.apache.lucene.codecs.PostingsFormat
index 4a812de77e5..f7390e28cff 100644
--- a/lucene/backward-codecs/src/resources/META-INF/services/org.apache.lucene.codecs.PostingsFormat
+++ b/lucene/backward-codecs/src/resources/META-INF/services/org.apache.lucene.codecs.PostingsFormat
@@ -13,3 +13,4 @@
# See the License for the specific language governing permissions and
# limitations under the License.
+org.apache.lucene.codecs.lucene50.Lucene50PostingsFormat
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene50/Lucene50PostingsWriter.java b/lucene/backward-codecs/src/test/org/apache/lucene/codecs/lucene50/Lucene50PostingsWriter.java
similarity index 100%
rename from lucene/core/src/java/org/apache/lucene/codecs/lucene50/Lucene50PostingsWriter.java
rename to lucene/backward-codecs/src/test/org/apache/lucene/codecs/lucene50/Lucene50PostingsWriter.java
diff --git a/lucene/backward-codecs/src/test/org/apache/lucene/codecs/lucene50/Lucene50RWPostingsFormat.java b/lucene/backward-codecs/src/test/org/apache/lucene/codecs/lucene50/Lucene50RWPostingsFormat.java
new file mode 100644
index 00000000000..d5e7d90eddf
--- /dev/null
+++ b/lucene/backward-codecs/src/test/org/apache/lucene/codecs/lucene50/Lucene50RWPostingsFormat.java
@@ -0,0 +1,47 @@
+/*
+ * 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.
+ */
+package org.apache.lucene.codecs.lucene50;
+
+import java.io.IOException;
+
+import org.apache.lucene.codecs.FieldsConsumer;
+import org.apache.lucene.codecs.PostingsWriterBase;
+import org.apache.lucene.codecs.blocktree.BlockTreeTermsWriter;
+import org.apache.lucene.index.SegmentWriteState;
+import org.apache.lucene.util.IOUtils;
+
+public class Lucene50RWPostingsFormat extends Lucene50PostingsFormat {
+
+ @Override
+ public FieldsConsumer fieldsConsumer(SegmentWriteState state) throws IOException {
+ PostingsWriterBase postingsWriter = new Lucene50PostingsWriter(state);
+ boolean success = false;
+ try {
+ FieldsConsumer ret = new BlockTreeTermsWriter(state,
+ postingsWriter,
+ BlockTreeTermsWriter.DEFAULT_MIN_BLOCK_SIZE,
+ BlockTreeTermsWriter.DEFAULT_MAX_BLOCK_SIZE);
+ success = true;
+ return ret;
+ } finally {
+ if (!success) {
+ IOUtils.closeWhileHandlingException(postingsWriter);
+ }
+ }
+ }
+
+}
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene50/Lucene50SkipWriter.java b/lucene/backward-codecs/src/test/org/apache/lucene/codecs/lucene50/Lucene50SkipWriter.java
similarity index 100%
rename from lucene/core/src/java/org/apache/lucene/codecs/lucene50/Lucene50SkipWriter.java
rename to lucene/backward-codecs/src/test/org/apache/lucene/codecs/lucene50/Lucene50SkipWriter.java
diff --git a/lucene/core/src/test/org/apache/lucene/codecs/lucene50/TestBlockPostingsFormat.java b/lucene/backward-codecs/src/test/org/apache/lucene/codecs/lucene50/TestBlockPostingsFormat.java
similarity index 96%
rename from lucene/core/src/test/org/apache/lucene/codecs/lucene50/TestBlockPostingsFormat.java
rename to lucene/backward-codecs/src/test/org/apache/lucene/codecs/lucene50/TestBlockPostingsFormat.java
index 25f06e2b154..690eba8aeeb 100644
--- a/lucene/core/src/test/org/apache/lucene/codecs/lucene50/TestBlockPostingsFormat.java
+++ b/lucene/backward-codecs/src/test/org/apache/lucene/codecs/lucene50/TestBlockPostingsFormat.java
@@ -55,7 +55,7 @@ import org.apache.lucene.util.TestUtil;
* Tests BlockPostingsFormat
*/
public class TestBlockPostingsFormat extends BasePostingsFormatTestCase {
- private final Codec codec = TestUtil.alwaysPostingsFormat(new Lucene50PostingsFormat());
+ private final Codec codec = TestUtil.alwaysPostingsFormat(new Lucene50RWPostingsFormat());
@Override
protected Codec getCodec() {
@@ -282,20 +282,6 @@ public class TestBlockPostingsFormat extends BasePostingsFormatTestCase {
d.close();
}
- private void shouldFail(int minItemsInBlock, int maxItemsInBlock) {
- expectThrows(IllegalArgumentException.class, () -> {
- new Lucene50PostingsFormat(minItemsInBlock, maxItemsInBlock, BlockTreeTermsReader.FSTLoadMode.AUTO);
- });
- }
-
- public void testInvalidBlockSizes() throws Exception {
- shouldFail(0, 0);
- shouldFail(10, 8);
- shouldFail(-1, 10);
- shouldFail(10, -1);
- shouldFail(10, 12);
- }
-
public void testImpactSerialization() throws IOException {
// omit norms and omit freqs
doTestImpactSerialization(Collections.singletonList(new Impact(1, 1L)));
diff --git a/lucene/core/src/test/org/apache/lucene/codecs/lucene50/TestBlockPostingsFormat2.java b/lucene/backward-codecs/src/test/org/apache/lucene/codecs/lucene50/TestBlockPostingsFormat2.java
similarity index 96%
rename from lucene/core/src/test/org/apache/lucene/codecs/lucene50/TestBlockPostingsFormat2.java
rename to lucene/backward-codecs/src/test/org/apache/lucene/codecs/lucene50/TestBlockPostingsFormat2.java
index b59c587da79..74fa2ff1406 100644
--- a/lucene/core/src/test/org/apache/lucene/codecs/lucene50/TestBlockPostingsFormat2.java
+++ b/lucene/backward-codecs/src/test/org/apache/lucene/codecs/lucene50/TestBlockPostingsFormat2.java
@@ -45,7 +45,7 @@ public class TestBlockPostingsFormat2 extends LuceneTestCase {
super.setUp();
dir = newFSDirectory(createTempDir("testDFBlockSize"));
IndexWriterConfig iwc = newIndexWriterConfig(new MockAnalyzer(random()));
- iwc.setCodec(TestUtil.alwaysPostingsFormat(new Lucene50PostingsFormat()));
+ iwc.setCodec(TestUtil.alwaysPostingsFormat(new Lucene50RWPostingsFormat()));
iw = new RandomIndexWriter(random(), dir, iwc);
iw.setDoRandomForceMerge(false); // we will ourselves
}
@@ -55,7 +55,7 @@ public class TestBlockPostingsFormat2 extends LuceneTestCase {
iw.close();
TestUtil.checkIndex(dir); // for some extra coverage, checkIndex before we forceMerge
IndexWriterConfig iwc = newIndexWriterConfig(new MockAnalyzer(random()));
- iwc.setCodec(TestUtil.alwaysPostingsFormat(new Lucene50PostingsFormat()));
+ iwc.setCodec(TestUtil.alwaysPostingsFormat(new Lucene50RWPostingsFormat()));
iwc.setOpenMode(OpenMode.APPEND);
IndexWriter iw = new IndexWriter(dir, iwc);
iw.forceMerge(1);
diff --git a/lucene/core/src/test/org/apache/lucene/codecs/lucene50/TestBlockPostingsFormat3.java b/lucene/backward-codecs/src/test/org/apache/lucene/codecs/lucene50/TestBlockPostingsFormat3.java
similarity index 96%
rename from lucene/core/src/test/org/apache/lucene/codecs/lucene50/TestBlockPostingsFormat3.java
rename to lucene/backward-codecs/src/test/org/apache/lucene/codecs/lucene50/TestBlockPostingsFormat3.java
index 3b99ee17105..9a275602c8d 100644
--- a/lucene/core/src/test/org/apache/lucene/codecs/lucene50/TestBlockPostingsFormat3.java
+++ b/lucene/backward-codecs/src/test/org/apache/lucene/codecs/lucene50/TestBlockPostingsFormat3.java
@@ -33,23 +33,21 @@ import org.apache.lucene.document.Field;
import org.apache.lucene.document.FieldType;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
-import org.apache.lucene.index.PostingsEnum;
import org.apache.lucene.index.IndexOptions;
import org.apache.lucene.index.IndexWriter;
-import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.index.IndexWriterConfig;
+import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.index.LeafReader;
import org.apache.lucene.index.LeafReaderContext;
+import org.apache.lucene.index.PostingsEnum;
import org.apache.lucene.index.RandomIndexWriter;
import org.apache.lucene.index.Terms;
-import org.apache.lucene.index.TermsEnum.SeekStatus;
import org.apache.lucene.index.TermsEnum;
+import org.apache.lucene.index.TermsEnum.SeekStatus;
import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.store.Directory;
-import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.English;
-import org.apache.lucene.util.FixedBitSet;
import org.apache.lucene.util.LuceneTestCase;
import org.apache.lucene.util.TestUtil;
import org.apache.lucene.util.automaton.AutomatonTestUtil;
@@ -82,7 +80,7 @@ public class TestBlockPostingsFormat3 extends LuceneTestCase {
}
};
IndexWriterConfig iwc = newIndexWriterConfig(analyzer);
- iwc.setCodec(TestUtil.alwaysPostingsFormat(new Lucene50PostingsFormat()));
+ iwc.setCodec(TestUtil.alwaysPostingsFormat(new Lucene50RWPostingsFormat()));
// TODO we could actually add more fields implemented with different PFs
// or, just put this test into the usual rotation?
RandomIndexWriter iw = new RandomIndexWriter(random(), dir, iwc);
@@ -137,7 +135,7 @@ public class TestBlockPostingsFormat3 extends LuceneTestCase {
verify(dir);
TestUtil.checkIndex(dir); // for some extra coverage, checkIndex before we forceMerge
iwc = newIndexWriterConfig(analyzer);
- iwc.setCodec(TestUtil.alwaysPostingsFormat(new Lucene50PostingsFormat()));
+ iwc.setCodec(TestUtil.alwaysPostingsFormat(new Lucene50RWPostingsFormat()));
iwc.setOpenMode(OpenMode.APPEND);
IndexWriter iw2 = new IndexWriter(dir, iwc);
iw2.forceMerge(1);
@@ -461,27 +459,5 @@ public class TestBlockPostingsFormat3 extends LuceneTestCase {
}
}
}
-
- private static class RandomBits implements Bits {
- FixedBitSet bits;
-
- RandomBits(int maxDoc, double pctLive, Random random) {
- bits = new FixedBitSet(maxDoc);
- for (int i = 0; i < maxDoc; i++) {
- if (random.nextDouble() <= pctLive) {
- bits.set(i);
- }
- }
- }
-
- @Override
- public boolean get(int index) {
- return bits.get(index);
- }
- @Override
- public int length() {
- return bits.length();
- }
- }
}
diff --git a/lucene/core/src/test/org/apache/lucene/codecs/lucene50/TestForUtil.java b/lucene/backward-codecs/src/test/org/apache/lucene/codecs/lucene50/TestForUtil.java
similarity index 100%
rename from lucene/core/src/test/org/apache/lucene/codecs/lucene50/TestForUtil.java
rename to lucene/backward-codecs/src/test/org/apache/lucene/codecs/lucene50/TestForUtil.java
diff --git a/lucene/backward-codecs/src/test/org/apache/lucene/codecs/lucene70/TestLucene70NormsFormat.java b/lucene/backward-codecs/src/test/org/apache/lucene/codecs/lucene70/TestLucene70NormsFormat.java
index f7d77142db0..63925e0ec97 100644
--- a/lucene/backward-codecs/src/test/org/apache/lucene/codecs/lucene70/TestLucene70NormsFormat.java
+++ b/lucene/backward-codecs/src/test/org/apache/lucene/codecs/lucene70/TestLucene70NormsFormat.java
@@ -18,14 +18,14 @@ package org.apache.lucene.codecs.lucene70;
import org.apache.lucene.codecs.Codec;
-import org.apache.lucene.codecs.lucene80.Lucene80Codec;
+import org.apache.lucene.codecs.lucene84.Lucene84Codec;
import org.apache.lucene.index.BaseNormsFormatTestCase;
/**
* Tests Lucene70NormsFormat
*/
public class TestLucene70NormsFormat extends BaseNormsFormatTestCase {
- private final Codec codec = new Lucene80Codec();
+ private final Codec codec = new Lucene84Codec();
@Override
protected Codec getCodec() {
diff --git a/lucene/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/CreateIndexTask.java b/lucene/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/CreateIndexTask.java
index 30076e93699..55103284d43 100644
--- a/lucene/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/CreateIndexTask.java
+++ b/lucene/benchmark/src/java/org/apache/lucene/benchmark/byTask/tasks/CreateIndexTask.java
@@ -29,13 +29,13 @@ import org.apache.lucene.benchmark.byTask.PerfRunData;
import org.apache.lucene.benchmark.byTask.utils.Config;
import org.apache.lucene.codecs.Codec;
import org.apache.lucene.codecs.PostingsFormat;
-import org.apache.lucene.codecs.lucene80.Lucene80Codec;
+import org.apache.lucene.codecs.lucene84.Lucene84Codec;
import org.apache.lucene.index.ConcurrentMergeScheduler;
import org.apache.lucene.index.IndexCommit;
import org.apache.lucene.index.IndexDeletionPolicy;
import org.apache.lucene.index.IndexWriter;
-import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.index.IndexWriterConfig;
+import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.index.LogMergePolicy;
import org.apache.lucene.index.MergePolicy;
import org.apache.lucene.index.MergeScheduler;
@@ -138,7 +138,7 @@ public class CreateIndexTask extends PerfTask {
if (defaultCodec == null && postingsFormat != null) {
try {
final PostingsFormat postingsFormatChosen = PostingsFormat.forName(postingsFormat);
- iwConf.setCodec(new Lucene80Codec() {
+ iwConf.setCodec(new Lucene84Codec() {
@Override
public PostingsFormat getPostingsFormatForField(String field) {
return postingsFormatChosen;
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/BlockTreeOrdsPostingsFormat.java b/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/BlockTreeOrdsPostingsFormat.java
index a93622cddcb..66493fe7f7e 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/BlockTreeOrdsPostingsFormat.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/BlockTreeOrdsPostingsFormat.java
@@ -25,13 +25,13 @@ import org.apache.lucene.codecs.PostingsFormat;
import org.apache.lucene.codecs.PostingsReaderBase;
import org.apache.lucene.codecs.PostingsWriterBase;
import org.apache.lucene.codecs.blocktree.BlockTreeTermsWriter;
-import org.apache.lucene.codecs.lucene50.Lucene50PostingsReader;
-import org.apache.lucene.codecs.lucene50.Lucene50PostingsWriter;
+import org.apache.lucene.codecs.lucene84.Lucene84PostingsReader;
+import org.apache.lucene.codecs.lucene84.Lucene84PostingsWriter;
import org.apache.lucene.index.SegmentReadState;
import org.apache.lucene.index.SegmentWriteState;
import org.apache.lucene.util.IOUtils;
-/** Uses {@link OrdsBlockTreeTermsWriter} with {@link Lucene50PostingsWriter}. */
+/** Uses {@link OrdsBlockTreeTermsWriter} with {@link Lucene84PostingsWriter}. */
public class BlockTreeOrdsPostingsFormat extends PostingsFormat {
private final int minTermBlockSize;
@@ -68,7 +68,7 @@ public class BlockTreeOrdsPostingsFormat extends PostingsFormat {
@Override
public FieldsConsumer fieldsConsumer(SegmentWriteState state) throws IOException {
- PostingsWriterBase postingsWriter = new Lucene50PostingsWriter(state);
+ PostingsWriterBase postingsWriter = new Lucene84PostingsWriter(state);
boolean success = false;
try {
@@ -87,7 +87,7 @@ public class BlockTreeOrdsPostingsFormat extends PostingsFormat {
@Override
public FieldsProducer fieldsProducer(SegmentReadState state) throws IOException {
- PostingsReaderBase postingsReader = new Lucene50PostingsReader(state);
+ PostingsReaderBase postingsReader = new Lucene84PostingsReader(state);
boolean success = false;
try {
FieldsProducer ret = new OrdsBlockTreeTermsReader(postingsReader, state);
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/memory/DirectPostingsFormat.java b/lucene/codecs/src/java/org/apache/lucene/codecs/memory/DirectPostingsFormat.java
index d9590e136ad..0503e034c3d 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/memory/DirectPostingsFormat.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/memory/DirectPostingsFormat.java
@@ -26,7 +26,7 @@ import java.util.TreeMap;
import org.apache.lucene.codecs.FieldsConsumer;
import org.apache.lucene.codecs.FieldsProducer;
import org.apache.lucene.codecs.PostingsFormat;
-import org.apache.lucene.codecs.lucene50.Lucene50PostingsFormat;
+import org.apache.lucene.codecs.lucene84.Lucene84PostingsFormat;
import org.apache.lucene.index.BaseTermsEnum;
import org.apache.lucene.index.FieldInfo;
import org.apache.lucene.index.Fields;
@@ -55,7 +55,7 @@ import org.apache.lucene.util.automaton.Transition;
// - build depth-N prefix hash?
// - or: longer dense skip lists than just next byte?
-/** Wraps {@link Lucene50PostingsFormat} format for on-disk
+/** Wraps {@link Lucene84PostingsFormat} format for on-disk
* storage, but then at read time loads and stores all
* terms and postings directly in RAM as byte[], int[].
*
@@ -103,12 +103,12 @@ public final class DirectPostingsFormat extends PostingsFormat {
@Override
public FieldsConsumer fieldsConsumer(SegmentWriteState state) throws IOException {
- return PostingsFormat.forName("Lucene50").fieldsConsumer(state);
+ return PostingsFormat.forName("Lucene84").fieldsConsumer(state);
}
@Override
public FieldsProducer fieldsProducer(SegmentReadState state) throws IOException {
- FieldsProducer postings = PostingsFormat.forName("Lucene50").fieldsProducer(state);
+ FieldsProducer postings = PostingsFormat.forName("Lucene84").fieldsProducer(state);
if (state.context.context != IOContext.Context.MERGE) {
FieldsProducer loadedPostings;
try {
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/memory/FSTOrdPostingsFormat.java b/lucene/codecs/src/java/org/apache/lucene/codecs/memory/FSTOrdPostingsFormat.java
index e19a4706820..0ce12178a90 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/memory/FSTOrdPostingsFormat.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/memory/FSTOrdPostingsFormat.java
@@ -25,8 +25,8 @@ import org.apache.lucene.codecs.FieldsProducer;
import org.apache.lucene.codecs.PostingsFormat;
import org.apache.lucene.codecs.PostingsReaderBase;
import org.apache.lucene.codecs.PostingsWriterBase;
-import org.apache.lucene.codecs.lucene50.Lucene50PostingsReader;
-import org.apache.lucene.codecs.lucene50.Lucene50PostingsWriter;
+import org.apache.lucene.codecs.lucene84.Lucene84PostingsReader;
+import org.apache.lucene.codecs.lucene84.Lucene84PostingsWriter;
import org.apache.lucene.index.SegmentReadState;
import org.apache.lucene.index.SegmentWriteState;
import org.apache.lucene.util.IOUtils;
@@ -47,7 +47,7 @@ public final class FSTOrdPostingsFormat extends PostingsFormat {
@Override
public FieldsConsumer fieldsConsumer(SegmentWriteState state) throws IOException {
- PostingsWriterBase postingsWriter = new Lucene50PostingsWriter(state);
+ PostingsWriterBase postingsWriter = new Lucene84PostingsWriter(state);
boolean success = false;
try {
@@ -63,7 +63,7 @@ public final class FSTOrdPostingsFormat extends PostingsFormat {
@Override
public FieldsProducer fieldsProducer(SegmentReadState state) throws IOException {
- PostingsReaderBase postingsReader = new Lucene50PostingsReader(state);
+ PostingsReaderBase postingsReader = new Lucene84PostingsReader(state);
boolean success = false;
try {
FieldsProducer ret = new FSTOrdTermsReader(state, postingsReader);
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/memory/FSTPostingsFormat.java b/lucene/codecs/src/java/org/apache/lucene/codecs/memory/FSTPostingsFormat.java
index 006554dff2a..97a799604e0 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/memory/FSTPostingsFormat.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/memory/FSTPostingsFormat.java
@@ -25,8 +25,8 @@ import org.apache.lucene.codecs.FieldsProducer;
import org.apache.lucene.codecs.PostingsFormat;
import org.apache.lucene.codecs.PostingsReaderBase;
import org.apache.lucene.codecs.PostingsWriterBase;
-import org.apache.lucene.codecs.lucene50.Lucene50PostingsReader;
-import org.apache.lucene.codecs.lucene50.Lucene50PostingsWriter;
+import org.apache.lucene.codecs.lucene84.Lucene84PostingsReader;
+import org.apache.lucene.codecs.lucene84.Lucene84PostingsWriter;
import org.apache.lucene.index.SegmentReadState;
import org.apache.lucene.index.SegmentWriteState;
import org.apache.lucene.util.IOUtils;
@@ -47,7 +47,7 @@ public final class FSTPostingsFormat extends PostingsFormat {
@Override
public FieldsConsumer fieldsConsumer(SegmentWriteState state) throws IOException {
- PostingsWriterBase postingsWriter = new Lucene50PostingsWriter(state);
+ PostingsWriterBase postingsWriter = new Lucene84PostingsWriter(state);
boolean success = false;
try {
@@ -63,7 +63,7 @@ public final class FSTPostingsFormat extends PostingsFormat {
@Override
public FieldsProducer fieldsProducer(SegmentReadState state) throws IOException {
- PostingsReaderBase postingsReader = new Lucene50PostingsReader(state);
+ PostingsReaderBase postingsReader = new Lucene84PostingsReader(state);
boolean success = false;
try {
FieldsProducer ret = new FSTTermsReader(state, postingsReader);
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/uniformsplit/DeltaBaseTermStateSerializer.java b/lucene/codecs/src/java/org/apache/lucene/codecs/uniformsplit/DeltaBaseTermStateSerializer.java
index f9e0c31dfeb..52c7465d093 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/uniformsplit/DeltaBaseTermStateSerializer.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/uniformsplit/DeltaBaseTermStateSerializer.java
@@ -17,25 +17,25 @@
package org.apache.lucene.codecs.uniformsplit;
+import static org.apache.lucene.codecs.lucene84.Lucene84PostingsFormat.BLOCK_SIZE;
+
import java.io.IOException;
import org.apache.lucene.codecs.BlockTermState;
-import org.apache.lucene.codecs.lucene50.Lucene50PostingsReader;
-import org.apache.lucene.codecs.lucene50.Lucene50PostingsWriter;
+import org.apache.lucene.codecs.lucene84.Lucene84PostingsFormat.IntBlockTermState;
+import org.apache.lucene.codecs.lucene84.Lucene84PostingsReader;
+import org.apache.lucene.codecs.lucene84.Lucene84PostingsWriter;
import org.apache.lucene.index.FieldInfo;
import org.apache.lucene.index.IndexOptions;
import org.apache.lucene.index.TermState;
import org.apache.lucene.store.DataInput;
import org.apache.lucene.store.DataOutput;
-import org.apache.lucene.codecs.lucene50.Lucene50PostingsFormat.IntBlockTermState;
import org.apache.lucene.util.Accountable;
import org.apache.lucene.util.RamUsageEstimator;
-import static org.apache.lucene.codecs.lucene50.Lucene50PostingsFormat.BLOCK_SIZE;
-
/**
* {@link TermState} serializer which encodes each file pointer as a delta relative
- * to a base file pointer. It differs from {@link Lucene50PostingsWriter#encodeTerm}
+ * to a base file pointer. It differs from {@link Lucene84PostingsWriter#encodeTerm}
* which encodes each file pointer as a delta relative to the previous file pointer.
* <p>
* It automatically sets the base file pointer to the first valid file pointer for
@@ -94,7 +94,7 @@ public class DeltaBaseTermStateSerializer implements Accountable {
/**
* Writes a {@link BlockTermState} to the provided {@link DataOutput}.
* <p>
- * Simpler variant of {@link Lucene50PostingsWriter#encodeTerm(long[], DataOutput, FieldInfo, BlockTermState, boolean)}.
+ * Simpler variant of {@link Lucene84PostingsWriter#encodeTerm(long[], DataOutput, FieldInfo, BlockTermState, boolean)}.
*/
public void writeTermState(DataOutput termStatesOutput, FieldInfo fieldInfo, BlockTermState termState) throws IOException {
IndexOptions indexOptions = fieldInfo.getIndexOptions();
@@ -143,7 +143,7 @@ public class DeltaBaseTermStateSerializer implements Accountable {
/**
* Reads a {@link BlockTermState} from the provided {@link DataInput}.
* <p>
- * Simpler variant of {@link Lucene50PostingsReader#decodeTerm(long[], DataInput, FieldInfo, BlockTermState, boolean)}.
+ * Simpler variant of {@link Lucene84PostingsReader#decodeTerm(long[], DataInput, FieldInfo, BlockTermState, boolean)}.
*
* @param reuse {@link BlockTermState} to reuse; or null to create a new one.
*/
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/uniformsplit/UniformSplitPostingsFormat.java b/lucene/codecs/src/java/org/apache/lucene/codecs/uniformsplit/UniformSplitPostingsFormat.java
index ce2e06817c0..f9d147a0814 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/uniformsplit/UniformSplitPostingsFormat.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/uniformsplit/UniformSplitPostingsFormat.java
@@ -24,8 +24,8 @@ import org.apache.lucene.codecs.FieldsProducer;
import org.apache.lucene.codecs.PostingsFormat;
import org.apache.lucene.codecs.PostingsReaderBase;
import org.apache.lucene.codecs.PostingsWriterBase;
-import org.apache.lucene.codecs.lucene50.Lucene50PostingsReader;
-import org.apache.lucene.codecs.lucene50.Lucene50PostingsWriter;
+import org.apache.lucene.codecs.lucene84.Lucene84PostingsReader;
+import org.apache.lucene.codecs.lucene84.Lucene84PostingsWriter;
import org.apache.lucene.index.SegmentReadState;
import org.apache.lucene.index.SegmentWriteState;
import org.apache.lucene.util.IOUtils;
@@ -90,7 +90,7 @@ public class UniformSplitPostingsFormat extends PostingsFormat {
@Override
public FieldsConsumer fieldsConsumer(SegmentWriteState state) throws IOException {
- PostingsWriterBase postingsWriter = new Lucene50PostingsWriter(state);
+ PostingsWriterBase postingsWriter = new Lucene84PostingsWriter(state);
boolean success = false;
try {
FieldsConsumer termsWriter = createUniformSplitTermsWriter(postingsWriter, state, targetNumBlockLines, deltaNumLines, blockEncoder);
@@ -105,7 +105,7 @@ public class UniformSplitPostingsFormat extends PostingsFormat {
@Override
public FieldsProducer fieldsProducer(SegmentReadState state) throws IOException {
- PostingsReaderBase postingsReader = new Lucene50PostingsReader(state);
+ PostingsReaderBase postingsReader = new Lucene84PostingsReader(state);
boolean success = false;
try {
FieldsProducer termsReader = createUniformSplitTermsReader(postingsReader, state, blockDecoder);
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/uniformsplit/package-info.java b/lucene/codecs/src/java/org/apache/lucene/codecs/uniformsplit/package-info.java
index 1ca0c8756c3..d4c65e64788 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/uniformsplit/package-info.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/uniformsplit/package-info.java
@@ -27,7 +27,7 @@
* <li>Efficient to seek terms ({@link org.apache.lucene.search.TermQuery}, {@link org.apache.lucene.search.PhraseQuery})</li>
* <li>Quite efficient for {@link org.apache.lucene.search.PrefixQuery}</li>
* <li>Not efficient for spell-check and {@link org.apache.lucene.search.FuzzyQuery}, in this case prefer
- * {@link org.apache.lucene.codecs.lucene50.Lucene50PostingsFormat}</li>
+ * {@link org.apache.lucene.codecs.lucene84.Lucene84PostingsFormat}</li>
* </ul>
*/
package org.apache.lucene.codecs.uniformsplit;
diff --git a/lucene/codecs/src/test/org/apache/lucene/codecs/lucene50/MockTermStateFactory.java b/lucene/codecs/src/test/org/apache/lucene/codecs/lucene84/MockTermStateFactory.java
similarity index 75%
rename from lucene/codecs/src/test/org/apache/lucene/codecs/lucene50/MockTermStateFactory.java
rename to lucene/codecs/src/test/org/apache/lucene/codecs/lucene84/MockTermStateFactory.java
index 37aed27efff..f090ea46f25 100644
--- a/lucene/codecs/src/test/org/apache/lucene/codecs/lucene50/MockTermStateFactory.java
+++ b/lucene/codecs/src/test/org/apache/lucene/codecs/lucene84/MockTermStateFactory.java
@@ -15,17 +15,17 @@
* limitations under the License.
*/
-package org.apache.lucene.codecs.lucene50;
+package org.apache.lucene.codecs.lucene84;
/**
- * Test utility class to create mock {@link Lucene50PostingsFormat.IntBlockTermState}.
+ * Test utility class to create mock {@link Lucene84PostingsFormat.IntBlockTermState}.
*/
public class MockTermStateFactory {
/**
- * Creates an empty {@link Lucene50PostingsFormat.IntBlockTermState}.
+ * Creates an empty {@link Lucene84PostingsFormat.IntBlockTermState}.
*/
- public static Lucene50PostingsFormat.IntBlockTermState create() {
- return new Lucene50PostingsFormat.IntBlockTermState();
+ public static Lucene84PostingsFormat.IntBlockTermState create() {
+ return new Lucene84PostingsFormat.IntBlockTermState();
}
}
\ No newline at end of file
diff --git a/lucene/codecs/src/test/org/apache/lucene/codecs/uniformsplit/TestBlockWriter.java b/lucene/codecs/src/test/org/apache/lucene/codecs/uniformsplit/TestBlockWriter.java
index 65aac357555..e3e1d06f7f6 100644
--- a/lucene/codecs/src/test/org/apache/lucene/codecs/uniformsplit/TestBlockWriter.java
+++ b/lucene/codecs/src/test/org/apache/lucene/codecs/uniformsplit/TestBlockWriter.java
@@ -20,7 +20,7 @@ package org.apache.lucene.codecs.uniformsplit;
import java.io.IOException;
import java.util.Collections;
-import org.apache.lucene.codecs.lucene50.MockTermStateFactory;
+import org.apache.lucene.codecs.lucene84.MockTermStateFactory;
import org.apache.lucene.index.DocValuesType;
import org.apache.lucene.index.FieldInfo;
import org.apache.lucene.index.IndexOptions;
diff --git a/lucene/codecs/src/test/org/apache/lucene/codecs/uniformsplit/sharedterms/STBlockReaderTest.java b/lucene/codecs/src/test/org/apache/lucene/codecs/uniformsplit/sharedterms/STBlockReaderTest.java
index ef08799ef60..f4111a45f70 100644
--- a/lucene/codecs/src/test/org/apache/lucene/codecs/uniformsplit/sharedterms/STBlockReaderTest.java
+++ b/lucene/codecs/src/test/org/apache/lucene/codecs/uniformsplit/sharedterms/STBlockReaderTest.java
@@ -29,7 +29,7 @@ import java.util.function.Supplier;
import org.apache.lucene.codecs.BlockTermState;
import org.apache.lucene.codecs.PostingsReaderBase;
-import org.apache.lucene.codecs.lucene50.MockTermStateFactory;
+import org.apache.lucene.codecs.lucene84.MockTermStateFactory;
import org.apache.lucene.codecs.uniformsplit.BlockHeader;
import org.apache.lucene.codecs.uniformsplit.BlockLine;
import org.apache.lucene.codecs.uniformsplit.FSTDictionary;
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/Codec.java b/lucene/core/src/java/org/apache/lucene/codecs/Codec.java
index 4aa22a6b467..07797c6f95d 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/Codec.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/Codec.java
@@ -57,7 +57,7 @@ public abstract class Codec implements NamedSPILoader.NamedSPI {
}
// TODO: should we use this, or maybe a system property is better?
- static Codec defaultCodec = LOADER.lookup("Lucene80");
+ static Codec defaultCodec = LOADER.lookup("Lucene84");
}
private final String name;
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene80/package-info.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene80/package-info.java
index 82b5689638c..c2c31534a79 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene80/package-info.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene80/package-info.java
@@ -16,396 +16,8 @@
*/
/**
- * Lucene 8.0 file format.
- *
- * <h1>Apache Lucene - Index File Formats</h1>
- * <div>
- * <ul>
- * <li><a href="#Introduction">Introduction</a></li>
- * <li><a href="#Definitions">Definitions</a>
- * <ul>
- * <li><a href="#Inverted_Indexing">Inverted Indexing</a></li>
- * <li><a href="#Types_of_Fields">Types of Fields</a></li>
- * <li><a href="#Segments">Segments</a></li>
- * <li><a href="#Document_Numbers">Document Numbers</a></li>
- * </ul>
- * </li>
- * <li><a href="#Overview">Index Structure Overview</a></li>
- * <li><a href="#File_Naming">File Naming</a></li>
- * <li><a href="#file-names">Summary of File Extensions</a>
- * <ul>
- * <li><a href="#Lock_File">Lock File</a></li>
- * <li><a href="#History">History</a></li>
- * <li><a href="#Limitations">Limitations</a></li>
- * </ul>
- * </li>
- * </ul>
- * </div>
- * <a name="Introduction"></a>
- * <h2>Introduction</h2>
- * <div>
- * <p>This document defines the index file formats used in this version of Lucene.
- * If you are using a different version of Lucene, please consult the copy of
- * <code>docs/</code> that was distributed with
- * the version you are using.</p>
- * <p>This document attempts to provide a high-level definition of the Apache
- * Lucene file formats.</p>
- * </div>
- * <a name="Definitions"></a>
- * <h2>Definitions</h2>
- * <div>
- * <p>The fundamental concepts in Lucene are index, document, field and term.</p>
- * <p>An index contains a sequence of documents.</p>
- * <ul>
- * <li>A document is a sequence of fields.</li>
- * <li>A field is a named sequence of terms.</li>
- * <li>A term is a sequence of bytes.</li>
- * </ul>
- * <p>The same sequence of bytes in two different fields is considered a different
- * term. Thus terms are represented as a pair: the string naming the field, and the
- * bytes within the field.</p>
- * <a name="Inverted_Indexing"></a>
- * <h3>Inverted Indexing</h3>
- * <p>The index stores statistics about terms in order to make term-based search
- * more efficient. Lucene's index falls into the family of indexes known as an
- * <i>inverted index.</i> This is because it can list, for a term, the documents
- * that contain it. This is the inverse of the natural relationship, in which
- * documents list terms.</p>
- * <a name="Types_of_Fields"></a>
- * <h3>Types of Fields</h3>
- * <p>In Lucene, fields may be <i>stored</i>, in which case their text is stored
- * in the index literally, in a non-inverted manner. Fields that are inverted are
- * called <i>indexed</i>. A field may be both stored and indexed.</p>
- * <p>The text of a field may be <i>tokenized</i> into terms to be indexed, or the
- * text of a field may be used literally as a term to be indexed. Most fields are
- * tokenized, but sometimes it is useful for certain identifier fields to be
- * indexed literally.</p>
- * <p>See the {@link org.apache.lucene.document.Field Field}
- * java docs for more information on Fields.</p>
- * <a name="Segments"></a>
- * <h3>Segments</h3>
- * <p>Lucene indexes may be composed of multiple sub-indexes, or <i>segments</i>.
- * Each segment is a fully independent index, which could be searched separately.
- * Indexes evolve by:</p>
- * <ol>
- * <li>Creating new segments for newly added documents.</li>
- * <li>Merging existing segments.</li>
- * </ol>
- * <p>Searches may involve multiple segments and/or multiple indexes, each index
- * potentially composed of a set of segments.</p>
- * <a name="Document_Numbers"></a>
- * <h3>Document Numbers</h3>
- * <p>Internally, Lucene refers to documents by an integer <i>document number</i>.
- * The first document added to an index is numbered zero, and each subsequent
- * document added gets a number one greater than the previous.</p>
- * <p>Note that a document's number may change, so caution should be taken when
- * storing these numbers outside of Lucene. In particular, numbers may change in
- * the following situations:</p>
- * <ul>
- * <li>
- * <p>The numbers stored in each segment are unique only within the segment, and
- * must be converted before they can be used in a larger context. The standard
- * technique is to allocate each segment a range of values, based on the range of
- * numbers used in that segment. To convert a document number from a segment to an
- * external value, the segment's <i>base</i> document number is added. To convert
- * an external value back to a segment-specific value, the segment is identified
- * by the range that the external value is in, and the segment's base value is
- * subtracted. For example two five document segments might be combined, so that
- * the first segment has a base value of zero, and the second of five. Document
- * three from the second segment would have an external value of eight.</p>
- * </li>
- * <li>
- * <p>When documents are deleted, gaps are created in the numbering. These are
- * eventually removed as the index evolves through merging. Deleted documents are
- * dropped when segments are merged. A freshly-merged segment thus has no gaps in
- * its numbering.</p>
- * </li>
- * </ul>
- * </div>
- * <a name="Overview"></a>
- * <h2>Index Structure Overview</h2>
- * <div>
- * <p>Each segment index maintains the following:</p>
- * <ul>
- * <li>
- * {@link org.apache.lucene.codecs.lucene70.Lucene70SegmentInfoFormat Segment info}.
- * This contains metadata about a segment, such as the number of documents,
- * what files it uses,
- * </li>
- * <li>
- * {@link org.apache.lucene.codecs.lucene50.Lucene50FieldInfosFormat Field names}.
- * This contains the set of field names used in the index.
- * </li>
- * <li>
- * {@link org.apache.lucene.codecs.lucene50.Lucene50StoredFieldsFormat Stored Field values}.
- * This contains, for each document, a list of attribute-value pairs, where the attributes
- * are field names. These are used to store auxiliary information about the document, such as
- * its title, url, or an identifier to access a database. The set of stored fields are what is
- * returned for each hit when searching. This is keyed by document number.
- * </li>
- * <li>
- * {@link org.apache.lucene.codecs.lucene50.Lucene50PostingsFormat Term dictionary}.
- * A dictionary containing all of the terms used in all of the
- * indexed fields of all of the documents. The dictionary also contains the number
- * of documents which contain the term, and pointers to the term's frequency and
- * proximity data.
- * </li>
- * <li>
- * {@link org.apache.lucene.codecs.lucene50.Lucene50PostingsFormat Term Frequency data}.
- * For each term in the dictionary, the numbers of all the
- * documents that contain that term, and the frequency of the term in that
- * document, unless frequencies are omitted (IndexOptions.DOCS_ONLY)
- * </li>
- * <li>
- * {@link org.apache.lucene.codecs.lucene50.Lucene50PostingsFormat Term Proximity data}.
- * For each term in the dictionary, the positions that the
- * term occurs in each document. Note that this will not exist if all fields in
- * all documents omit position data.
- * </li>
- * <li>
- * {@link org.apache.lucene.codecs.lucene80.Lucene80NormsFormat Normalization factors}.
- * For each field in each document, a value is stored
- * that is multiplied into the score for hits on that field.
- * </li>
- * <li>
- * {@link org.apache.lucene.codecs.lucene50.Lucene50TermVectorsFormat Term Vectors}.
- * For each field in each document, the term vector (sometimes
- * called document vector) may be stored. A term vector consists of term text and
- * term frequency. To add Term Vectors to your index see the
- * {@link org.apache.lucene.document.Field Field} constructors
- * </li>
- * <li>
- * {@link org.apache.lucene.codecs.lucene80.Lucene80DocValuesFormat Per-document values}.
- * Like stored values, these are also keyed by document
- * number, but are generally intended to be loaded into main memory for fast
- * access. Whereas stored values are generally intended for summary results from
- * searches, per-document values are useful for things like scoring factors.
- * </li>
- * <li>
- * {@link org.apache.lucene.codecs.lucene50.Lucene50LiveDocsFormat Live documents}.
- * An optional file indicating which documents are live.
- * </li>
- * <li>
- * {@link org.apache.lucene.codecs.lucene60.Lucene60PointsFormat Point values}.
- * Optional pair of files, recording dimensionally indexed fields, to enable fast
- * numeric range filtering and large numeric values like BigInteger and BigDecimal (1D)
- * and geographic shape intersection (2D, 3D).
- * </li>
- * </ul>
- * <p>Details on each of these are provided in their linked pages.</p>
- * </div>
- * <a name="File_Naming"></a>
- * <h2>File Naming</h2>
- * <div>
- * <p>All files belonging to a segment have the same name with varying extensions.
- * The extensions correspond to the different file formats described below. When
- * using the Compound File format (default for small segments) these files (except
- * for the Segment info file, the Lock file, and Deleted documents file) are collapsed
- * into a single .cfs file (see below for details)</p>
- * <p>Typically, all segments in an index are stored in a single directory,
- * although this is not required.</p>
- * <p>File names are never re-used. That is, when any file is saved
- * to the Directory it is given a never before used filename. This is achieved
- * using a simple generations approach. For example, the first segments file is
- * segments_1, then segments_2, etc. The generation is a sequential long integer
- * represented in alpha-numeric (base 36) form.</p>
- * </div>
- * <a name="file-names"></a>
- * <h2>Summary of File Extensions</h2>
- * <div>
- * <p>The following table summarizes the names and extensions of the files in
- * Lucene:</p>
- * <table cellspacing="1" cellpadding="4" summary="lucene filenames by extension">
- * <tr>
- * <th>Name</th>
- * <th>Extension</th>
- * <th>Brief Description</th>
- * </tr>
- * <tr>
- * <td>{@link org.apache.lucene.index.SegmentInfos Segments File}</td>
- * <td>segments_N</td>
- * <td>Stores information about a commit point</td>
- * </tr>
- * <tr>
- * <td><a href="#Lock_File">Lock File</a></td>
- * <td>write.lock</td>
- * <td>The Write lock prevents multiple IndexWriters from writing to the same
- * file.</td>
- * </tr>
- * <tr>
- * <td>{@link org.apache.lucene.codecs.lucene70.Lucene70SegmentInfoFormat Segment Info}</td>
- * <td>.si</td>
- * <td>Stores metadata about a segment</td>
- * </tr>
- * <tr>
- * <td>{@link org.apache.lucene.codecs.lucene50.Lucene50CompoundFormat Compound File}</td>
- * <td>.cfs, .cfe</td>
- * <td>An optional "virtual" file consisting of all the other index files for
- * systems that frequently run out of file handles.</td>
- * </tr>
- * <tr>
- * <td>{@link org.apache.lucene.codecs.lucene50.Lucene50FieldInfosFormat Fields}</td>
- * <td>.fnm</td>
- * <td>Stores information about the fields</td>
- * </tr>
- * <tr>
- * <td>{@link org.apache.lucene.codecs.lucene50.Lucene50StoredFieldsFormat Field Index}</td>
- * <td>.fdx</td>
- * <td>Contains pointers to field data</td>
- * </tr>
- * <tr>
- * <td>{@link org.apache.lucene.codecs.lucene50.Lucene50StoredFieldsFormat Field Data}</td>
- * <td>.fdt</td>
- * <td>The stored fields for documents</td>
- * </tr>
- * <tr>
- * <td>{@link org.apache.lucene.codecs.lucene50.Lucene50PostingsFormat Term Dictionary}</td>
- * <td>.tim</td>
- * <td>The term dictionary, stores term info</td>
- * </tr>
- * <tr>
- * <td>{@link org.apache.lucene.codecs.lucene50.Lucene50PostingsFormat Term Index}</td>
- * <td>.tip</td>
- * <td>The index into the Term Dictionary</td>
- * </tr>
- * <tr>
- * <td>{@link org.apache.lucene.codecs.lucene50.Lucene50PostingsFormat Frequencies}</td>
- * <td>.doc</td>
- * <td>Contains the list of docs which contain each term along with frequency</td>
- * </tr>
- * <tr>
- * <td>{@link org.apache.lucene.codecs.lucene50.Lucene50PostingsFormat Positions}</td>
- * <td>.pos</td>
- * <td>Stores position information about where a term occurs in the index</td>
- * </tr>
- * <tr>
- * <td>{@link org.apache.lucene.codecs.lucene50.Lucene50PostingsFormat Payloads}</td>
- * <td>.pay</td>
- * <td>Stores additional per-position metadata information such as character offsets and user payloads</td>
- * </tr>
- * <tr>
- * <td>{@link org.apache.lucene.codecs.lucene80.Lucene80NormsFormat Norms}</td>
- * <td>.nvd, .nvm</td>
- * <td>Encodes length and boost factors for docs and fields</td>
- * </tr>
- * <tr>
- * <td>{@link org.apache.lucene.codecs.lucene80.Lucene80DocValuesFormat Per-Document Values}</td>
- * <td>.dvd, .dvm</td>
- * <td>Encodes additional scoring factors or other per-document information.</td>
- * </tr>
- * <tr>
- * <td>{@link org.apache.lucene.codecs.lucene50.Lucene50TermVectorsFormat Term Vector Index}</td>
- * <td>.tvx</td>
- * <td>Stores offset into the document data file</td>
- * </tr>
- * <tr>
- * <td>{@link org.apache.lucene.codecs.lucene50.Lucene50TermVectorsFormat Term Vector Data}</td>
- * <td>.tvd</td>
- * <td>Contains term vector data.</td>
- * </tr>
- * <tr>
- * <td>{@link org.apache.lucene.codecs.lucene50.Lucene50LiveDocsFormat Live Documents}</td>
- * <td>.liv</td>
- * <td>Info about what documents are live</td>
- * </tr>
- * <tr>
- * <td>{@link org.apache.lucene.codecs.lucene60.Lucene60PointsFormat Point values}</td>
- * <td>.dii, .dim</td>
- * <td>Holds indexed points, if any</td>
- * </tr>
- * </table>
- * </div>
- * <a name="Lock_File"></a>
- * <h2>Lock File</h2>
- * The write lock, which is stored in the index directory by default, is named
- * "write.lock". If the lock directory is different from the index directory then
- * the write lock will be named "XXXX-write.lock" where XXXX is a unique prefix
- * derived from the full path to the index directory. When this file is present, a
- * writer is currently modifying the index (adding or removing documents). This
- * lock file ensures that only one writer is modifying the index at a time.
- * <a name="History"></a>
- * <h2>History</h2>
- * <p>Compatibility notes are provided in this document, describing how file
- * formats have changed from prior versions:</p>
- * <ul>
- * <li>In version 2.1, the file format was changed to allow lock-less commits (ie,
- * no more commit lock). The change is fully backwards compatible: you can open a
- * pre-2.1 index for searching or adding/deleting of docs. When the new segments
- * file is saved (committed), it will be written in the new file format (meaning
- * no specific "upgrade" process is needed). But note that once a commit has
- * occurred, pre-2.1 Lucene will not be able to read the index.</li>
- * <li>In version 2.3, the file format was changed to allow segments to share a
- * single set of doc store (vectors &amp; stored fields) files. This allows for
- * faster indexing in certain cases. The change is fully backwards compatible (in
- * the same way as the lock-less commits change in 2.1).</li>
- * <li>In version 2.4, Strings are now written as true UTF-8 byte sequence, not
- * Java's modified UTF-8. See <a href="http://issues.apache.org/jira/browse/LUCENE-510">
- * LUCENE-510</a> for details.</li>
- * <li>In version 2.9, an optional opaque Map&lt;String,String&gt; CommitUserData
- * may be passed to IndexWriter's commit methods (and later retrieved), which is
- * recorded in the segments_N file. See <a href="http://issues.apache.org/jira/browse/LUCENE-1382">
- * LUCENE-1382</a> for details. Also,
- * diagnostics were added to each segment written recording details about why it
- * was written (due to flush, merge; which OS/JRE was used; etc.). See issue
- * <a href="http://issues.apache.org/jira/browse/LUCENE-1654">LUCENE-1654</a> for details.</li>
- * <li>In version 3.0, compressed fields are no longer written to the index (they
- * can still be read, but on merge the new segment will write them, uncompressed).
- * See issue <a href="http://issues.apache.org/jira/browse/LUCENE-1960">LUCENE-1960</a>
- * for details.</li>
- * <li>In version 3.1, segments records the code version that created them. See
- * <a href="http://issues.apache.org/jira/browse/LUCENE-2720">LUCENE-2720</a> for details.
- * Additionally segments track explicitly whether or not they have term vectors.
- * See <a href="http://issues.apache.org/jira/browse/LUCENE-2811">LUCENE-2811</a>
- * for details.</li>
- * <li>In version 3.2, numeric fields are written as natively to stored fields
- * file, previously they were stored in text format only.</li>
- * <li>In version 3.4, fields can omit position data while still indexing term
- * frequencies.</li>
- * <li>In version 4.0, the format of the inverted index became extensible via
- * the {@link org.apache.lucene.codecs.Codec Codec} api. Fast per-document storage
- * ({@code DocValues}) was introduced. Normalization factors need no longer be a
- * single byte, they can be any {@link org.apache.lucene.index.NumericDocValues NumericDocValues}.
- * Terms need not be unicode strings, they can be any byte sequence. Term offsets
- * can optionally be indexed into the postings lists. Payloads can be stored in the
- * term vectors.</li>
- * <li>In version 4.1, the format of the postings list changed to use either
- * of FOR compression or variable-byte encoding, depending upon the frequency
- * of the term. Terms appearing only once were changed to inline directly into
- * the term dictionary. Stored fields are compressed by default. </li>
- * <li>In version 4.2, term vectors are compressed by default. DocValues has
- * a new multi-valued type (SortedSet), that can be used for faceting/grouping/joining
- * on multi-valued fields.</li>
- * <li>In version 4.5, DocValues were extended to explicitly represent missing values.</li>
- * <li>In version 4.6, FieldInfos were extended to support per-field DocValues generation, to
- * allow updating NumericDocValues fields.</li>
- * <li>In version 4.8, checksum footers were added to the end of each index file
- * for improved data integrity. Specifically, the last 8 bytes of every index file
- * contain the zlib-crc32 checksum of the file.</li>
- * <li>In version 4.9, DocValues has a new multi-valued numeric type (SortedNumeric)
- * that is suitable for faceting/sorting/analytics.
- * <li>In version 5.4, DocValues have been improved to store more information on disk:
- * addresses for binary fields and ord indexes for multi-valued fields.
- * <li>In version 6.0, Points were added, for multi-dimensional range/distance search.
- * <li>In version 6.2, new Segment info format that reads/writes the index sort, to support index sorting.
- * <li>In version 7.0, DocValues have been improved to better support sparse doc values
- * thanks to an iterator API.</li>
- * <li>In version 8.0, postings have been enhanced to record, for each block of
- * doc ids, the (term freq, normalization factor) pairs that may trigger the
- * maximum score of the block. This information is recorded alongside skip data
- * in order to be able to skip blocks of doc ids if they may not produce high
- * enough scores.
- * Additionally doc values and norms has been extended with jump-tables to make access O(1)
- * instead of O(n), where n is the number of elements to skip when advancing in the data.</li>
- * </ul>
- * <a name="Limitations"></a>
- * <h2>Limitations</h2>
- * <div>
- * <p>Lucene uses a Java <code>int</code> to refer to
- * document numbers, and the index file format uses an <code>Int32</code>
- * on-disk to store document numbers. This is a limitation
- * of both the index file format and the current implementation. Eventually these
- * should be replaced with either <code>UInt64</code> values, or
- * better yet, {@link org.apache.lucene.store.DataOutput#writeVInt VInt} values which have no limit.</p>
- * </div>
+ * Components from the Lucene 8.0 index format
+ * See {@link org.apache.lucene.codecs.lucene84} for an overview
+ * of the index format.
*/
package org.apache.lucene.codecs.lucene80;
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene84/ForDeltaUtil.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene84/ForDeltaUtil.java
new file mode 100644
index 00000000000..862d049d2a2
--- /dev/null
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene84/ForDeltaUtil.java
@@ -0,0 +1,93 @@
+/*
+ * 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.
+ */
+package org.apache.lucene.codecs.lucene84;
+
+import java.io.IOException;
+
+import org.apache.lucene.store.DataInput;
+import org.apache.lucene.store.DataOutput;
+import org.apache.lucene.util.packed.PackedInts;
+
+/**
+ * Utility class to encode/decode increasing sequences of 128 integers.
+ */
+public class ForDeltaUtil {
+
+ // IDENTITY_PLUS_ONE[i] == i+1
+ private static final long[] IDENTITY_PLUS_ONE = new long[ForUtil.BLOCK_SIZE];
+ static {
+ for (int i = 0; i < ForUtil.BLOCK_SIZE; ++i) {
+ IDENTITY_PLUS_ONE[i] = i+1;
+ }
+ }
+
+ private static void prefixSumOfOnes(long[] arr, long base) {
+ System.arraycopy(IDENTITY_PLUS_ONE, 0, arr, 0, ForUtil.BLOCK_SIZE);
+ // This loop gets auto-vectorized
+ for (int i = 0; i < arr.length; ++i) {
+ arr[i] += base;
+ }
+ }
+
+ private final ForUtil forUtil;
+
+ ForDeltaUtil(ForUtil forUtil) {
+ this.forUtil = forUtil;
+ }
+
+ /**
+ * Encode deltas of a strictly monotonically increasing sequence of integers.
+ * The provided {@code longs} are expected to be deltas between consecutive values.
+ */
+ void encodeDeltas(long[] longs, DataOutput out) throws IOException {
+ if (longs[0] == 1 && PForUtil.allEqual(longs)) { // happens with very dense postings
+ out.writeByte((byte) 0);
+ } else {
+ long or = 0;
+ for (long l : longs) {
+ or |= l;
+ }
+ assert or != 0;
+ final int bitsPerValue = PackedInts.bitsRequired(or);
+ out.writeByte((byte) bitsPerValue);
+ forUtil.encode(longs, bitsPerValue, out);
+ }
+ }
+
+ /**
+ * Decode deltas, compute the prefix sum and add {@code base} to all decoded longs.
+ */
+ void decodeAndPrefixSum(DataInput in, long base, long[] longs) throws IOException {
+ final int bitsPerValue = Byte.toUnsignedInt(in.readByte());
+ if (bitsPerValue == 0) {
+ prefixSumOfOnes(longs, base);
+ } else {
+ forUtil.decodeAndPrefixSum(bitsPerValue, in, base, longs);
+ }
+ }
+
+ /**
+ * Skip a sequence of 128 longs.
+ */
+ void skip(DataInput in) throws IOException {
+ final int bitsPerValue = Byte.toUnsignedInt(in.readByte());
+ if (bitsPerValue != 0) {
+ in.skipBytes(forUtil.numBytes(bitsPerValue));
+ }
+ }
+
+}
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene84/ForUtil.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene84/ForUtil.java
new file mode 100644
index 00000000000..f16aa8377fe
--- /dev/null
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene84/ForUtil.java
@@ -0,0 +1,1125 @@
+// This file has been automatically generated, DO NOT EDIT
+
+/*
+ * 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.
+ */
+package org.apache.lucene.codecs.lucene84;
+
+import java.io.IOException;
+import java.util.Arrays;
+
+import org.apache.lucene.store.DataInput;
+import org.apache.lucene.store.DataOutput;
+
+// Inspired from https://fulmicoton.com/posts/bitpacking/
+// Encodes multiple integers in a long to get SIMD-like speedups.
+// If bitsPerValue <= 8 then we pack 8 ints per long
+// else if bitsPerValue <= 16 we pack 4 ints per long
+// else we pack 2 ints per long
+final class ForUtil {
+
+ static final int BLOCK_SIZE = 128;
+ private static final int BLOCK_SIZE_LOG2 = 7;
+
+ private static long expandMask32(long mask32) {
+ return mask32 | (mask32 << 32);
+ }
+
+ private static long expandMask16(long mask16) {
+ return expandMask32(mask16 | (mask16 << 16));
+ }
+
+ private static long expandMask8(long mask8) {
+ return expandMask16(mask8 | (mask8 << 8));
+ }
+
+ private static long mask32(int bitsPerValue) {
+ return expandMask32((1L << bitsPerValue) - 1);
+ }
+
+ private static long mask16(int bitsPerValue) {
+ return expandMask16((1L << bitsPerValue) - 1);
+ }
+
+ private static long mask8(int bitsPerValue) {
+ return expandMask8((1L << bitsPerValue) - 1);
+ }
+
+ private static void expand8(long[] arr) {
+ for (int i = 0; i < 16; ++i) {
+ long l = arr[i];
+ arr[i] = (l >>> 56) & 0xFFL;
+ arr[16+i] = (l >>> 48) & 0xFFL;
+ arr[32+i] = (l >>> 40) & 0xFFL;
+ arr[48+i] = (l >>> 32) & 0xFFL;
+ arr[64+i] = (l >>> 24) & 0xFFL;
+ arr[80+i] = (l >>> 16) & 0xFFL;
+ arr[96+i] = (l >>> 8) & 0xFFL;
+ arr[112+i] = l & 0xFFL;
+ }
+ }
+
+ private static void expand8To32(long[] arr) {
+ for (int i = 0; i < 16; ++i) {
+ long l = arr[i];
+ arr[i] = (l >>> 24) & 0x000000FF000000FFL;
+ arr[16+i] = (l >>> 16) & 0x000000FF000000FFL;
+ arr[32+i] = (l >>> 8) & 0x000000FF000000FFL;
+ arr[48+i] = l & 0x000000FF000000FFL;
+ }
+ }
+
+ private static void collapse8(long[] arr) {
+ for (int i = 0; i < 16; ++i) {
+ arr[i] = (arr[i] << 56) | (arr[16+i] << 48) | (arr[32+i] << 40) | (arr[48+i] << 32) | (arr[64+i] << 24) | (arr[80+i] << 16) | (arr[96+i] << 8) | arr[112+i];
+ }
+ }
+
+ private static void expand16(long[] arr) {
+ for (int i = 0; i < 32; ++i) {
+ long l = arr[i];
+ arr[i] = (l >>> 48) & 0xFFFFL;
+ arr[32+i] = (l >>> 32) & 0xFFFFL;
+ arr[64+i] = (l >>> 16) & 0xFFFFL;
+ arr[96+i] = l & 0xFFFFL;
+ }
+ }
+
+ private static void expand16To32(long[] arr) {
+ for (int i = 0; i < 32; ++i) {
+ long l = arr[i];
+ arr[i] = (l >>> 16) & 0x0000FFFF0000FFFFL;
+ arr[32+i] = l & 0x0000FFFF0000FFFFL;
+ }
+ }
+
+ private static void collapse16(long[] arr) {
+ for (int i = 0; i < 32; ++i) {
+ arr[i] = (arr[i] << 48) | (arr[32+i] << 32) | (arr[64+i] << 16) | arr[96+i];
+ }
+ }
+
+ private static void expand32(long[] arr) {
+ for (int i = 0; i < 64; ++i) {
+ long l = arr[i];
+ arr[i] = l >>> 32;
+ arr[64 + i] = l & 0xFFFFFFFFL;
+ }
+ }
+
+ private static void collapse32(long[] arr) {
+ for (int i = 0; i < 64; ++i) {
+ arr[i] = (arr[i] << 32) | arr[64+i];
+ }
+ }
+
+ private static void prefixSum8(long[] arr, long base) {
+ expand8To32(arr);
+ prefixSum32(arr, base);
+ }
+
+ private static void prefixSum16(long[] arr, long base) {
+ // We need to move to the next primitive size to avoid overflows
+ expand16To32(arr);
+ prefixSum32(arr, base);
+ }
+
+ private static void prefixSum32(long[] arr, long base) {
+ arr[0] += base << 32;
+ innerPrefixSum32(arr);
+ expand32(arr);
+ final long l = arr[BLOCK_SIZE/2-1];
+ for (int i = BLOCK_SIZE/2; i < BLOCK_SIZE; ++i) {
+ arr[i] += l;
+ }
+ }
+
+ // For some reason unrolling seems to help
+ private static void innerPrefixSum32(long[] arr) {
+ arr[1] += arr[0];
+ arr[2] += arr[1];
+ arr[3] += arr[2];
+ arr[4] += arr[3];
+ arr[5] += arr[4];
+ arr[6] += arr[5];
+ arr[7] += arr[6];
+ arr[8] += arr[7];
+ arr[9] += arr[8];
+ arr[10] += arr[9];
+ arr[11] += arr[10];
+ arr[12] += arr[11];
+ arr[13] += arr[12];
+ arr[14] += arr[13];
+ arr[15] += arr[14];
+ arr[16] += arr[15];
+ arr[17] += arr[16];
+ arr[18] += arr[17];
+ arr[19] += arr[18];
+ arr[20] += arr[19];
+ arr[21] += arr[20];
+ arr[22] += arr[21];
+ arr[23] += arr[22];
+ arr[24] += arr[23];
+ arr[25] += arr[24];
+ arr[26] += arr[25];
+ arr[27] += arr[26];
+ arr[28] += arr[27];
+ arr[29] += arr[28];
+ arr[30] += arr[29];
+ arr[31] += arr[30];
+ arr[32] += arr[31];
+ arr[33] += arr[32];
+ arr[34] += arr[33];
+ arr[35] += arr[34];
+ arr[36] += arr[35];
+ arr[37] += arr[36];
+ arr[38] += arr[37];
+ arr[39] += arr[38];
+ arr[40] += arr[39];
+ arr[41] += arr[40];
+ arr[42] += arr[41];
+ arr[43] += arr[42];
+ arr[44] += arr[43];
+ arr[45] += arr[44];
+ arr[46] += arr[45];
+ arr[47] += arr[46];
+ arr[48] += arr[47];
+ arr[49] += arr[48];
+ arr[50] += arr[49];
+ arr[51] += arr[50];
+ arr[52] += arr[51];
+ arr[53] += arr[52];
+ arr[54] += arr[53];
+ arr[55] += arr[54];
+ arr[56] += arr[55];
+ arr[57] += arr[56];
+ arr[58] += arr[57];
+ arr[59] += arr[58];
+ arr[60] += arr[59];
+ arr[61] += arr[60];
+ arr[62] += arr[61];
+ arr[63] += arr[62];
+ }
+
+ private final long[] tmp = new long[BLOCK_SIZE/2];
+
+ /**
+ * Encode 128 integers from {@code longs} into {@code out}.
+ */
+ void encode(long[] longs, int bitsPerValue, DataOutput out) throws IOException {
+ final int nextPrimitive;
+ final int numLongs;
+ if (bitsPerValue <= 8) {
+ nextPrimitive = 8;
+ numLongs = BLOCK_SIZE / 8;
+ collapse8(longs);
+ } else if (bitsPerValue <= 16) {
+ nextPrimitive = 16;
+ numLongs = BLOCK_SIZE / 4;
+ collapse16(longs);
+ } else {
+ nextPrimitive = 32;
+ numLongs = BLOCK_SIZE / 2;
+ collapse32(longs);
+ }
+
+ final int numLongsPerShift = bitsPerValue * 2;
+ Arrays.fill(tmp, 0L);
+ int idx = 0;
+ for (int shift = nextPrimitive - bitsPerValue; shift >= 0; shift -= bitsPerValue) {
+ for (int i = 0; i < numLongsPerShift; ++i) {
+ tmp[i] |= longs[idx++] << shift;
+ }
+ }
+
+ final int remainingBitsPerLong = nextPrimitive % bitsPerValue;
+ final long maskRemainingBitsPerLong;
+ if (nextPrimitive == 8) {
+ maskRemainingBitsPerLong = mask8(remainingBitsPerLong);
+ } else if (nextPrimitive == 16) {
+ maskRemainingBitsPerLong = mask16(remainingBitsPerLong);
+ } else {
+ maskRemainingBitsPerLong = mask32(remainingBitsPerLong);
+ }
+ int tmpIdx = 0;
+ int remainingBitsPerValue = bitsPerValue;
+ while (idx < numLongs) {
+ if (remainingBitsPerValue > remainingBitsPerLong) {
+ remainingBitsPerValue -= remainingBitsPerLong;
+ tmp[tmpIdx++] |= (longs[idx] >>> remainingBitsPerValue) & maskRemainingBitsPerLong;
+ if (remainingBitsPerValue == 0) {
+ idx++;
+ remainingBitsPerValue = bitsPerValue;
+ }
+ } else {
+ final long mask1, mask2;
+ if (nextPrimitive == 8) {
+ mask1 = mask8(remainingBitsPerValue);
+ mask2 = mask8(remainingBitsPerLong - remainingBitsPerValue);
+ } else if (nextPrimitive == 16) {
+ mask1 = mask16(remainingBitsPerValue);
+ mask2 = mask16(remainingBitsPerLong - remainingBitsPerValue);
+ } else {
+ mask1 = mask32(remainingBitsPerValue);
+ mask2 = mask32(remainingBitsPerLong - remainingBitsPerValue);
+ }
+ tmp[tmpIdx] |= (longs[idx++] & mask1) << (remainingBitsPerLong - remainingBitsPerValue);
+ remainingBitsPerValue = bitsPerValue - remainingBitsPerLong + remainingBitsPerValue;
+ tmp[tmpIdx++] |= (longs[idx] >>> remainingBitsPerValue) & mask2;
+ }
+ }
+
+ for (int i = 0; i < numLongsPerShift; ++i) {
+ // Java longs are big endian and we want to read little endian longs, so we need to reverse bytes
+ long l = Long.reverseBytes(tmp[i]);
+ out.writeLong(l);
+ }
+ }
+
+ /**
+ * Number of bytes required to encode 128 integers of {@code bitsPerValue} bits per value.
+ */
+ int numBytes(int bitsPerValue) throws IOException {
+ return bitsPerValue << (BLOCK_SIZE_LOG2 - 3);
+ }
+
+ private static void decodeSlow(int bitsPerValue, DataInput in, long[] tmp, long[] longs) throws IOException {
+ final int numLongs = bitsPerValue << 1;
+ in.readLELongs(tmp, 0, numLongs);
+ final long mask = mask32(bitsPerValue);
+ int longsIdx = 0;
+ int shift = 32 - bitsPerValue;
+ for (; shift >= 0; shift -= bitsPerValue) {
+ shiftLongs(tmp, numLongs, longs, longsIdx, shift, mask);
+ longsIdx += numLongs;
+ }
+ final int remainingBitsPerLong = shift + bitsPerValue;
+ final long mask32RemainingBitsPerLong = mask32(remainingBitsPerLong);
+ int tmpIdx = 0;
+ int remainingBits = remainingBitsPerLong;
+ for (; longsIdx < BLOCK_SIZE / 2; ++longsIdx) {
+ int b = bitsPerValue - remainingBits;
+ long l = (tmp[tmpIdx++] & mask32(remainingBits)) << b;
+ while (b >= remainingBitsPerLong) {
+ b -= remainingBitsPerLong;
+ l |= (tmp[tmpIdx++] & mask32RemainingBitsPerLong) << b;
+ }
+ if (b > 0) {
+ l |= (tmp[tmpIdx] >>> (remainingBitsPerLong-b)) & mask32(b);
+ remainingBits = remainingBitsPerLong - b;
+ } else {
+ remainingBits = remainingBitsPerLong;
+ }
+ longs[longsIdx] = l;
+ }
+ }
+
+ /**
+ * The pattern that this shiftLongs method applies is recognized by the C2
+ * compiler, which generates SIMD instructions for it in order to shift
+ * multiple longs at once.
+ */
+ private static void shiftLongs(long[] a, int count, long[] b, int bi, int shift, long mask) {
+ for (int i = 0; i < count; ++i) {
+ b[bi+i] = (a[i] >>> shift) & mask;
+ }
+ }
+
+ private static final long MASK8_1 = mask8(1);
+ private static final long MASK8_2 = mask8(2);
+ private static final long MASK8_3 = mask8(3);
+ private static final long MASK8_4 = mask8(4);
+ private static final long MASK8_5 = mask8(5);
+ private static final long MASK8_6 = mask8(6);
+ private static final long MASK8_7 = mask8(7);
+ private static final long MASK16_1 = mask16(1);
+ private static final long MASK16_2 = mask16(2);
+ private static final long MASK16_3 = mask16(3);
+ private static final long MASK16_4 = mask16(4);
+ private static final long MASK16_5 = mask16(5);
+ private static final long MASK16_6 = mask16(6);
+ private static final long MASK16_7 = mask16(7);
+ private static final long MASK16_9 = mask16(9);
+ private static final long MASK16_10 = mask16(10);
+ private static final long MASK16_11 = mask16(11);
+ private static final long MASK16_12 = mask16(12);
+ private static final long MASK16_13 = mask16(13);
+ private static final long MASK16_14 = mask16(14);
+ private static final long MASK16_15 = mask16(15);
+ private static final long MASK32_1 = mask32(1);
+ private static final long MASK32_2 = mask32(2);
+ private static final long MASK32_3 = mask32(3);
+ private static final long MASK32_4 = mask32(4);
+ private static final long MASK32_5 = mask32(5);
+ private static final long MASK32_6 = mask32(6);
+ private static final long MASK32_7 = mask32(7);
+ private static final long MASK32_8 = mask32(8);
+ private static final long MASK32_9 = mask32(9);
+ private static final long MASK32_10 = mask32(10);
+ private static final long MASK32_11 = mask32(11);
+ private static final long MASK32_12 = mask32(12);
+ private static final long MASK32_13 = mask32(13);
+ private static final long MASK32_14 = mask32(14);
+ private static final long MASK32_15 = mask32(15);
+ private static final long MASK32_17 = mask32(17);
+ private static final long MASK32_18 = mask32(18);
+ private static final long MASK32_19 = mask32(19);
+ private static final long MASK32_20 = mask32(20);
+ private static final long MASK32_21 = mask32(21);
+ private static final long MASK32_22 = mask32(22);
+ private static final long MASK32_23 = mask32(23);
+ private static final long MASK32_24 = mask32(24);
+
+
+ /**
+ * Decode 128 integers into {@code longs}.
+ */
+ void decode(int bitsPerValue, DataInput in, long[] longs) throws IOException {
+ switch (bitsPerValue) {
+ case 1:
+ decode1(in, tmp, longs);
+ expand8(longs);
+ break;
+ case 2:
+ decode2(in, tmp, longs);
+ expand8(longs);
+ break;
+ case 3:
+ decode3(in, tmp, longs);
+ expand8(longs);
+ break;
+ case 4:
+ decode4(in, tmp, longs);
+ expand8(longs);
+ break;
+ case 5:
+ decode5(in, tmp, longs);
+ expand8(longs);
+ break;
+ case 6:
+ decode6(in, tmp, longs);
+ expand8(longs);
+ break;
+ case 7:
+ decode7(in, tmp, longs);
+ expand8(longs);
+ break;
+ case 8:
+ decode8(in, tmp, longs);
+ expand8(longs);
+ break;
+ case 9:
+ decode9(in, tmp, longs);
+ expand16(longs);
+ break;
+ case 10:
+ decode10(in, tmp, longs);
+ expand16(longs);
+ break;
+ case 11:
+ decode11(in, tmp, longs);
+ expand16(longs);
+ break;
+ case 12:
+ decode12(in, tmp, longs);
+ expand16(longs);
+ break;
+ case 13:
+ decode13(in, tmp, longs);
+ expand16(longs);
+ break;
+ case 14:
+ decode14(in, tmp, longs);
+ expand16(longs);
+ break;
+ case 15:
+ decode15(in, tmp, longs);
+ expand16(longs);
+ break;
+ case 16:
+ decode16(in, tmp, longs);
+ expand16(longs);
+ break;
+ case 17:
+ decode17(in, tmp, longs);
+ expand32(longs);
+ break;
+ case 18:
+ decode18(in, tmp, longs);
+ expand32(longs);
+ break;
+ case 19:
+ decode19(in, tmp, longs);
+ expand32(longs);
+ break;
+ case 20:
+ decode20(in, tmp, longs);
+ expand32(longs);
+ break;
+ case 21:
+ decode21(in, tmp, longs);
+ expand32(longs);
+ break;
+ case 22:
+ decode22(in, tmp, longs);
+ expand32(longs);
+ break;
+ case 23:
+ decode23(in, tmp, longs);
+ expand32(longs);
+ break;
+ case 24:
+ decode24(in, tmp, longs);
+ expand32(longs);
+ break;
+ default:
+ decodeSlow(bitsPerValue, in, tmp, longs);
+ expand32(longs);
+ break;
+ }
+ }
+
+ /**
+ * Delta-decode 128 integers into {@code longs}.
+ */
+ void decodeAndPrefixSum(int bitsPerValue, DataInput in, long base, long[] longs) throws IOException {
+ switch (bitsPerValue) {
+ case 1:
+ decode1(in, tmp, longs);
+ prefixSum8(longs, base);
+ break;
+ case 2:
+ decode2(in, tmp, longs);
+ prefixSum8(longs, base);
+ break;
+ case 3:
+ decode3(in, tmp, longs);
+ prefixSum8(longs, base);
+ break;
+ case 4:
+ decode4(in, tmp, longs);
+ prefixSum8(longs, base);
+ break;
+ case 5:
+ decode5(in, tmp, longs);
+ prefixSum8(longs, base);
+ break;
+ case 6:
+ decode6(in, tmp, longs);
+ prefixSum8(longs, base);
+ break;
+ case 7:
+ decode7(in, tmp, longs);
+ prefixSum8(longs, base);
+ break;
+ case 8:
+ decode8(in, tmp, longs);
+ prefixSum8(longs, base);
+ break;
+ case 9:
+ decode9(in, tmp, longs);
+ prefixSum16(longs, base);
+ break;
+ case 10:
+ decode10(in, tmp, longs);
+ prefixSum16(longs, base);
+ break;
+ case 11:
+ decode11(in, tmp, longs);
+ prefixSum16(longs, base);
+ break;
+ case 12:
+ decode12(in, tmp, longs);
+ prefixSum16(longs, base);
+ break;
+ case 13:
+ decode13(in, tmp, longs);
+ prefixSum16(longs, base);
+ break;
+ case 14:
+ decode14(in, tmp, longs);
+ prefixSum16(longs, base);
+ break;
+ case 15:
+ decode15(in, tmp, longs);
+ prefixSum16(longs, base);
+ break;
+ case 16:
+ decode16(in, tmp, longs);
+ prefixSum16(longs, base);
+ break;
+ case 17:
+ decode17(in, tmp, longs);
+ prefixSum32(longs, base);
+ break;
+ case 18:
+ decode18(in, tmp, longs);
+ prefixSum32(longs, base);
+ break;
+ case 19:
+ decode19(in, tmp, longs);
+ prefixSum32(longs, base);
+ break;
+ case 20:
+ decode20(in, tmp, longs);
+ prefixSum32(longs, base);
+ break;
+ case 21:
+ decode21(in, tmp, longs);
+ prefixSum32(longs, base);
+ break;
+ case 22:
+ decode22(in, tmp, longs);
+ prefixSum32(longs, base);
+ break;
+ case 23:
+ decode23(in, tmp, longs);
+ prefixSum32(longs, base);
+ break;
+ case 24:
+ decode24(in, tmp, longs);
+ prefixSum32(longs, base);
+ break;
+ default:
+ decodeSlow(bitsPerValue, in, tmp, longs);
+ prefixSum32(longs, base);
+ break;
+ }
+ }
+
+ private static void decode1(DataInput in, long[] tmp, long[] longs) throws IOException {
+ in.readLELongs(tmp, 0, 2);
+ shiftLongs(tmp, 2, longs, 0, 7, MASK8_1);
+ shiftLongs(tmp, 2, longs, 2, 6, MASK8_1);
+ shiftLongs(tmp, 2, longs, 4, 5, MASK8_1);
+ shiftLongs(tmp, 2, longs, 6, 4, MASK8_1);
+ shiftLongs(tmp, 2, longs, 8, 3, MASK8_1);
+ shiftLongs(tmp, 2, longs, 10, 2, MASK8_1);
+ shiftLongs(tmp, 2, longs, 12, 1, MASK8_1);
+ shiftLongs(tmp, 2, longs, 14, 0, MASK8_1);
+ }
+
+ private static void decode2(DataInput in, long[] tmp, long[] longs) throws IOException {
+ in.readLELongs(tmp, 0, 4);
+ shiftLongs(tmp, 4, longs, 0, 6, MASK8_2);
+ shiftLongs(tmp, 4, longs, 4, 4, MASK8_2);
+ shiftLongs(tmp, 4, longs, 8, 2, MASK8_2);
+ shiftLongs(tmp, 4, longs, 12, 0, MASK8_2);
+ }
+
+ private static void decode3(DataInput in, long[] tmp, long[] longs) throws IOException {
+ in.readLELongs(tmp, 0, 6);
+ shiftLongs(tmp, 6, longs, 0, 5, MASK8_3);
+ shiftLongs(tmp, 6, longs, 6, 2, MASK8_3);
+ for (int iter = 0, tmpIdx = 0, longsIdx = 12; iter < 2; ++iter, tmpIdx += 3, longsIdx += 2) {
+ long l0 = (tmp[tmpIdx+0] & MASK8_2) << 1;
+ l0 |= (tmp[tmpIdx+1] >>> 1) & MASK8_1;
+ longs[longsIdx+0] = l0;
+ long l1 = (tmp[tmpIdx+1] & MASK8_1) << 2;
+ l1 |= (tmp[tmpIdx+2] & MASK8_2) << 0;
+ longs[longsIdx+1] = l1;
+ }
+ }
+
+ private static void decode4(DataInput in, long[] tmp, long[] longs) throws IOException {
+ in.readLELongs(tmp, 0, 8);
+ shiftLongs(tmp, 8, longs, 0, 4, MASK8_4);
+ shiftLongs(tmp, 8, longs, 8, 0, MASK8_4);
+ }
+
+ private static void decode5(DataInput in, long[] tmp, long[] longs) throws IOException {
+ in.readLELongs(tmp, 0, 10);
+ shiftLongs(tmp, 10, longs, 0, 3, MASK8_5);
+ for (int iter = 0, tmpIdx = 0, longsIdx = 10; iter < 2; ++iter, tmpIdx += 5, longsIdx += 3) {
+ long l0 = (tmp[tmpIdx+0] & MASK8_3) << 2;
+ l0 |= (tmp[tmpIdx+1] >>> 1) & MASK8_2;
+ longs[longsIdx+0] = l0;
+ long l1 = (tmp[tmpIdx+1] & MASK8_1) << 4;
+ l1 |= (tmp[tmpIdx+2] & MASK8_3) << 1;
+ l1 |= (tmp[tmpIdx+3] >>> 2) & MASK8_1;
+ longs[longsIdx+1] = l1;
+ long l2 = (tmp[tmpIdx+3] & MASK8_2) << 3;
+ l2 |= (tmp[tmpIdx+4] & MASK8_3) << 0;
+ longs[longsIdx+2] = l2;
+ }
+ }
+
+ private static void decode6(DataInput in, long[] tmp, long[] longs) throws IOException {
+ in.readLELongs(tmp, 0, 12);
+ shiftLongs(tmp, 12, longs, 0, 2, MASK8_6);
+ for (int iter = 0, tmpIdx = 0, longsIdx = 12; iter < 4; ++iter, tmpIdx += 3, longsIdx += 1) {
+ long l0 = (tmp[tmpIdx+0] & MASK8_2) << 4;
+ l0 |= (tmp[tmpIdx+1] & MASK8_2) << 2;
+ l0 |= (tmp[tmpIdx+2] & MASK8_2) << 0;
+ longs[longsIdx+0] = l0;
+ }
+ }
+
+ private static void decode7(DataInput in, long[] tmp, long[] longs) throws IOException {
+ in.readLELongs(tmp, 0, 14);
+ shiftLongs(tmp, 14, longs, 0, 1, MASK8_7);
+ for (int iter = 0, tmpIdx = 0, longsIdx = 14; iter < 2; ++iter, tmpIdx += 7, longsIdx += 1) {
+ long l0 = (tmp[tmpIdx+0] & MASK8_1) << 6;
+ l0 |= (tmp[tmpIdx+1] & MASK8_1) << 5;
+ l0 |= (tmp[tmpIdx+2] & MASK8_1) << 4;
+ l0 |= (tmp[tmpIdx+3] & MASK8_1) << 3;
+ l0 |= (tmp[tmpIdx+4] & MASK8_1) << 2;
+ l0 |= (tmp[tmpIdx+5] & MASK8_1) << 1;
+ l0 |= (tmp[tmpIdx+6] & MASK8_1) << 0;
+ longs[longsIdx+0] = l0;
+ }
+ }
+
+ private static void decode8(DataInput in, long[] tmp, long[] longs) throws IOException {
+ in.readLELongs(longs, 0, 16);
+ }
+
+ private static void decode9(DataInput in, long[] tmp, long[] longs) throws IOException {
+ in.readLELongs(tmp, 0, 18);
+ shiftLongs(tmp, 18, longs, 0, 7, MASK16_9);
+ for (int iter = 0, tmpIdx = 0, longsIdx = 18; iter < 2; ++iter, tmpIdx += 9, longsIdx += 7) {
+ long l0 = (tmp[tmpIdx+0] & MASK16_7) << 2;
+ l0 |= (tmp[tmpIdx+1] >>> 5) & MASK16_2;
+ longs[longsIdx+0] = l0;
+ long l1 = (tmp[tmpIdx+1] & MASK16_5) << 4;
+ l1 |= (tmp[tmpIdx+2] >>> 3) & MASK16_4;
+ longs[longsIdx+1] = l1;
+ long l2 = (tmp[tmpIdx+2] & MASK16_3) << 6;
+ l2 |= (tmp[tmpIdx+3] >>> 1) & MASK16_6;
+ longs[longsIdx+2] = l2;
+ long l3 = (tmp[tmpIdx+3] & MASK16_1) << 8;
+ l3 |= (tmp[tmpIdx+4] & MASK16_7) << 1;
+ l3 |= (tmp[tmpIdx+5] >>> 6) & MASK16_1;
+ longs[longsIdx+3] = l3;
+ long l4 = (tmp[tmpIdx+5] & MASK16_6) << 3;
+ l4 |= (tmp[tmpIdx+6] >>> 4) & MASK16_3;
+ longs[longsIdx+4] = l4;
+ long l5 = (tmp[tmpIdx+6] & MASK16_4) << 5;
+ l5 |= (tmp[tmpIdx+7] >>> 2) & MASK16_5;
+ longs[longsIdx+5] = l5;
+ long l6 = (tmp[tmpIdx+7] & MASK16_2) << 7;
+ l6 |= (tmp[tmpIdx+8] & MASK16_7) << 0;
+ longs[longsIdx+6] = l6;
+ }
+ }
+
+ private static void decode10(DataInput in, long[] tmp, long[] longs) throws IOException {
+ in.readLELongs(tmp, 0, 20);
+ shiftLongs(tmp, 20, longs, 0, 6, MASK16_10);
+ for (int iter = 0, tmpIdx = 0, longsIdx = 20; iter < 4; ++iter, tmpIdx += 5, longsIdx += 3) {
+ long l0 = (tmp[tmpIdx+0] & MASK16_6) << 4;
+ l0 |= (tmp[tmpIdx+1] >>> 2) & MASK16_4;
+ longs[longsIdx+0] = l0;
+ long l1 = (tmp[tmpIdx+1] & MASK16_2) << 8;
+ l1 |= (tmp[tmpIdx+2] & MASK16_6) << 2;
+ l1 |= (tmp[tmpIdx+3] >>> 4) & MASK16_2;
+ longs[longsIdx+1] = l1;
+ long l2 = (tmp[tmpIdx+3] & MASK16_4) << 6;
+ l2 |= (tmp[tmpIdx+4] & MASK16_6) << 0;
+ longs[longsIdx+2] = l2;
+ }
+ }
+
+ private static void decode11(DataInput in, long[] tmp, long[] longs) throws IOException {
+ in.readLELongs(tmp, 0, 22);
+ shiftLongs(tmp, 22, longs, 0, 5, MASK16_11);
+ for (int iter = 0, tmpIdx = 0, longsIdx = 22; iter < 2; ++iter, tmpIdx += 11, longsIdx += 5) {
+ long l0 = (tmp[tmpIdx+0] & MASK16_5) << 6;
+ l0 |= (tmp[tmpIdx+1] & MASK16_5) << 1;
+ l0 |= (tmp[tmpIdx+2] >>> 4) & MASK16_1;
+ longs[longsIdx+0] = l0;
+ long l1 = (tmp[tmpIdx+2] & MASK16_4) << 7;
+ l1 |= (tmp[tmpIdx+3] & MASK16_5) << 2;
+ l1 |= (tmp[tmpIdx+4] >>> 3) & MASK16_2;
+ longs[longsIdx+1] = l1;
+ long l2 = (tmp[tmpIdx+4] & MASK16_3) << 8;
+ l2 |= (tmp[tmpIdx+5] & MASK16_5) << 3;
+ l2 |= (tmp[tmpIdx+6] >>> 2) & MASK16_3;
+ longs[longsIdx+2] = l2;
+ long l3 = (tmp[tmpIdx+6] & MASK16_2) << 9;
+ l3 |= (tmp[tmpIdx+7] & MASK16_5) << 4;
+ l3 |= (tmp[tmpIdx+8] >>> 1) & MASK16_4;
+ longs[longsIdx+3] = l3;
+ long l4 = (tmp[tmpIdx+8] & MASK16_1) << 10;
+ l4 |= (tmp[tmpIdx+9] & MASK16_5) << 5;
+ l4 |= (tmp[tmpIdx+10] & MASK16_5) << 0;
+ longs[longsIdx+4] = l4;
+ }
+ }
+
+ private static void decode12(DataInput in, long[] tmp, long[] longs) throws IOException {
+ in.readLELongs(tmp, 0, 24);
+ shiftLongs(tmp, 24, longs, 0, 4, MASK16_12);
+ for (int iter = 0, tmpIdx = 0, longsIdx = 24; iter < 8; ++iter, tmpIdx += 3, longsIdx += 1) {
+ long l0 = (tmp[tmpIdx+0] & MASK16_4) << 8;
+ l0 |= (tmp[tmpIdx+1] & MASK16_4) << 4;
+ l0 |= (tmp[tmpIdx+2] & MASK16_4) << 0;
+ longs[longsIdx+0] = l0;
+ }
+ }
+
+ private static void decode13(DataInput in, long[] tmp, long[] longs) throws IOException {
+ in.readLELongs(tmp, 0, 26);
+ shiftLongs(tmp, 26, longs, 0, 3, MASK16_13);
+ for (int iter = 0, tmpIdx = 0, longsIdx = 26; iter < 2; ++iter, tmpIdx += 13, longsIdx += 3) {
+ long l0 = (tmp[tmpIdx+0] & MASK16_3) << 10;
+ l0 |= (tmp[tmpIdx+1] & MASK16_3) << 7;
+ l0 |= (tmp[tmpIdx+2] & MASK16_3) << 4;
+ l0 |= (tmp[tmpIdx+3] & MASK16_3) << 1;
+ l0 |= (tmp[tmpIdx+4] >>> 2) & MASK16_1;
+ longs[longsIdx+0] = l0;
+ long l1 = (tmp[tmpIdx+4] & MASK16_2) << 11;
+ l1 |= (tmp[tmpIdx+5] & MASK16_3) << 8;
+ l1 |= (tmp[tmpIdx+6] & MASK16_3) << 5;
+ l1 |= (tmp[tmpIdx+7] & MASK16_3) << 2;
+ l1 |= (tmp[tmpIdx+8] >>> 1) & MASK16_2;
+ longs[longsIdx+1] = l1;
+ long l2 = (tmp[tmpIdx+8] & MASK16_1) << 12;
+ l2 |= (tmp[tmpIdx+9] & MASK16_3) << 9;
+ l2 |= (tmp[tmpIdx+10] & MASK16_3) << 6;
+ l2 |= (tmp[tmpIdx+11] & MASK16_3) << 3;
+ l2 |= (tmp[tmpIdx+12] & MASK16_3) << 0;
+ longs[longsIdx+2] = l2;
+ }
+ }
+
+ private static void decode14(DataInput in, long[] tmp, long[] longs) throws IOException {
+ in.readLELongs(tmp, 0, 28);
+ shiftLongs(tmp, 28, longs, 0, 2, MASK16_14);
+ for (int iter = 0, tmpIdx = 0, longsIdx = 28; iter < 4; ++iter, tmpIdx += 7, longsIdx += 1) {
+ long l0 = (tmp[tmpIdx+0] & MASK16_2) << 12;
+ l0 |= (tmp[tmpIdx+1] & MASK16_2) << 10;
+ l0 |= (tmp[tmpIdx+2] & MASK16_2) << 8;
+ l0 |= (tmp[tmpIdx+3] & MASK16_2) << 6;
+ l0 |= (tmp[tmpIdx+4] & MASK16_2) << 4;
+ l0 |= (tmp[tmpIdx+5] & MASK16_2) << 2;
+ l0 |= (tmp[tmpIdx+6] & MASK16_2) << 0;
+ longs[longsIdx+0] = l0;
+ }
+ }
+
+ private static void decode15(DataInput in, long[] tmp, long[] longs) throws IOException {
+ in.readLELongs(tmp, 0, 30);
+ shiftLongs(tmp, 30, longs, 0, 1, MASK16_15);
+ for (int iter = 0, tmpIdx = 0, longsIdx = 30; iter < 2; ++iter, tmpIdx += 15, longsIdx += 1) {
+ long l0 = (tmp[tmpIdx+0] & MASK16_1) << 14;
+ l0 |= (tmp[tmpIdx+1] & MASK16_1) << 13;
+ l0 |= (tmp[tmpIdx+2] & MASK16_1) << 12;
+ l0 |= (tmp[tmpIdx+3] & MASK16_1) << 11;
+ l0 |= (tmp[tmpIdx+4] & MASK16_1) << 10;
+ l0 |= (tmp[tmpIdx+5] & MASK16_1) << 9;
+ l0 |= (tmp[tmpIdx+6] & MASK16_1) << 8;
+ l0 |= (tmp[tmpIdx+7] & MASK16_1) << 7;
+ l0 |= (tmp[tmpIdx+8] & MASK16_1) << 6;
+ l0 |= (tmp[tmpIdx+9] & MASK16_1) << 5;
+ l0 |= (tmp[tmpIdx+10] & MASK16_1) << 4;
+ l0 |= (tmp[tmpIdx+11] & MASK16_1) << 3;
+ l0 |= (tmp[tmpIdx+12] & MASK16_1) << 2;
+ l0 |= (tmp[tmpIdx+13] & MASK16_1) << 1;
+ l0 |= (tmp[tmpIdx+14] & MASK16_1) << 0;
+ longs[longsIdx+0] = l0;
+ }
+ }
+
+ private static void decode16(DataInput in, long[] tmp, long[] longs) throws IOException {
+ in.readLELongs(longs, 0, 32);
+ }
+
+ private static void decode17(DataInput in, long[] tmp, long[] longs) throws IOException {
+ in.readLELongs(tmp, 0, 34);
+ shiftLongs(tmp, 34, longs, 0, 15, MASK32_17);
+ for (int iter = 0, tmpIdx = 0, longsIdx = 34; iter < 2; ++iter, tmpIdx += 17, longsIdx += 15) {
+ long l0 = (tmp[tmpIdx+0] & MASK32_15) << 2;
+ l0 |= (tmp[tmpIdx+1] >>> 13) & MASK32_2;
+ longs[longsIdx+0] = l0;
+ long l1 = (tmp[tmpIdx+1] & MASK32_13) << 4;
+ l1 |= (tmp[tmpIdx+2] >>> 11) & MASK32_4;
+ longs[longsIdx+1] = l1;
+ long l2 = (tmp[tmpIdx+2] & MASK32_11) << 6;
+ l2 |= (tmp[tmpIdx+3] >>> 9) & MASK32_6;
+ longs[longsIdx+2] = l2;
+ long l3 = (tmp[tmpIdx+3] & MASK32_9) << 8;
+ l3 |= (tmp[tmpIdx+4] >>> 7) & MASK32_8;
+ longs[longsIdx+3] = l3;
+ long l4 = (tmp[tmpIdx+4] & MASK32_7) << 10;
+ l4 |= (tmp[tmpIdx+5] >>> 5) & MASK32_10;
+ longs[longsIdx+4] = l4;
+ long l5 = (tmp[tmpIdx+5] & MASK32_5) << 12;
+ l5 |= (tmp[tmpIdx+6] >>> 3) & MASK32_12;
+ longs[longsIdx+5] = l5;
+ long l6 = (tmp[tmpIdx+6] & MASK32_3) << 14;
+ l6 |= (tmp[tmpIdx+7] >>> 1) & MASK32_14;
+ longs[longsIdx+6] = l6;
+ long l7 = (tmp[tmpIdx+7] & MASK32_1) << 16;
+ l7 |= (tmp[tmpIdx+8] & MASK32_15) << 1;
+ l7 |= (tmp[tmpIdx+9] >>> 14) & MASK32_1;
+ longs[longsIdx+7] = l7;
+ long l8 = (tmp[tmpIdx+9] & MASK32_14) << 3;
+ l8 |= (tmp[tmpIdx+10] >>> 12) & MASK32_3;
+ longs[longsIdx+8] = l8;
+ long l9 = (tmp[tmpIdx+10] & MASK32_12) << 5;
+ l9 |= (tmp[tmpIdx+11] >>> 10) & MASK32_5;
+ longs[longsIdx+9] = l9;
+ long l10 = (tmp[tmpIdx+11] & MASK32_10) << 7;
+ l10 |= (tmp[tmpIdx+12] >>> 8) & MASK32_7;
+ longs[longsIdx+10] = l10;
+ long l11 = (tmp[tmpIdx+12] & MASK32_8) << 9;
+ l11 |= (tmp[tmpIdx+13] >>> 6) & MASK32_9;
+ longs[longsIdx+11] = l11;
+ long l12 = (tmp[tmpIdx+13] & MASK32_6) << 11;
+ l12 |= (tmp[tmpIdx+14] >>> 4) & MASK32_11;
+ longs[longsIdx+12] = l12;
+ long l13 = (tmp[tmpIdx+14] & MASK32_4) << 13;
+ l13 |= (tmp[tmpIdx+15] >>> 2) & MASK32_13;
+ longs[longsIdx+13] = l13;
+ long l14 = (tmp[tmpIdx+15] & MASK32_2) << 15;
+ l14 |= (tmp[tmpIdx+16] & MASK32_15) << 0;
+ longs[longsIdx+14] = l14;
+ }
+ }
+
+ private static void decode18(DataInput in, long[] tmp, long[] longs) throws IOException {
+ in.readLELongs(tmp, 0, 36);
+ shiftLongs(tmp, 36, longs, 0, 14, MASK32_18);
+ for (int iter = 0, tmpIdx = 0, longsIdx = 36; iter < 4; ++iter, tmpIdx += 9, longsIdx += 7) {
+ long l0 = (tmp[tmpIdx+0] & MASK32_14) << 4;
+ l0 |= (tmp[tmpIdx+1] >>> 10) & MASK32_4;
+ longs[longsIdx+0] = l0;
+ long l1 = (tmp[tmpIdx+1] & MASK32_10) << 8;
+ l1 |= (tmp[tmpIdx+2] >>> 6) & MASK32_8;
+ longs[longsIdx+1] = l1;
+ long l2 = (tmp[tmpIdx+2] & MASK32_6) << 12;
+ l2 |= (tmp[tmpIdx+3] >>> 2) & MASK32_12;
+ longs[longsIdx+2] = l2;
+ long l3 = (tmp[tmpIdx+3] & MASK32_2) << 16;
+ l3 |= (tmp[tmpIdx+4] & MASK32_14) << 2;
+ l3 |= (tmp[tmpIdx+5] >>> 12) & MASK32_2;
+ longs[longsIdx+3] = l3;
+ long l4 = (tmp[tmpIdx+5] & MASK32_12) << 6;
+ l4 |= (tmp[tmpIdx+6] >>> 8) & MASK32_6;
+ longs[longsIdx+4] = l4;
+ long l5 = (tmp[tmpIdx+6] & MASK32_8) << 10;
+ l5 |= (tmp[tmpIdx+7] >>> 4) & MASK32_10;
+ longs[longsIdx+5] = l5;
+ long l6 = (tmp[tmpIdx+7] & MASK32_4) << 14;
+ l6 |= (tmp[tmpIdx+8] & MASK32_14) << 0;
+ longs[longsIdx+6] = l6;
+ }
+ }
+
+ private static void decode19(DataInput in, long[] tmp, long[] longs) throws IOException {
+ in.readLELongs(tmp, 0, 38);
+ shiftLongs(tmp, 38, longs, 0, 13, MASK32_19);
+ for (int iter = 0, tmpIdx = 0, longsIdx = 38; iter < 2; ++iter, tmpIdx += 19, longsIdx += 13) {
+ long l0 = (tmp[tmpIdx+0] & MASK32_13) << 6;
+ l0 |= (tmp[tmpIdx+1] >>> 7) & MASK32_6;
+ longs[longsIdx+0] = l0;
+ long l1 = (tmp[tmpIdx+1] & MASK32_7) << 12;
+ l1 |= (tmp[tmpIdx+2] >>> 1) & MASK32_12;
+ longs[longsIdx+1] = l1;
+ long l2 = (tmp[tmpIdx+2] & MASK32_1) << 18;
+ l2 |= (tmp[tmpIdx+3] & MASK32_13) << 5;
+ l2 |= (tmp[tmpIdx+4] >>> 8) & MASK32_5;
+ longs[longsIdx+2] = l2;
+ long l3 = (tmp[tmpIdx+4] & MASK32_8) << 11;
+ l3 |= (tmp[tmpIdx+5] >>> 2) & MASK32_11;
+ longs[longsIdx+3] = l3;
+ long l4 = (tmp[tmpIdx+5] & MASK32_2) << 17;
+ l4 |= (tmp[tmpIdx+6] & MASK32_13) << 4;
+ l4 |= (tmp[tmpIdx+7] >>> 9) & MASK32_4;
+ longs[longsIdx+4] = l4;
+ long l5 = (tmp[tmpIdx+7] & MASK32_9) << 10;
+ l5 |= (tmp[tmpIdx+8] >>> 3) & MASK32_10;
+ longs[longsIdx+5] = l5;
+ long l6 = (tmp[tmpIdx+8] & MASK32_3) << 16;
+ l6 |= (tmp[tmpIdx+9] & MASK32_13) << 3;
+ l6 |= (tmp[tmpIdx+10] >>> 10) & MASK32_3;
+ longs[longsIdx+6] = l6;
+ long l7 = (tmp[tmpIdx+10] & MASK32_10) << 9;
+ l7 |= (tmp[tmpIdx+11] >>> 4) & MASK32_9;
+ longs[longsIdx+7] = l7;
+ long l8 = (tmp[tmpIdx+11] & MASK32_4) << 15;
+ l8 |= (tmp[tmpIdx+12] & MASK32_13) << 2;
+ l8 |= (tmp[tmpIdx+13] >>> 11) & MASK32_2;
+ longs[longsIdx+8] = l8;
+ long l9 = (tmp[tmpIdx+13] & MASK32_11) << 8;
+ l9 |= (tmp[tmpIdx+14] >>> 5) & MASK32_8;
+ longs[longsIdx+9] = l9;
+ long l10 = (tmp[tmpIdx+14] & MASK32_5) << 14;
+ l10 |= (tmp[tmpIdx+15] & MASK32_13) << 1;
+ l10 |= (tmp[tmpIdx+16] >>> 12) & MASK32_1;
+ longs[longsIdx+10] = l10;
+ long l11 = (tmp[tmpIdx+16] & MASK32_12) << 7;
+ l11 |= (tmp[tmpIdx+17] >>> 6) & MASK32_7;
+ longs[longsIdx+11] = l11;
+ long l12 = (tmp[tmpIdx+17] & MASK32_6) << 13;
+ l12 |= (tmp[tmpIdx+18] & MASK32_13) << 0;
+ longs[longsIdx+12] = l12;
+ }
+ }
+
+ private static void decode20(DataInput in, long[] tmp, long[] longs) throws IOException {
+ in.readLELongs(tmp, 0, 40);
+ shiftLongs(tmp, 40, longs, 0, 12, MASK32_20);
+ for (int iter = 0, tmpIdx = 0, longsIdx = 40; iter < 8; ++iter, tmpIdx += 5, longsIdx += 3) {
+ long l0 = (tmp[tmpIdx+0] & MASK32_12) << 8;
+ l0 |= (tmp[tmpIdx+1] >>> 4) & MASK32_8;
+ longs[longsIdx+0] = l0;
+ long l1 = (tmp[tmpIdx+1] & MASK32_4) << 16;
+ l1 |= (tmp[tmpIdx+2] & MASK32_12) << 4;
+ l1 |= (tmp[tmpIdx+3] >>> 8) & MASK32_4;
+ longs[longsIdx+1] = l1;
+ long l2 = (tmp[tmpIdx+3] & MASK32_8) << 12;
+ l2 |= (tmp[tmpIdx+4] & MASK32_12) << 0;
+ longs[longsIdx+2] = l2;
+ }
+ }
+
+ private static void decode21(DataInput in, long[] tmp, long[] longs) throws IOException {
+ in.readLELongs(tmp, 0, 42);
+ shiftLongs(tmp, 42, longs, 0, 11, MASK32_21);
+ for (int iter = 0, tmpIdx = 0, longsIdx = 42; iter < 2; ++iter, tmpIdx += 21, longsIdx += 11) {
+ long l0 = (tmp[tmpIdx+0] & MASK32_11) << 10;
+ l0 |= (tmp[tmpIdx+1] >>> 1) & MASK32_10;
+ longs[longsIdx+0] = l0;
+ long l1 = (tmp[tmpIdx+1] & MASK32_1) << 20;
+ l1 |= (tmp[tmpIdx+2] & MASK32_11) << 9;
+ l1 |= (tmp[tmpIdx+3] >>> 2) & MASK32_9;
+ longs[longsIdx+1] = l1;
+ long l2 = (tmp[tmpIdx+3] & MASK32_2) << 19;
+ l2 |= (tmp[tmpIdx+4] & MASK32_11) << 8;
+ l2 |= (tmp[tmpIdx+5] >>> 3) & MASK32_8;
+ longs[longsIdx+2] = l2;
+ long l3 = (tmp[tmpIdx+5] & MASK32_3) << 18;
+ l3 |= (tmp[tmpIdx+6] & MASK32_11) << 7;
+ l3 |= (tmp[tmpIdx+7] >>> 4) & MASK32_7;
+ longs[longsIdx+3] = l3;
+ long l4 = (tmp[tmpIdx+7] & MASK32_4) << 17;
+ l4 |= (tmp[tmpIdx+8] & MASK32_11) << 6;
+ l4 |= (tmp[tmpIdx+9] >>> 5) & MASK32_6;
+ longs[longsIdx+4] = l4;
+ long l5 = (tmp[tmpIdx+9] & MASK32_5) << 16;
+ l5 |= (tmp[tmpIdx+10] & MASK32_11) << 5;
+ l5 |= (tmp[tmpIdx+11] >>> 6) & MASK32_5;
+ longs[longsIdx+5] = l5;
+ long l6 = (tmp[tmpIdx+11] & MASK32_6) << 15;
+ l6 |= (tmp[tmpIdx+12] & MASK32_11) << 4;
+ l6 |= (tmp[tmpIdx+13] >>> 7) & MASK32_4;
+ longs[longsIdx+6] = l6;
+ long l7 = (tmp[tmpIdx+13] & MASK32_7) << 14;
+ l7 |= (tmp[tmpIdx+14] & MASK32_11) << 3;
+ l7 |= (tmp[tmpIdx+15] >>> 8) & MASK32_3;
+ longs[longsIdx+7] = l7;
+ long l8 = (tmp[tmpIdx+15] & MASK32_8) << 13;
+ l8 |= (tmp[tmpIdx+16] & MASK32_11) << 2;
+ l8 |= (tmp[tmpIdx+17] >>> 9) & MASK32_2;
+ longs[longsIdx+8] = l8;
+ long l9 = (tmp[tmpIdx+17] & MASK32_9) << 12;
+ l9 |= (tmp[tmpIdx+18] & MASK32_11) << 1;
+ l9 |= (tmp[tmpIdx+19] >>> 10) & MASK32_1;
+ longs[longsIdx+9] = l9;
+ long l10 = (tmp[tmpIdx+19] & MASK32_10) << 11;
+ l10 |= (tmp[tmpIdx+20] & MASK32_11) << 0;
+ longs[longsIdx+10] = l10;
+ }
+ }
+
+ private static void decode22(DataInput in, long[] tmp, long[] longs) throws IOException {
+ in.readLELongs(tmp, 0, 44);
+ shiftLongs(tmp, 44, longs, 0, 10, MASK32_22);
+ for (int iter = 0, tmpIdx = 0, longsIdx = 44; iter < 4; ++iter, tmpIdx += 11, longsIdx += 5) {
+ long l0 = (tmp[tmpIdx+0] & MASK32_10) << 12;
+ l0 |= (tmp[tmpIdx+1] & MASK32_10) << 2;
+ l0 |= (tmp[tmpIdx+2] >>> 8) & MASK32_2;
+ longs[longsIdx+0] = l0;
+ long l1 = (tmp[tmpIdx+2] & MASK32_8) << 14;
+ l1 |= (tmp[tmpIdx+3] & MASK32_10) << 4;
+ l1 |= (tmp[tmpIdx+4] >>> 6) & MASK32_4;
+ longs[longsIdx+1] = l1;
+ long l2 = (tmp[tmpIdx+4] & MASK32_6) << 16;
+ l2 |= (tmp[tmpIdx+5] & MASK32_10) << 6;
+ l2 |= (tmp[tmpIdx+6] >>> 4) & MASK32_6;
+ longs[longsIdx+2] = l2;
+ long l3 = (tmp[tmpIdx+6] & MASK32_4) << 18;
+ l3 |= (tmp[tmpIdx+7] & MASK32_10) << 8;
+ l3 |= (tmp[tmpIdx+8] >>> 2) & MASK32_8;
+ longs[longsIdx+3] = l3;
+ long l4 = (tmp[tmpIdx+8] & MASK32_2) << 20;
+ l4 |= (tmp[tmpIdx+9] & MASK32_10) << 10;
+ l4 |= (tmp[tmpIdx+10] & MASK32_10) << 0;
+ longs[longsIdx+4] = l4;
+ }
+ }
+
+ private static void decode23(DataInput in, long[] tmp, long[] longs) throws IOException {
+ in.readLELongs(tmp, 0, 46);
+ shiftLongs(tmp, 46, longs, 0, 9, MASK32_23);
+ for (int iter = 0, tmpIdx = 0, longsIdx = 46; iter < 2; ++iter, tmpIdx += 23, longsIdx += 9) {
+ long l0 = (tmp[tmpIdx+0] & MASK32_9) << 14;
+ l0 |= (tmp[tmpIdx+1] & MASK32_9) << 5;
+ l0 |= (tmp[tmpIdx+2] >>> 4) & MASK32_5;
+ longs[longsIdx+0] = l0;
+ long l1 = (tmp[tmpIdx+2] & MASK32_4) << 19;
+ l1 |= (tmp[tmpIdx+3] & MASK32_9) << 10;
+ l1 |= (tmp[tmpIdx+4] & MASK32_9) << 1;
+ l1 |= (tmp[tmpIdx+5] >>> 8) & MASK32_1;
+ longs[longsIdx+1] = l1;
+ long l2 = (tmp[tmpIdx+5] & MASK32_8) << 15;
+ l2 |= (tmp[tmpIdx+6] & MASK32_9) << 6;
+ l2 |= (tmp[tmpIdx+7] >>> 3) & MASK32_6;
+ longs[longsIdx+2] = l2;
+ long l3 = (tmp[tmpIdx+7] & MASK32_3) << 20;
+ l3 |= (tmp[tmpIdx+8] & MASK32_9) << 11;
+ l3 |= (tmp[tmpIdx+9] & MASK32_9) << 2;
+ l3 |= (tmp[tmpIdx+10] >>> 7) & MASK32_2;
+ longs[longsIdx+3] = l3;
+ long l4 = (tmp[tmpIdx+10] & MASK32_7) << 16;
+ l4 |= (tmp[tmpIdx+11] & MASK32_9) << 7;
+ l4 |= (tmp[tmpIdx+12] >>> 2) & MASK32_7;
+ longs[longsIdx+4] = l4;
+ long l5 = (tmp[tmpIdx+12] & MASK32_2) << 21;
+ l5 |= (tmp[tmpIdx+13] & MASK32_9) << 12;
+ l5 |= (tmp[tmpIdx+14] & MASK32_9) << 3;
+ l5 |= (tmp[tmpIdx+15] >>> 6) & MASK32_3;
+ longs[longsIdx+5] = l5;
+ long l6 = (tmp[tmpIdx+15] & MASK32_6) << 17;
+ l6 |= (tmp[tmpIdx+16] & MASK32_9) << 8;
+ l6 |= (tmp[tmpIdx+17] >>> 1) & MASK32_8;
+ longs[longsIdx+6] = l6;
+ long l7 = (tmp[tmpIdx+17] & MASK32_1) << 22;
+ l7 |= (tmp[tmpIdx+18] & MASK32_9) << 13;
+ l7 |= (tmp[tmpIdx+19] & MASK32_9) << 4;
+ l7 |= (tmp[tmpIdx+20] >>> 5) & MASK32_4;
+ longs[longsIdx+7] = l7;
+ long l8 = (tmp[tmpIdx+20] & MASK32_5) << 18;
+ l8 |= (tmp[tmpIdx+21] & MASK32_9) << 9;
+ l8 |= (tmp[tmpIdx+22] & MASK32_9) << 0;
+ longs[longsIdx+8] = l8;
+ }
+ }
+
+ private static void decode24(DataInput in, long[] tmp, long[] longs) throws IOException {
+ in.readLELongs(tmp, 0, 48);
+ shiftLongs(tmp, 48, longs, 0, 8, MASK32_24);
+ for (int iter = 0, tmpIdx = 0, longsIdx = 48; iter < 16; ++iter, tmpIdx += 3, longsIdx += 1) {
+ long l0 = (tmp[tmpIdx+0] & MASK32_8) << 16;
+ l0 |= (tmp[tmpIdx+1] & MASK32_8) << 8;
+ l0 |= (tmp[tmpIdx+2] & MASK32_8) << 0;
+ longs[longsIdx+0] = l0;
+ }
+ }
+
+}
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene80/Lucene80Codec.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene84/Lucene84Codec.java
similarity index 90%
rename from lucene/core/src/java/org/apache/lucene/codecs/lucene80/Lucene80Codec.java
rename to lucene/core/src/java/org/apache/lucene/codecs/lucene84/Lucene84Codec.java
index 9abb1ebab55..e3f061ad27c 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene80/Lucene80Codec.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene84/Lucene84Codec.java
@@ -14,7 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.lucene.codecs.lucene80;
+package org.apache.lucene.codecs.lucene84;
import java.util.Objects;
@@ -32,28 +32,28 @@ import org.apache.lucene.codecs.StoredFieldsFormat;
import org.apache.lucene.codecs.TermVectorsFormat;
import org.apache.lucene.codecs.lucene50.Lucene50CompoundFormat;
import org.apache.lucene.codecs.lucene50.Lucene50LiveDocsFormat;
-import org.apache.lucene.codecs.lucene50.Lucene50PostingsFormat;
import org.apache.lucene.codecs.lucene50.Lucene50StoredFieldsFormat;
import org.apache.lucene.codecs.lucene50.Lucene50StoredFieldsFormat.Mode;
import org.apache.lucene.codecs.lucene50.Lucene50TermVectorsFormat;
import org.apache.lucene.codecs.lucene60.Lucene60FieldInfosFormat;
import org.apache.lucene.codecs.lucene60.Lucene60PointsFormat;
import org.apache.lucene.codecs.lucene70.Lucene70SegmentInfoFormat;
+import org.apache.lucene.codecs.lucene80.Lucene80NormsFormat;
import org.apache.lucene.codecs.perfield.PerFieldDocValuesFormat;
import org.apache.lucene.codecs.perfield.PerFieldPostingsFormat;
/**
- * Implements the Lucene 8.0 index format, with configurable per-field postings
+ * Implements the Lucene 8.4 index format, with configurable per-field postings
* and docvalues formats.
* <p>
* If you want to reuse functionality of this codec in another codec, extend
* {@link FilterCodec}.
*
- * @see org.apache.lucene.codecs.lucene80 package documentation for file format details.
+ * @see org.apache.lucene.codecs.lucene84 package documentation for file format details.
*
* @lucene.experimental
*/
-public class Lucene80Codec extends Codec {
+public class Lucene84Codec extends Codec {
private final TermVectorsFormat vectorsFormat = new Lucene50TermVectorsFormat();
private final FieldInfosFormat fieldInfosFormat = new Lucene60FieldInfosFormat();
private final SegmentInfoFormat segmentInfosFormat = new Lucene70SegmentInfoFormat();
@@ -64,14 +64,14 @@ public class Lucene80Codec extends Codec {
private final PostingsFormat postingsFormat = new PerFieldPostingsFormat() {
@Override
public PostingsFormat getPostingsFormatForField(String field) {
- return Lucene80Codec.this.getPostingsFormatForField(field);
+ return Lucene84Codec.this.getPostingsFormatForField(field);
}
};
private final DocValuesFormat docValuesFormat = new PerFieldDocValuesFormat() {
@Override
public DocValuesFormat getDocValuesFormatForField(String field) {
- return Lucene80Codec.this.getDocValuesFormatForField(field);
+ return Lucene84Codec.this.getDocValuesFormatForField(field);
}
};
@@ -80,7 +80,7 @@ public class Lucene80Codec extends Codec {
/**
* Instantiates a new codec.
*/
- public Lucene80Codec() {
+ public Lucene84Codec() {
this(Mode.BEST_SPEED);
}
@@ -90,10 +90,10 @@ public class Lucene80Codec extends Codec {
* @param mode stored fields compression mode to use for newly
* flushed/merged segments.
*/
- public Lucene80Codec(Mode mode) {
- super("Lucene80");
+ public Lucene84Codec(Mode mode) {
+ super("Lucene84");
this.storedFieldsFormat = new Lucene50StoredFieldsFormat(Objects.requireNonNull(mode));
- this.defaultFormat = new Lucene50PostingsFormat();
+ this.defaultFormat = new Lucene84PostingsFormat();
}
@Override
@@ -139,7 +139,7 @@ public class Lucene80Codec extends Codec {
/** Returns the postings format that should be used for writing
* new segments of <code>field</code>.
*
- * The default implementation always returns "Lucene50".
+ * The default implementation always returns "Lucene84".
* <p>
* <b>WARNING:</b> if you subclass, you are responsible for index
* backwards compatibility: future version of Lucene are only
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene84/Lucene84PostingsFormat.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene84/Lucene84PostingsFormat.java
new file mode 100644
index 00000000000..c069ef0f457
--- /dev/null
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene84/Lucene84PostingsFormat.java
@@ -0,0 +1,506 @@
+/*
+ * 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.
+ */
+package org.apache.lucene.codecs.lucene84;
+
+import java.io.IOException;
+
+import org.apache.lucene.codecs.BlockTermState;
+import org.apache.lucene.codecs.CodecUtil;
+import org.apache.lucene.codecs.FieldsConsumer;
+import org.apache.lucene.codecs.FieldsProducer;
+import org.apache.lucene.codecs.MultiLevelSkipListWriter;
+import org.apache.lucene.codecs.PostingsFormat;
+import org.apache.lucene.codecs.PostingsReaderBase;
+import org.apache.lucene.codecs.PostingsWriterBase;
+import org.apache.lucene.codecs.blocktree.BlockTreeTermsReader;
+import org.apache.lucene.codecs.blocktree.BlockTreeTermsWriter;
+import org.apache.lucene.index.IndexOptions;
+import org.apache.lucene.index.SegmentReadState;
+import org.apache.lucene.index.SegmentWriteState;
+import org.apache.lucene.index.TermState;
+import org.apache.lucene.store.DataOutput;
+import org.apache.lucene.util.IOUtils;
+import org.apache.lucene.util.packed.PackedInts;
+
+/**
+ * Lucene 5.0 postings format, which encodes postings in packed integer blocks
+ * for fast decode.
+ *
+ * <p>
+ * Basic idea:
+ * <ul>
+ * <li>
+ * <b>Packed Blocks and VInt Blocks</b>:
+ * <p>In packed blocks, integers are encoded with the same bit width ({@link PackedInts packed format}):
+ * the block size (i.e. number of integers inside block) is fixed (currently 128). Additionally blocks
+ * that are all the same value are encoded in an optimized way.</p>
+ * <p>In VInt blocks, integers are encoded as {@link DataOutput#writeVInt VInt}:
+ * the block size is variable.</p>
+ * </li>
+ *
+ * <li>
+ * <b>Block structure</b>:
+ * <p>When the postings are long enough, Lucene84PostingsFormat will try to encode most integer data
+ * as a packed block.</p>
+ * <p>Take a term with 259 documents as an example, the first 256 document ids are encoded as two packed
+ * blocks, while the remaining 3 are encoded as one VInt block. </p>
+ * <p>Different kinds of data are always encoded separately into different packed blocks, but may
+ * possibly be interleaved into the same VInt block. </p>
+ * <p>This strategy is applied to pairs:
+ * &lt;document number, frequency&gt;,
+ * &lt;position, payload length&gt;,
+ * &lt;position, offset start, offset length&gt;, and
+ * &lt;position, payload length, offsetstart, offset length&gt;.</p>
+ * </li>
+ *
+ * <li>
+ * <b>Skipdata settings</b>:
+ * <p>The structure of skip table is quite similar to previous version of Lucene. Skip interval is the
+ * same as block size, and each skip entry points to the beginning of each block. However, for
+ * the first block, skip data is omitted.</p>
+ * </li>
+ *
+ * <li>
+ * <b>Positions, Payloads, and Offsets</b>:
+ * <p>A position is an integer indicating where the term occurs within one document.
+ * A payload is a blob of metadata associated with current position.
+ * An offset is a pair of integers indicating the tokenized start/end offsets for given term
+ * in current position: it is essentially a specialized payload. </p>
+ * <p>When payloads and offsets are not omitted, numPositions==numPayloads==numOffsets (assuming a
+ * null payload contributes one count). As mentioned in block structure, it is possible to encode
+ * these three either combined or separately.
+ * <p>In all cases, payloads and offsets are stored together. When encoded as a packed block,
+ * position data is separated out as .pos, while payloads and offsets are encoded in .pay (payload
+ * metadata will also be stored directly in .pay). When encoded as VInt blocks, all these three are
+ * stored interleaved into the .pos (so is payload metadata).</p>
+ * <p>With this strategy, the majority of payload and offset data will be outside .pos file.
+ * So for queries that require only position data, running on a full index with payloads and offsets,
+ * this reduces disk pre-fetches.</p>
+ * </li>
+ * </ul>
+ *
+ * <p>
+ * Files and detailed format:
+ * <ul>
+ * <li><tt>.tim</tt>: <a href="#Termdictionary">Term Dictionary</a></li>
+ * <li><tt>.tip</tt>: <a href="#Termindex">Term Index</a></li>
+ * <li><tt>.doc</tt>: <a href="#Frequencies">Frequencies and Skip Data</a></li>
+ * <li><tt>.pos</tt>: <a href="#Positions">Positions</a></li>
+ * <li><tt>.pay</tt>: <a href="#Payloads">Payloads and Offsets</a></li>
+ * </ul>
+ *
+ * <a name="Termdictionary"></a>
+ * <dl>
+ * <dd>
+ * <b>Term Dictionary</b>
+ *
+ * <p>The .tim file contains the list of terms in each
+ * field along with per-term statistics (such as docfreq)
+ * and pointers to the frequencies, positions, payload and
+ * skip data in the .doc, .pos, and .pay files.
+ * See {@link BlockTreeTermsWriter} for more details on the format.
+ *
+ * <p>NOTE: The term dictionary can plug into different postings implementations:
+ * the postings writer/reader are actually responsible for encoding
+ * and decoding the PostingsHeader and TermMetadata sections described here:
+ *
+ * <ul>
+ * <li>PostingsHeader --&gt; Header, PackedBlockSize</li>
+ * <li>TermMetadata --&gt; (DocFPDelta|SingletonDocID), PosFPDelta?, PosVIntBlockFPDelta?, PayFPDelta?,
+ * SkipFPDelta?</li>
+ * <li>Header, --&gt; {@link CodecUtil#writeIndexHeader IndexHeader}</li>
+ * <li>PackedBlockSize, SingletonDocID --&gt; {@link DataOutput#writeVInt VInt}</li>
+ * <li>DocFPDelta, PosFPDelta, PayFPDelta, PosVIntBlockFPDelta, SkipFPDelta --&gt; {@link DataOutput#writeVLong VLong}</li>
+ * <li>Footer --&gt; {@link CodecUtil#writeFooter CodecFooter}</li>
+ * </ul>
+ * <p>Notes:
+ * <ul>
+ * <li>Header is a {@link CodecUtil#writeIndexHeader IndexHeader} storing the version information
+ * for the postings.</li>
+ * <li>PackedBlockSize is the fixed block size for packed blocks. In packed block, bit width is
+ * determined by the largest integer. Smaller block size result in smaller variance among width
+ * of integers hence smaller indexes. Larger block size result in more efficient bulk i/o hence
+ * better acceleration. This value should always be a multiple of 64, currently fixed as 128 as
+ * a tradeoff. It is also the skip interval used to accelerate {@link org.apache.lucene.index.PostingsEnum#advance(int)}.
+ * <li>DocFPDelta determines the position of this term's TermFreqs within the .doc file.
+ * In particular, it is the difference of file offset between this term's
+ * data and previous term's data (or zero, for the first term in the block).On disk it is
+ * stored as the difference from previous value in sequence. </li>
+ * <li>PosFPDelta determines the position of this term's TermPositions within the .pos file.
+ * While PayFPDelta determines the position of this term's &lt;TermPayloads, TermOffsets?&gt; within
+ * the .pay file. Similar to DocFPDelta, it is the difference between two file positions (or
+ * neglected, for fields that omit payloads and offsets).</li>
+ * <li>PosVIntBlockFPDelta determines the position of this term's last TermPosition in last pos packed
+ * block within the .pos file. It is synonym for PayVIntBlockFPDelta or OffsetVIntBlockFPDelta.
+ * This is actually used to indicate whether it is necessary to load following
+ * payloads and offsets from .pos instead of .pay. Every time a new block of positions are to be
+ * loaded, the PostingsReader will use this value to check whether current block is packed format
+ * or VInt. When packed format, payloads and offsets are fetched from .pay, otherwise from .pos.
+ * (this value is neglected when total number of positions i.e. totalTermFreq is less or equal
+ * to PackedBlockSize).
+ * <li>SkipFPDelta determines the position of this term's SkipData within the .doc
+ * file. In particular, it is the length of the TermFreq data.
+ * SkipDelta is only stored if DocFreq is not smaller than SkipMinimum
+ * (i.e. 128 in Lucene84PostingsFormat).</li>
+ * <li>SingletonDocID is an optimization when a term only appears in one document. In this case, instead
+ * of writing a file pointer to the .doc file (DocFPDelta), and then a VIntBlock at that location, the
+ * single document ID is written to the term dictionary.</li>
+ * </ul>
+ * </dd>
+ * </dl>
+ *
+ * <a name="Termindex"></a>
+ * <dl>
+ * <dd>
+ * <b>Term Index</b>
+ * <p>The .tip file contains an index into the term dictionary, so that it can be
+ * accessed randomly. See {@link BlockTreeTermsWriter} for more details on the format.
+ * </dd>
+ * </dl>
+ *
+ *
+ * <a name="Frequencies"></a>
+ * <dl>
+ * <dd>
+ * <b>Frequencies and Skip Data</b>
+ *
+ * <p>The .doc file contains the lists of documents which contain each term, along
+ * with the frequency of the term in that document (except when frequencies are
+ * omitted: {@link IndexOptions#DOCS}). It also saves skip data to the beginning of
+ * each packed or VInt block, when the length of document list is larger than packed block size.</p>
+ *
+ * <ul>
+ * <li>docFile(.doc) --&gt; Header, &lt;TermFreqs, SkipData?&gt;<sup>TermCount</sup>, Footer</li>
+ * <li>Header --&gt; {@link CodecUtil#writeIndexHeader IndexHeader}</li>
+ * <li>TermFreqs --&gt; &lt;PackedBlock&gt; <sup>PackedDocBlockNum</sup>,
+ * VIntBlock? </li>
+ * <li>PackedBlock --&gt; PackedDocDeltaBlock, PackedFreqBlock?
+ * <li>VIntBlock --&gt; &lt;DocDelta[, Freq?]&gt;<sup>DocFreq-PackedBlockSize*PackedDocBlockNum</sup>
+ * <li>SkipData --&gt; &lt;&lt;SkipLevelLength, SkipLevel&gt;
+ * <sup>NumSkipLevels-1</sup>, SkipLevel&gt;, SkipDatum?</li>
+ * <li>SkipLevel --&gt; &lt;SkipDatum&gt; <sup>TrimmedDocFreq/(PackedBlockSize^(Level + 1))</sup></li>
+ * <li>SkipDatum --&gt; DocSkip, DocFPSkip, &lt;PosFPSkip, PosBlockOffset, PayLength?,
+ * PayFPSkip?&gt;?, SkipChildLevelPointer?</li>
+ * <li>PackedDocDeltaBlock, PackedFreqBlock --&gt; {@link PackedInts PackedInts}</li>
+ * <li>DocDelta, Freq, DocSkip, DocFPSkip, PosFPSkip, PosBlockOffset, PayByteUpto, PayFPSkip
+ * --&gt;
+ * {@link DataOutput#writeVInt VInt}</li>
+ * <li>SkipChildLevelPointer --&gt; {@link DataOutput#writeVLong VLong}</li>
+ * <li>Footer --&gt; {@link CodecUtil#writeFooter CodecFooter}</li>
+ * </ul>
+ * <p>Notes:
+ * <ul>
+ * <li>PackedDocDeltaBlock is theoretically generated from two steps:
+ * <ol>
+ * <li>Calculate the difference between each document number and previous one,
+ * and get a d-gaps list (for the first document, use absolute value); </li>
+ * <li>For those d-gaps from first one to PackedDocBlockNum*PackedBlockSize<sup>th</sup>,
+ * separately encode as packed blocks.</li>
+ * </ol>
+ * If frequencies are not omitted, PackedFreqBlock will be generated without d-gap step.
+ * </li>
+ * <li>VIntBlock stores remaining d-gaps (along with frequencies when possible) with a format
+ * that encodes DocDelta and Freq:
+ * <p>DocDelta: if frequencies are indexed, this determines both the document
+ * number and the frequency. In particular, DocDelta/2 is the difference between
+ * this document number and the previous document number (or zero when this is the
+ * first document in a TermFreqs). When DocDelta is odd, the frequency is one.
+ * When DocDelta is even, the frequency is read as another VInt. If frequencies
+ * are omitted, DocDelta contains the gap (not multiplied by 2) between document
+ * numbers and no frequency information is stored.</p>
+ * <p>For example, the TermFreqs for a term which occurs once in document seven
+ * and three times in document eleven, with frequencies indexed, would be the
+ * following sequence of VInts:</p>
+ * <p>15, 8, 3</p>
+ * <p>If frequencies were omitted ({@link IndexOptions#DOCS}) it would be this
+ * sequence of VInts instead:</p>
+ * <p>7,4</p>
+ * </li>
+ * <li>PackedDocBlockNum is the number of packed blocks for current term's docids or frequencies.
+ * In particular, PackedDocBlockNum = floor(DocFreq/PackedBlockSize) </li>
+ * <li>TrimmedDocFreq = DocFreq % PackedBlockSize == 0 ? DocFreq - 1 : DocFreq.
+ * We use this trick since the definition of skip entry is a little different from base interface.
+ * In {@link MultiLevelSkipListWriter}, skip data is assumed to be saved for
+ * skipInterval<sup>th</sup>, 2*skipInterval<sup>th</sup> ... posting in the list. However,
+ * in Lucene84PostingsFormat, the skip data is saved for skipInterval+1<sup>th</sup>,
+ * 2*skipInterval+1<sup>th</sup> ... posting (skipInterval==PackedBlockSize in this case).
+ * When DocFreq is multiple of PackedBlockSize, MultiLevelSkipListWriter will expect one
+ * more skip data than Lucene84SkipWriter. </li>
+ * <li>SkipDatum is the metadata of one skip entry.
+ * For the first block (no matter packed or VInt), it is omitted.</li>
+ * <li>DocSkip records the document number of every PackedBlockSize<sup>th</sup> document number in
+ * the postings (i.e. last document number in each packed block). On disk it is stored as the
+ * difference from previous value in the sequence. </li>
+ * <li>DocFPSkip records the file offsets of each block (excluding )posting at
+ * PackedBlockSize+1<sup>th</sup>, 2*PackedBlockSize+1<sup>th</sup> ... , in DocFile.
+ * The file offsets are relative to the start of current term's TermFreqs.
+ * On disk it is also stored as the difference from previous SkipDatum in the sequence.</li>
+ * <li>Since positions and payloads are also block encoded, the skip should skip to related block first,
+ * then fetch the values according to in-block offset. PosFPSkip and PayFPSkip record the file
+ * offsets of related block in .pos and .pay, respectively. While PosBlockOffset indicates
+ * which value to fetch inside the related block (PayBlockOffset is unnecessary since it is always
+ * equal to PosBlockOffset). Same as DocFPSkip, the file offsets are relative to the start of
+ * current term's TermFreqs, and stored as a difference sequence.</li>
+ * <li>PayByteUpto indicates the start offset of the current payload. It is equivalent to
+ * the sum of the payload lengths in the current block up to PosBlockOffset</li>
+ * </ul>
+ * </dd>
+ * </dl>
+ *
+ * <a name="Positions"></a>
+ * <dl>
+ * <dd>
+ * <b>Positions</b>
+ * <p>The .pos file contains the lists of positions that each term occurs at within documents. It also
+ * sometimes stores part of payloads and offsets for speedup.</p>
+ * <ul>
+ * <li>PosFile(.pos) --&gt; Header, &lt;TermPositions&gt; <sup>TermCount</sup>, Footer</li>
+ * <li>Header --&gt; {@link CodecUtil#writeIndexHeader IndexHeader}</li>
+ * <li>TermPositions --&gt; &lt;PackedPosDeltaBlock&gt; <sup>PackedPosBlockNum</sup>,
+ * VIntBlock? </li>
+ * <li>VIntBlock --&gt; &lt;PositionDelta[, PayloadLength?], PayloadData?,
+ * OffsetDelta?, OffsetLength?&gt;<sup>PosVIntCount</sup>
+ * <li>PackedPosDeltaBlock --&gt; {@link PackedInts PackedInts}</li>
+ * <li>PositionDelta, OffsetDelta, OffsetLength --&gt;
+ * {@link DataOutput#writeVInt VInt}</li>
+ * <li>PayloadData --&gt; {@link DataOutput#writeByte byte}<sup>PayLength</sup></li>
+ * <li>Footer --&gt; {@link CodecUtil#writeFooter CodecFooter}</li>
+ * </ul>
+ * <p>Notes:
+ * <ul>
+ * <li>TermPositions are order by term (terms are implicit, from the term dictionary), and position
+ * values for each term document pair are incremental, and ordered by document number.</li>
+ * <li>PackedPosBlockNum is the number of packed blocks for current term's positions, payloads or offsets.
+ * In particular, PackedPosBlockNum = floor(totalTermFreq/PackedBlockSize) </li>
+ * <li>PosVIntCount is the number of positions encoded as VInt format. In particular,
+ * PosVIntCount = totalTermFreq - PackedPosBlockNum*PackedBlockSize</li>
+ * <li>The procedure how PackedPosDeltaBlock is generated is the same as PackedDocDeltaBlock
+ * in chapter <a href="#Frequencies">Frequencies and Skip Data</a>.</li>
+ * <li>PositionDelta is, if payloads are disabled for the term's field, the
+ * difference between the position of the current occurrence in the document and
+ * the previous occurrence (or zero, if this is the first occurrence in this
+ * document). If payloads are enabled for the term's field, then PositionDelta/2
+ * is the difference between the current and the previous position. If payloads
+ * are enabled and PositionDelta is odd, then PayloadLength is stored, indicating
+ * the length of the payload at the current term position.</li>
+ * <li>For example, the TermPositions for a term which occurs as the fourth term in
+ * one document, and as the fifth and ninth term in a subsequent document, would
+ * be the following sequence of VInts (payloads disabled):
+ * <p>4, 5, 4</p></li>
+ * <li>PayloadData is metadata associated with the current term position. If
+ * PayloadLength is stored at the current position, then it indicates the length
+ * of this payload. If PayloadLength is not stored, then this payload has the same
+ * length as the payload at the previous position.</li>
+ * <li>OffsetDelta/2 is the difference between this position's startOffset from the
+ * previous occurrence (or zero, if this is the first occurrence in this document).
+ * If OffsetDelta is odd, then the length (endOffset-startOffset) differs from the
+ * previous occurrence and an OffsetLength follows. Offset data is only written for
+ * {@link IndexOptions#DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS}.</li>
+ * </ul>
+ * </dd>
+ * </dl>
+ *
+ * <a name="Payloads"></a>
+ * <dl>
+ * <dd>
+ * <b>Payloads and Offsets</b>
+ * <p>The .pay file will store payloads and offsets associated with certain term-document positions.
+ * Some payloads and offsets will be separated out into .pos file, for performance reasons.
+ * <ul>
+ * <li>PayFile(.pay): --&gt; Header, &lt;TermPayloads, TermOffsets?&gt; <sup>TermCount</sup>, Footer</li>
+ * <li>Header --&gt; {@link CodecUtil#writeIndexHeader IndexHeader}</li>
+ * <li>TermPayloads --&gt; &lt;PackedPayLengthBlock, SumPayLength, PayData&gt; <sup>PackedPayBlockNum</sup>
+ * <li>TermOffsets --&gt; &lt;PackedOffsetStartDeltaBlock, PackedOffsetLengthBlock&gt; <sup>PackedPayBlockNum</sup>
+ * <li>PackedPayLengthBlock, PackedOffsetStartDeltaBlock, PackedOffsetLengthBlock --&gt; {@link PackedInts PackedInts}</li>
+ * <li>SumPayLength --&gt; {@link DataOutput#writeVInt VInt}</li>
+ * <li>PayData --&gt; {@link DataOutput#writeByte byte}<sup>SumPayLength</sup></li>
+ * <li>Footer --&gt; {@link CodecUtil#writeFooter CodecFooter}</li>
+ * </ul>
+ * <p>Notes:
+ * <ul>
+ * <li>The order of TermPayloads/TermOffsets will be the same as TermPositions, note that part of
+ * payload/offsets are stored in .pos.</li>
+ * <li>The procedure how PackedPayLengthBlock and PackedOffsetLengthBlock are generated is the
+ * same as PackedFreqBlock in chapter <a href="#Frequencies">Frequencies and Skip Data</a>.
+ * While PackedStartDeltaBlock follows a same procedure as PackedDocDeltaBlock.</li>
+ * <li>PackedPayBlockNum is always equal to PackedPosBlockNum, for the same term. It is also synonym
+ * for PackedOffsetBlockNum.</li>
+ * <li>SumPayLength is the total length of payloads written within one block, should be the sum
+ * of PayLengths in one packed block.</li>
+ * <li>PayLength in PackedPayLengthBlock is the length of each payload associated with the current
+ * position.</li>
+ * </ul>
+ * </dd>
+ * </dl>
+ *
+ * @lucene.experimental
+ */
+
+public final class Lucene84PostingsFormat extends PostingsFormat {
+
+ /**
+ * Filename extension for document number, frequencies, and skip data.
+ * See chapter: <a href="#Frequencies">Frequencies and Skip Data</a>
+ */
+ public static final String DOC_EXTENSION = "doc";
+
+ /**
+ * Filename extension for positions.
+ * See chapter: <a href="#Positions">Positions</a>
+ */
+ public static final String POS_EXTENSION = "pos";
+
+ /**
+ * Filename extension for payloads and offsets.
+ * See chapter: <a href="#Payloads">Payloads and Offsets</a>
+ */
+ public static final String PAY_EXTENSION = "pay";
+
+ /** Size of blocks. */
+ public static final int BLOCK_SIZE = ForUtil.BLOCK_SIZE;
+
+ /**
+ * Expert: The maximum number of skip levels. Smaller values result in
+ * slightly smaller indexes, but slower skipping in big posting lists.
+ */
+ static final int MAX_SKIP_LEVELS = 10;
+
+ final static String TERMS_CODEC = "Lucene84PostingsWriterTerms";
+ final static String DOC_CODEC = "Lucene84PostingsWriterDoc";
+ final static String POS_CODEC = "Lucene84PostingsWriterPos";
+ final static String PAY_CODEC = "Lucene84PostingsWriterPay";
+
+ // Increment version to change it
+ final static int VERSION_START = 0;
+ final static int VERSION_CURRENT = VERSION_START;
+
+ private final int minTermBlockSize;
+ private final int maxTermBlockSize;
+
+ private final BlockTreeTermsReader.FSTLoadMode fstLoadMode;
+
+ /** Creates {@code Lucene84PostingsFormat} with default
+ * settings. */
+ public Lucene84PostingsFormat() {
+ this(BlockTreeTermsWriter.DEFAULT_MIN_BLOCK_SIZE, BlockTreeTermsWriter.DEFAULT_MAX_BLOCK_SIZE, BlockTreeTermsReader.FSTLoadMode.AUTO);
+ }
+
+ /** Creates {@code Lucene84PostingsFormat} with custom
+ * values for {@code minBlockSize} and {@code
+ * maxBlockSize} passed to block terms dictionary.
+ * @see BlockTreeTermsWriter#BlockTreeTermsWriter(SegmentWriteState,PostingsWriterBase,int,int) */
+ public Lucene84PostingsFormat(int minTermBlockSize, int maxTermBlockSize, BlockTreeTermsReader.FSTLoadMode loadMode) {
+ super("Lucene84");
+ BlockTreeTermsWriter.validateSettings(minTermBlockSize, maxTermBlockSize);
+ this.minTermBlockSize = minTermBlockSize;
+ this.maxTermBlockSize = maxTermBlockSize;
+ this.fstLoadMode = loadMode;
+ }
+
+ @Override
+ public String toString() {
+ return getName();
+ }
+
+ @Override
+ public FieldsConsumer fieldsConsumer(SegmentWriteState state) throws IOException {
+ PostingsWriterBase postingsWriter = new Lucene84PostingsWriter(state);
+ boolean success = false;
+ try {
+ FieldsConsumer ret = new BlockTreeTermsWriter(state,
+ postingsWriter,
+ minTermBlockSize,
+ maxTermBlockSize);
+ success = true;
+ return ret;
+ } finally {
+ if (!success) {
+ IOUtils.closeWhileHandlingException(postingsWriter);
+ }
+ }
+ }
+
+ @Override
+ public FieldsProducer fieldsProducer(SegmentReadState state) throws IOException {
+ PostingsReaderBase postingsReader = new Lucene84PostingsReader(state);
+ boolean success = false;
+ try {
+ FieldsProducer ret = new BlockTreeTermsReader(postingsReader, state, fstLoadMode);
+ success = true;
+ return ret;
+ } finally {
+ if (!success) {
+ IOUtils.closeWhileHandlingException(postingsReader);
+ }
+ }
+ }
+
+ /**
+ * Holds all state required for {@link Lucene84PostingsReader} to produce a
+ * {@link org.apache.lucene.index.PostingsEnum} without re-seeking the terms dict.
+ *
+ * @lucene.internal
+ */
+ public static final class IntBlockTermState extends BlockTermState {
+ /** file pointer to the start of the doc ids enumeration, in {@link #DOC_EXTENSION} file */
+ public long docStartFP;
+ /** file pointer to the start of the positions enumeration, in {@link #POS_EXTENSION} file */
+ public long posStartFP;
+ /** file pointer to the start of the payloads enumeration, in {@link #PAY_EXTENSION} file */
+ public long payStartFP;
+ /** file offset for the start of the skip list, relative to docStartFP, if there are more
+ * than {@link ForUtil#BLOCK_SIZE} docs; otherwise -1 */
+ public long skipOffset;
+ /** file offset for the last position in the last block, if there are more than
+ * {@link ForUtil#BLOCK_SIZE} positions; otherwise -1 */
+ public long lastPosBlockOffset;
+ /** docid when there is a single pulsed posting, otherwise -1.
+ * freq is always implicitly totalTermFreq in this case. */
+ public int singletonDocID;
+
+ /** Sole constructor. */
+ public IntBlockTermState() {
+ skipOffset = -1;
+ lastPosBlockOffset = -1;
+ singletonDocID = -1;
+ }
+
+ @Override
+ public IntBlockTermState clone() {
+ IntBlockTermState other = new IntBlockTermState();
+ other.copyFrom(this);
+ return other;
+ }
+
+ @Override
+ public void copyFrom(TermState _other) {
+ super.copyFrom(_other);
+ IntBlockTermState other = (IntBlockTermState) _other;
+ docStartFP = other.docStartFP;
+ posStartFP = other.posStartFP;
+ payStartFP = other.payStartFP;
+ lastPosBlockOffset = other.lastPosBlockOffset;
+ skipOffset = other.skipOffset;
+ singletonDocID = other.singletonDocID;
+ }
+
+ @Override
+ public String toString() {
+ return super.toString() + " docStartFP=" + docStartFP + " posStartFP=" + posStartFP + " payStartFP=" + payStartFP + " lastPosBlockOffset=" + lastPosBlockOffset + " singletonDocID=" + singletonDocID;
+ }
+ }
+}
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene84/Lucene84PostingsReader.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene84/Lucene84PostingsReader.java
new file mode 100644
index 00000000000..c49b0cedbd5
--- /dev/null
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene84/Lucene84PostingsReader.java
@@ -0,0 +1,1966 @@
+/*
+ * 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.
+ */
+package org.apache.lucene.codecs.lucene84;
+
+
+import static org.apache.lucene.codecs.lucene84.ForUtil.BLOCK_SIZE;
+import static org.apache.lucene.codecs.lucene84.Lucene84PostingsFormat.DOC_CODEC;
+import static org.apache.lucene.codecs.lucene84.Lucene84PostingsFormat.MAX_SKIP_LEVELS;
+import static org.apache.lucene.codecs.lucene84.Lucene84PostingsFormat.PAY_CODEC;
+import static org.apache.lucene.codecs.lucene84.Lucene84PostingsFormat.POS_CODEC;
+import static org.apache.lucene.codecs.lucene84.Lucene84PostingsFormat.TERMS_CODEC;
+import static org.apache.lucene.codecs.lucene84.Lucene84PostingsFormat.VERSION_CURRENT;
+import static org.apache.lucene.codecs.lucene84.Lucene84PostingsFormat.VERSION_START;
+
+import java.io.IOException;
+import java.util.Arrays;
+
+import org.apache.lucene.codecs.BlockTermState;
+import org.apache.lucene.codecs.CodecUtil;
+import org.apache.lucene.codecs.PostingsReaderBase;
+import org.apache.lucene.codecs.lucene84.Lucene84PostingsFormat.IntBlockTermState;
+import org.apache.lucene.index.FieldInfo;
+import org.apache.lucene.index.Impacts;
+import org.apache.lucene.index.ImpactsEnum;
+import org.apache.lucene.index.IndexFileNames;
+import org.apache.lucene.index.IndexOptions;
+import org.apache.lucene.index.PostingsEnum;
+import org.apache.lucene.index.SegmentReadState;
+import org.apache.lucene.index.SlowImpactsEnum;
+import org.apache.lucene.search.DocIdSetIterator;
+import org.apache.lucene.store.DataInput;
+import org.apache.lucene.store.IndexInput;
+import org.apache.lucene.util.ArrayUtil;
+import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.IOUtils;
+import org.apache.lucene.util.RamUsageEstimator;
+
+/**
+ * Concrete class that reads docId(maybe frq,pos,offset,payloads) list
+ * with postings format.
+ *
+ * @lucene.experimental
+ */
+public final class Lucene84PostingsReader extends PostingsReaderBase {
+
+ private static final long BASE_RAM_BYTES_USED = RamUsageEstimator.shallowSizeOfInstance(Lucene84PostingsReader.class);
+
+ private final IndexInput docIn;
+ private final IndexInput posIn;
+ private final IndexInput payIn;
+
+ private final int version;
+
+ /** Sole constructor. */
+ public Lucene84PostingsReader(SegmentReadState state) throws IOException {
+ boolean success = false;
+ IndexInput docIn = null;
+ IndexInput posIn = null;
+ IndexInput payIn = null;
+
+ // NOTE: these data files are too costly to verify checksum against all the bytes on open,
+ // but for now we at least verify proper structure of the checksum footer: which looks
+ // for FOOTER_MAGIC + algorithmID. This is cheap and can detect some forms of corruption
+ // such as file truncation.
+
+ String docName = IndexFileNames.segmentFileName(state.segmentInfo.name, state.segmentSuffix, Lucene84PostingsFormat.DOC_EXTENSION);
+ try {
+ docIn = state.directory.openInput(docName, state.context);
+ version = CodecUtil.checkIndexHeader(docIn, DOC_CODEC, VERSION_START, VERSION_CURRENT, state.segmentInfo.getId(), state.segmentSuffix);
+ CodecUtil.retrieveChecksum(docIn);
+
+ if (state.fieldInfos.hasProx()) {
+ String proxName = IndexFileNames.segmentFileName(state.segmentInfo.name, state.segmentSuffix, Lucene84PostingsFormat.POS_EXTENSION);
+ posIn = state.directory.openInput(proxName, state.context);
+ CodecUtil.checkIndexHeader(posIn, POS_CODEC, version, version, state.segmentInfo.getId(), state.segmentSuffix);
+ CodecUtil.retrieveChecksum(posIn);
+
+ if (state.fieldInfos.hasPayloads() || state.fieldInfos.hasOffsets()) {
+ String payName = IndexFileNames.segmentFileName(state.segmentInfo.name, state.segmentSuffix, Lucene84PostingsFormat.PAY_EXTENSION);
+ payIn = state.directory.openInput(payName, state.context);
+ CodecUtil.checkIndexHeader(payIn, PAY_CODEC, version, version, state.segmentInfo.getId(), state.segmentSuffix);
+ CodecUtil.retrieveChecksum(payIn);
+ }
+ }
+
+ this.docIn = docIn;
+ this.posIn = posIn;
+ this.payIn = payIn;
+ success = true;
+ } finally {
+ if (!success) {
+ IOUtils.closeWhileHandlingException(docIn, posIn, payIn);
+ }
+ }
+ }
+
+ @Override
+ public void init(IndexInput termsIn, SegmentReadState state) throws IOException {
+ // Make sure we are talking to the matching postings writer
+ CodecUtil.checkIndexHeader(termsIn, TERMS_CODEC, VERSION_START, VERSION_CURRENT, state.segmentInfo.getId(), state.segmentSuffix);
+ final int indexBlockSize = termsIn.readVInt();
+ if (indexBlockSize != BLOCK_SIZE) {
+ throw new IllegalStateException("index-time BLOCK_SIZE (" + indexBlockSize + ") != read-time BLOCK_SIZE (" + BLOCK_SIZE + ")");
+ }
+ }
+
+ /**
+ * Read values that have been written using variable-length encoding instead of bit-packing.
+ */
+ static void readVIntBlock(IndexInput docIn, long[] docBuffer,
+ long[] freqBuffer, int num, boolean indexHasFreq) throws IOException {
+ if (indexHasFreq) {
+ for(int i=0;i<num;i++) {
+ final int code = docIn.readVInt();
+ docBuffer[i] = code >>> 1;
+ if ((code & 1) != 0) {
+ freqBuffer[i] = 1;
+ } else {
+ freqBuffer[i] = docIn.readVInt();
+ }
+ }
+ } else {
+ for(int i=0;i<num;i++) {
+ docBuffer[i] = docIn.readVInt();
+ }
+ }
+ }
+
+ static void prefixSum(long[] buffer, int count, long base) {
+ buffer[0] += base;
+ for (int i = 1; i < count; ++i) {
+ buffer[i] += buffer[i-1];
+ }
+ }
+
+ static int findFirstGreater(long[] buffer, int target, int from) {
+ for (int i = from; i < BLOCK_SIZE; ++i) {
+ if (buffer[i] >= target) {
+ return i;
+ }
+ }
+ return BLOCK_SIZE;
+ }
+
+ @Override
+ public BlockTermState newTermState() {
+ return new IntBlockTermState();
+ }
+
+ @Override
+ public void close() throws IOException {
+ IOUtils.close(docIn, posIn, payIn);
+ }
+
+ @Override
+ public void decodeTerm(long[] longs, DataInput in, FieldInfo fieldInfo, BlockTermState _termState, boolean absolute)
+ throws IOException {
+ final IntBlockTermState termState = (IntBlockTermState) _termState;
+ final boolean fieldHasPositions = fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0;
+ final boolean fieldHasOffsets = fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0;
+ final boolean fieldHasPayloads = fieldInfo.hasPayloads();
+
+ if (absolute) {
+ termState.docStartFP = 0;
+ termState.posStartFP = 0;
+ termState.payStartFP = 0;
+ }
+
+ termState.docStartFP += longs[0];
+ if (fieldHasPositions) {
+ termState.posStartFP += longs[1];
+ if (fieldHasOffsets || fieldHasPayloads) {
+ termState.payStartFP += longs[2];
+ }
+ }
+ if (termState.docFreq == 1) {
+ termState.singletonDocID = in.readVInt();
+ } else {
+ termState.singletonDocID = -1;
+ }
+ if (fieldHasPositions) {
+ if (termState.totalTermFreq > BLOCK_SIZE) {
+ termState.lastPosBlockOffset = in.readVLong();
+ } else {
+ termState.lastPosBlockOffset = -1;
+ }
+ }
+ if (termState.docFreq > BLOCK_SIZE) {
+ termState.skipOffset = in.readVLong();
+ } else {
+ termState.skipOffset = -1;
+ }
+ }
+
+ @Override
+ public PostingsEnum postings(FieldInfo fieldInfo, BlockTermState termState, PostingsEnum reuse, int flags) throws IOException {
+
+ boolean indexHasPositions = fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0;
+
+ if (indexHasPositions == false || PostingsEnum.featureRequested(flags, PostingsEnum.POSITIONS) == false) {
+ BlockDocsEnum docsEnum;
+ if (reuse instanceof BlockDocsEnum) {
+ docsEnum = (BlockDocsEnum) reuse;
+ if (!docsEnum.canReuse(docIn, fieldInfo)) {
+ docsEnum = new BlockDocsEnum(fieldInfo);
+ }
+ } else {
+ docsEnum = new BlockDocsEnum(fieldInfo);
+ }
+ return docsEnum.reset((IntBlockTermState) termState, flags);
+ } else {
+ EverythingEnum everythingEnum;
+ if (reuse instanceof EverythingEnum) {
+ everythingEnum = (EverythingEnum) reuse;
+ if (!everythingEnum.canReuse(docIn, fieldInfo)) {
+ everythingEnum = new EverythingEnum(fieldInfo);
+ }
+ } else {
+ everythingEnum = new EverythingEnum(fieldInfo);
+ }
+ return everythingEnum.reset((IntBlockTermState) termState, flags);
+ }
+ }
+
+ @Override
+ public ImpactsEnum impacts(FieldInfo fieldInfo, BlockTermState state, int flags) throws IOException {
+ if (state.docFreq <= BLOCK_SIZE) {
+ // no skip data
+ return new SlowImpactsEnum(postings(fieldInfo, state, null, flags));
+ }
+
+ final boolean indexHasPositions = fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0;
+ final boolean indexHasOffsets = fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0;
+ final boolean indexHasPayloads = fieldInfo.hasPayloads();
+
+ if (indexHasPositions == false || PostingsEnum.featureRequested(flags, PostingsEnum.POSITIONS) == false) {
+ return new BlockImpactsDocsEnum(fieldInfo, (IntBlockTermState) state);
+ }
+
+ if (indexHasPositions &&
+ PostingsEnum.featureRequested(flags, PostingsEnum.POSITIONS) &&
+ (indexHasOffsets == false || PostingsEnum.featureRequested(flags, PostingsEnum.OFFSETS) == false) &&
+ (indexHasPayloads == false || PostingsEnum.featureRequested(flags, PostingsEnum.PAYLOADS) == false)) {
+ return new BlockImpactsPostingsEnum(fieldInfo, (IntBlockTermState) state);
+ }
+
+ return new BlockImpactsEverythingEnum(fieldInfo, (IntBlockTermState) state, flags);
+ }
+
+ final class BlockDocsEnum extends PostingsEnum {
+
+ final ForUtil forUtil = new ForUtil();
+ final ForDeltaUtil forDeltaUtil = new ForDeltaUtil(forUtil);
+ final PForUtil pforUtil = new PForUtil(forUtil);
+
+ private final long[] docBuffer = new long[BLOCK_SIZE];
+ private final long[] freqBuffer = new long[BLOCK_SIZE];
+
+ private int docBufferUpto;
+
+ private Lucene84SkipReader skipper;
+ private boolean skipped;
+
+ final IndexInput startDocIn;
+
+ IndexInput docIn;
+ final boolean indexHasFreq;
+ final boolean indexHasPos;
+ final boolean indexHasOffsets;
+ final boolean indexHasPayloads;
+
+ private int docFreq; // number of docs in this posting list
+ private long totalTermFreq; // sum of freqBuffer in this posting list (or docFreq when omitted)
+ private int docUpto; // how many docs we've read
+ private int doc; // doc we last read
+ private long accum; // accumulator for doc deltas
+
+ // Where this term's postings start in the .doc file:
+ private long docTermStartFP;
+
+ // Where this term's skip data starts (after
+ // docTermStartFP) in the .doc file (or -1 if there is
+ // no skip data for this term):
+ private long skipOffset;
+
+ // docID for next skip point, we won't use skipper if
+ // target docID is not larger than this
+ private int nextSkipDoc;
+
+ private boolean needsFreq; // true if the caller actually needs frequencies
+ // as we read freqBuffer lazily, isFreqsRead shows if freqBuffer are read for the current block
+ // always true when we don't have freqBuffer (indexHasFreq=false) or don't need freqBuffer (needsFreq=false)
+ private boolean isFreqsRead;
+ private int singletonDocID; // docid when there is a single pulsed posting, otherwise -1
+
+ public BlockDocsEnum(FieldInfo fieldInfo) throws IOException {
+ this.startDocIn = Lucene84PostingsReader.this.docIn;
+ this.docIn = null;
+ indexHasFreq = fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS) >= 0;
+ indexHasPos = fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0;
+ indexHasOffsets = fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0;
+ indexHasPayloads = fieldInfo.hasPayloads();
+ }
+
+ public boolean canReuse(IndexInput docIn, FieldInfo fieldInfo) {
+ return docIn == startDocIn &&
+ indexHasFreq == (fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS) >= 0) &&
+ indexHasPos == (fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0) &&
+ indexHasPayloads == fieldInfo.hasPayloads();
+ }
+
+ public PostingsEnum reset(IntBlockTermState termState, int flags) throws IOException {
+ docFreq = termState.docFreq;
+ totalTermFreq = indexHasFreq ? termState.totalTermFreq : docFreq;
+ docTermStartFP = termState.docStartFP;
+ skipOffset = termState.skipOffset;
+ singletonDocID = termState.singletonDocID;
+ if (docFreq > 1) {
+ if (docIn == null) {
+ // lazy init
+ docIn = startDocIn.clone();
+ }
+ docIn.seek(docTermStartFP);
+ }
+
+ doc = -1;
+ this.needsFreq = PostingsEnum.featureRequested(flags, PostingsEnum.FREQS);
+ this.isFreqsRead = true;
+ if (indexHasFreq == false || needsFreq == false) {
+ for (int i = 0; i < ForUtil.BLOCK_SIZE; ++i) {
+ freqBuffer[i] = 1;
+ }
+ }
+ accum = 0;
+ docUpto = 0;
+ nextSkipDoc = BLOCK_SIZE - 1; // we won't skip if target is found in first block
+ docBufferUpto = BLOCK_SIZE;
+ skipped = false;
+ return this;
+ }
+
+ @Override
+ public int freq() throws IOException {
+ if (isFreqsRead == false) {
+ pforUtil.decode(docIn, freqBuffer); // read freqBuffer for this block
+ isFreqsRead = true;
+ }
+ return (int) freqBuffer[docBufferUpto-1];
+ }
+
+ @Override
+ public int nextPosition() throws IOException {
+ return -1;
+ }
+
+ @Override
+ public int startOffset() throws IOException {
+ return -1;
+ }
+
+ @Override
+ public int endOffset() throws IOException {
+ return -1;
+ }
+
+ @Override
+ public BytesRef getPayload() throws IOException {
+ return null;
+ }
+
+ @Override
+ public int docID() {
+ return doc;
+ }
+
+ private void refillDocs() throws IOException {
+ // Check if we skipped reading the previous block of freqBuffer, and if yes, position docIn after it
+ if (isFreqsRead == false) {
+ pforUtil.skip(docIn);
+ isFreqsRead = true;
+ }
+
+ final int left = docFreq - docUpto;
+ assert left >= 0;
+
+ if (left >= BLOCK_SIZE) {
+ forDeltaUtil.decodeAndPrefixSum(docIn, accum, docBuffer);
+
+ if (indexHasFreq) {
+ if (needsFreq) {
+ isFreqsRead = false;
+ } else {
+ pforUtil.skip(docIn); // skip over freqBuffer if we don't need them at all
+ }
+ }
+ } else if (docFreq == 1) {
+ docBuffer[0] = singletonDocID;
+ freqBuffer[0] = totalTermFreq;
+ Arrays.fill(docBuffer, 1, BLOCK_SIZE, DocIdSetIterator.NO_MORE_DOCS);
+ } else {
+ // Read vInts:
+ readVIntBlock(docIn, docBuffer, freqBuffer, left, indexHasFreq);
+ prefixSum(docBuffer, left, accum);
+ Arrays.fill(docBuffer, left, BLOCK_SIZE, DocIdSetIterator.NO_MORE_DOCS);
+ }
+ accum = docBuffer[BLOCK_SIZE - 1];
+ docBufferUpto = 0;
+ }
+
+ @Override
+ public int nextDoc() throws IOException {
+ if (docBufferUpto == BLOCK_SIZE) {
+ refillDocs(); // we don't need to load freqBuffer for now (will be loaded later if necessary)
+ }
+
+ doc = (int) docBuffer[docBufferUpto];
+ docUpto++;
+ docBufferUpto++;
+ return doc;
+ }
+
+ @Override
+ public int advance(int target) throws IOException {
+ // current skip docID < docIDs generated from current buffer <= next skip docID
+ // we don't need to skip if target is buffered already
+ if (docFreq > BLOCK_SIZE && target > nextSkipDoc) {
+
+ if (skipper == null) {
+ // Lazy init: first time this enum has ever been used for skipping
+ skipper = new Lucene84SkipReader(docIn.clone(),
+ MAX_SKIP_LEVELS,
+ indexHasPos,
+ indexHasOffsets,
+ indexHasPayloads);
+ }
+
+ if (!skipped) {
+ assert skipOffset != -1;
+ // This is the first time this enum has skipped
+ // since reset() was called; load the skip data:
+ skipper.init(docTermStartFP+skipOffset, docTermStartFP, 0, 0, docFreq);
+ skipped = true;
+ }
+
+ // always plus one to fix the result, since skip position in Lucene84SkipReader
+ // is a little different from MultiLevelSkipListReader
+ final int newDocUpto = skipper.skipTo(target) + 1;
+
+ if (newDocUpto > docUpto) {
+ // Skipper moved
+ assert newDocUpto % BLOCK_SIZE == 0 : "got " + newDocUpto;
+ docUpto = newDocUpto;
+
+ // Force to read next block
+ docBufferUpto = BLOCK_SIZE;
+ accum = skipper.getDoc(); // actually, this is just lastSkipEntry
+ docIn.seek(skipper.getDocPointer()); // now point to the block we want to search
+ // even if freqBuffer were not read from the previous block, we will mark them as read,
+ // as we don't need to skip the previous block freqBuffer in refillDocs,
+ // as we have already positioned docIn where in needs to be.
+ isFreqsRead = true;
+ }
+ // next time we call advance, this is used to
+ // foresee whether skipper is necessary.
+ nextSkipDoc = skipper.getNextSkipDoc();
+ }
+ if (docBufferUpto == BLOCK_SIZE) {
+ refillDocs();
+ }
+
+ // Now scan... this is an inlined/pared down version
+ // of nextDoc():
+ long doc;
+ while (true) {
+ doc = docBuffer[docBufferUpto];
+ docUpto++;
+
+ if (doc >= target) {
+ break;
+ }
+ if (++docBufferUpto == BLOCK_SIZE) {
+ return this.doc = NO_MORE_DOCS;
+ }
+ }
+
+ docBufferUpto++;
+ return this.doc = (int) doc;
+ }
+
+ @Override
+ public long cost() {
+ return docFreq;
+ }
+ }
+
+ // Also handles payloads + offsets
+ final class EverythingEnum extends PostingsEnum {
+
+ final ForUtil forUtil = new ForUtil();
+ final ForDeltaUtil forDeltaUtil = new ForDeltaUtil(forUtil);
+ final PForUtil pforUtil = new PForUtil(forUtil);
+
+ private final long[] docBuffer = new long[BLOCK_SIZE];
+ private final long[] freqBuffer = new long[BLOCK_SIZE];
+ private final long[] posDeltaBuffer = new long[BLOCK_SIZE];
+
+ private final long[] payloadLengthBuffer;
+ private final long[] offsetStartDeltaBuffer;
+ private final long[] offsetLengthBuffer;
+
+ private byte[] payloadBytes;
+ private int payloadByteUpto;
+ private int payloadLength;
+
+ private int lastStartOffset;
+ private int startOffset;
+ private int endOffset;
+
+ private int docBufferUpto;
+ private int posBufferUpto;
+
+ private Lucene84SkipReader skipper;
+ private boolean skipped;
+
+ final IndexInput startDocIn;
+
+ IndexInput docIn;
+ final IndexInput posIn;
+ final IndexInput payIn;
+ final BytesRef payload;
+
+ final boolean indexHasOffsets;
+ final boolean indexHasPayloads;
+
+ private int docFreq; // number of docs in this posting list
+ private long totalTermFreq; // number of positions in this posting list
+ private int docUpto; // how many docs we've read
+ private int doc; // doc we last read
+ private long accum; // accumulator for doc deltas
+ private int freq; // freq we last read
+ private int position; // current position
+
+ // how many positions "behind" we are; nextPosition must
+ // skip these to "catch up":
+ private int posPendingCount;
+
+ // Lazy pos seek: if != -1 then we must seek to this FP
+ // before reading positions:
+ private long posPendingFP;
+
+ // Lazy pay seek: if != -1 then we must seek to this FP
+ // before reading payloads/offsets:
+ private long payPendingFP;
+
+ // Where this term's postings start in the .doc file:
+ private long docTermStartFP;
+
+ // Where this term's postings start in the .pos file:
+ private long posTermStartFP;
+
+ // Where this term's payloads/offsets start in the .pay
+ // file:
+ private long payTermStartFP;
+
+ // File pointer where the last (vInt encoded) pos delta
+ // block is. We need this to know whether to bulk
+ // decode vs vInt decode the block:
+ private long lastPosBlockFP;
+
+ // Where this term's skip data starts (after
+ // docTermStartFP) in the .doc file (or -1 if there is
+ // no skip data for this term):
+ private long skipOffset;
+
+ private int nextSkipDoc;
+
+ private boolean needsOffsets; // true if we actually need offsets
+ private boolean needsPayloads; // true if we actually need payloads
+ private int singletonDocID; // docid when there is a single pulsed posting, otherwise -1
+
+ public EverythingEnum(FieldInfo fieldInfo) throws IOException {
+ indexHasOffsets = fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0;
+ indexHasPayloads = fieldInfo.hasPayloads();
+
+ this.startDocIn = Lucene84PostingsReader.this.docIn;
+ this.docIn = null;
+ this.posIn = Lucene84PostingsReader.this.posIn.clone();
+ if (indexHasOffsets || indexHasPayloads) {
+ this.payIn = Lucene84PostingsReader.this.payIn.clone();
+ } else {
+ this.payIn = null;
+ }
+ if (indexHasOffsets) {
+ offsetStartDeltaBuffer = new long[BLOCK_SIZE];
+ offsetLengthBuffer = new long[BLOCK_SIZE];
+ } else {
+ offsetStartDeltaBuffer = null;
+ offsetLengthBuffer = null;
+ startOffset = -1;
+ endOffset = -1;
+ }
+
+ if (indexHasPayloads) {
+ payloadLengthBuffer = new long[BLOCK_SIZE];
+ payloadBytes = new byte[128];
+ payload = new BytesRef();
+ } else {
+ payloadLengthBuffer = null;
+ payloadBytes = null;
+ payload = null;
+ }
+ }
+
+ public boolean canReuse(IndexInput docIn, FieldInfo fieldInfo) {
+ return docIn == startDocIn &&
+ indexHasOffsets == (fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0) &&
+ indexHasPayloads == fieldInfo.hasPayloads();
+ }
+
+ public EverythingEnum reset(IntBlockTermState termState, int flags) throws IOException {
+ docFreq = termState.docFreq;
+ docTermStartFP = termState.docStartFP;
+ posTermStartFP = termState.posStartFP;
+ payTermStartFP = termState.payStartFP;
+ skipOffset = termState.skipOffset;
+ totalTermFreq = termState.totalTermFreq;
+ singletonDocID = termState.singletonDocID;
+ if (docFreq > 1) {
+ if (docIn == null) {
+ // lazy init
+ docIn = startDocIn.clone();
+ }
+ docIn.seek(docTermStartFP);
+ }
+ posPendingFP = posTermStartFP;
+ payPendingFP = payTermStartFP;
+ posPendingCount = 0;
+ if (termState.totalTermFreq < BLOCK_SIZE) {
+ lastPosBlockFP = posTermStartFP;
+ } else if (termState.totalTermFreq == BLOCK_SIZE) {
+ lastPosBlockFP = -1;
+ } else {
+ lastPosBlockFP = posTermStartFP + termState.lastPosBlockOffset;
+ }
+
+ this.needsOffsets = PostingsEnum.featureRequested(flags, PostingsEnum.OFFSETS);
+ this.needsPayloads = PostingsEnum.featureRequested(flags, PostingsEnum.PAYLOADS);
+
+ doc = -1;
+ accum = 0;
+ docUpto = 0;
+ if (docFreq > BLOCK_SIZE) {
+ nextSkipDoc = BLOCK_SIZE - 1; // we won't skip if target is found in first block
+ } else {
+ nextSkipDoc = NO_MORE_DOCS; // not enough docs for skipping
+ }
+ docBufferUpto = BLOCK_SIZE;
+ skipped = false;
+ return this;
+ }
+
+ @Override
+ public int freq() throws IOException {
+ return freq;
+ }
+
+ @Override
+ public int docID() {
+ return doc;
+ }
+
+ private void refillDocs() throws IOException {
+ final int left = docFreq - docUpto;
+ assert left >= 0;
+
+ if (left >= BLOCK_SIZE) {
+ forDeltaUtil.decodeAndPrefixSum(docIn, accum, docBuffer);
+ pforUtil.decode(docIn, freqBuffer);
+ } else if (docFreq == 1) {
+ docBuffer[0] = singletonDocID;
+ freqBuffer[0] = totalTermFreq;
+ Arrays.fill(docBuffer, 1, BLOCK_SIZE, DocIdSetIterator.NO_MORE_DOCS);
+ } else {
+ readVIntBlock(docIn, docBuffer, freqBuffer, left, true);
+ prefixSum(docBuffer, left, accum);
+ Arrays.fill(docBuffer, left, BLOCK_SIZE, DocIdSetIterator.NO_MORE_DOCS);
+ }
+ accum = docBuffer[BLOCK_SIZE - 1];
+ docBufferUpto = 0;
+ }
+
+ private void refillPositions() throws IOException {
+ if (posIn.getFilePointer() == lastPosBlockFP) {
+ final int count = (int) (totalTermFreq % BLOCK_SIZE);
+ int payloadLength = 0;
+ int offsetLength = 0;
+ payloadByteUpto = 0;
+ for(int i=0;i<count;i++) {
+ int code = posIn.readVInt();
+ if (indexHasPayloads) {
+ if ((code & 1) != 0) {
+ payloadLength = posIn.readVInt();
+ }
+ payloadLengthBuffer[i] = payloadLength;
+ posDeltaBuffer[i] = code >>> 1;
+ if (payloadLength != 0) {
+ if (payloadByteUpto + payloadLength > payloadBytes.length) {
+ payloadBytes = ArrayUtil.grow(payloadBytes, payloadByteUpto + payloadLength);
+ }
+ posIn.readBytes(payloadBytes, payloadByteUpto, payloadLength);
+ payloadByteUpto += payloadLength;
+ }
+ } else {
+ posDeltaBuffer[i] = code;
+ }
+
+ if (indexHasOffsets) {
+ int deltaCode = posIn.readVInt();
+ if ((deltaCode & 1) != 0) {
+ offsetLength = posIn.readVInt();
+ }
+ offsetStartDeltaBuffer[i] = deltaCode >>> 1;
+ offsetLengthBuffer[i] = offsetLength;
+ }
+ }
+ payloadByteUpto = 0;
+ } else {
+ pforUtil.decode(posIn, posDeltaBuffer);
+
+ if (indexHasPayloads) {
+ if (needsPayloads) {
+ pforUtil.decode(payIn, payloadLengthBuffer);
+ int numBytes = payIn.readVInt();
+
+ if (numBytes > payloadBytes.length) {
+ payloadBytes = ArrayUtil.grow(payloadBytes, numBytes);
+ }
+ payIn.readBytes(payloadBytes, 0, numBytes);
+ } else {
+ // this works, because when writing a vint block we always force the first length to be written
+ pforUtil.skip(payIn); // skip over lengths
+ int numBytes = payIn.readVInt(); // read length of payloadBytes
+ payIn.seek(payIn.getFilePointer() + numBytes); // skip over payloadBytes
+ }
+ payloadByteUpto = 0;
+ }
+
+ if (indexHasOffsets) {
+ if (needsOffsets) {
+ pforUtil.decode(payIn, offsetStartDeltaBuffer);
+ pforUtil.decode(payIn, offsetLengthBuffer);
+ } else {
+ // this works, because when writing a vint block we always force the first length to be written
+ pforUtil.skip(payIn); // skip over starts
+ pforUtil.skip(payIn); // skip over lengths
+ }
+ }
+ }
+ }
+
+ @Override
+ public int nextDoc() throws IOException {
+ if (docBufferUpto == BLOCK_SIZE) {
+ refillDocs();
+ }
+
+ doc = (int) docBuffer[docBufferUpto];
+ freq = (int) freqBuffer[docBufferUpto];
+ posPendingCount += freq;
+ docBufferUpto++;
+ docUpto++;
+
+ position = 0;
+ lastStartOffset = 0;
+ return doc;
+ }
+
+ @Override
+ public int advance(int target) throws IOException {
+ if (target > nextSkipDoc) {
+ if (skipper == null) {
+ // Lazy init: first time this enum has ever been used for skipping
+ skipper = new Lucene84SkipReader(docIn.clone(),
+ MAX_SKIP_LEVELS,
+ true,
+ indexHasOffsets,
+ indexHasPayloads);
+ }
+
+ if (!skipped) {
+ assert skipOffset != -1;
+ // This is the first time this enum has skipped
+ // since reset() was called; load the skip data:
+ skipper.init(docTermStartFP+skipOffset, docTermStartFP, posTermStartFP, payTermStartFP, docFreq);
+ skipped = true;
+ }
+
+ final int newDocUpto = skipper.skipTo(target) + 1;
+
+ if (newDocUpto > docUpto) {
+ // Skipper moved
+ assert newDocUpto % BLOCK_SIZE == 0 : "got " + newDocUpto;
+ docUpto = newDocUpto;
+
+ // Force to read next block
+ docBufferUpto = BLOCK_SIZE;
+ accum = skipper.getDoc();
+ docIn.seek(skipper.getDocPointer());
+ posPendingFP = skipper.getPosPointer();
+ payPendingFP = skipper.getPayPointer();
+ posPendingCount = skipper.getPosBufferUpto();
+ lastStartOffset = 0; // new document
+ payloadByteUpto = skipper.getPayloadByteUpto();
+ }
+ nextSkipDoc = skipper.getNextSkipDoc();
+ }
+ if (docBufferUpto == BLOCK_SIZE) {
+ refillDocs();
+ }
+
+ // Now scan:
+ long doc;
+ while (true) {
+ doc = docBuffer[docBufferUpto];
+ freq = (int) freqBuffer[docBufferUpto];
+ posPendingCount += freq;
+ docBufferUpto++;
+ docUpto++;
+
+ if (doc >= target) {
+ break;
+ }
+
+ if (docBufferUpto == BLOCK_SIZE) {
+ return this.doc = NO_MORE_DOCS;
+ }
+ }
+
+ position = 0;
+ lastStartOffset = 0;
+ return this.doc = (int) doc;
+ }
+
+ // TODO: in theory we could avoid loading frq block
+ // when not needed, ie, use skip data to load how far to
+ // seek the pos pointer ... instead of having to load frq
+ // blocks only to sum up how many positions to skip
+ private void skipPositions() throws IOException {
+ // Skip positions now:
+ int toSkip = posPendingCount - freq;
+ // if (DEBUG) {
+ // System.out.println(" FPR.skipPositions: toSkip=" + toSkip);
+ // }
+
+ final int leftInBlock = BLOCK_SIZE - posBufferUpto;
+ if (toSkip < leftInBlock) {
+ int end = posBufferUpto + toSkip;
+ while(posBufferUpto < end) {
+ if (indexHasPayloads) {
+ payloadByteUpto += payloadLengthBuffer[posBufferUpto];
+ }
+ posBufferUpto++;
+ }
+ } else {
+ toSkip -= leftInBlock;
+ while(toSkip >= BLOCK_SIZE) {
+ assert posIn.getFilePointer() != lastPosBlockFP;
+ pforUtil.skip(posIn);
+
+ if (indexHasPayloads) {
+ // Skip payloadLength block:
+ pforUtil.skip(payIn);
+
+ // Skip payloadBytes block:
+ int numBytes = payIn.readVInt();
+ payIn.seek(payIn.getFilePointer() + numBytes);
+ }
+
+ if (indexHasOffsets) {
+ pforUtil.skip(payIn);
+ pforUtil.skip(payIn);
+ }
+ toSkip -= BLOCK_SIZE;
+ }
+ refillPositions();
+ payloadByteUpto = 0;
+ posBufferUpto = 0;
+ while(posBufferUpto < toSkip) {
+ if (indexHasPayloads) {
+ payloadByteUpto += payloadLengthBuffer[posBufferUpto];
+ }
+ posBufferUpto++;
+ }
+ }
+
+ position = 0;
+ lastStartOffset = 0;
+ }
+
+ @Override
+ public int nextPosition() throws IOException {
+ assert posPendingCount > 0;
+
+ if (posPendingFP != -1) {
+ posIn.seek(posPendingFP);
+ posPendingFP = -1;
+
+ if (payPendingFP != -1 && payIn != null) {
+ payIn.seek(payPendingFP);
+ payPendingFP = -1;
+ }
+
+ // Force buffer refill:
+ posBufferUpto = BLOCK_SIZE;
+ }
+
+ if (posPendingCount > freq) {
+ skipPositions();
+ posPendingCount = freq;
+ }
+
+ if (posBufferUpto == BLOCK_SIZE) {
+ refillPositions();
+ posBufferUpto = 0;
+ }
+ position += posDeltaBuffer[posBufferUpto];
+
+ if (indexHasPayloads) {
+ payloadLength = (int) payloadLengthBuffer[posBufferUpto];
+ payload.bytes = payloadBytes;
+ payload.offset = payloadByteUpto;
+ payload.length = payloadLength;
+ payloadByteUpto += payloadLength;
+ }
+
+ if (indexHasOffsets) {
+ startOffset = lastStartOffset + (int) offsetStartDeltaBuffer[posBufferUpto];
+ endOffset = startOffset + (int) offsetLengthBuffer[posBufferUpto];
+ lastStartOffset = startOffset;
+ }
+
+ posBufferUpto++;
+ posPendingCount--;
+ return position;
+ }
+
+ @Override
+ public int startOffset() {
+ return startOffset;
+ }
+
+ @Override
+ public int endOffset() {
+ return endOffset;
+ }
+
+ @Override
+ public BytesRef getPayload() {
+ if (payloadLength == 0) {
+ return null;
+ } else {
+ return payload;
+ }
+ }
+
+ @Override
+ public long cost() {
+ return docFreq;
+ }
+ }
+
+ final class BlockImpactsDocsEnum extends ImpactsEnum {
+
+ final ForUtil forUtil = new ForUtil();
+ final ForDeltaUtil forDeltaUtil = new ForDeltaUtil(forUtil);
+ final PForUtil pforUtil = new PForUtil(forUtil);
+
+ private final long[] docBuffer = new long[BLOCK_SIZE];
+ private final long[] freqBuffer = new long[BLOCK_SIZE];
+
+ private int docBufferUpto;
+
+ private final Lucene84ScoreSkipReader skipper;
+
+ final IndexInput docIn;
+
+ final boolean indexHasFreqs;
+
+ private int docFreq; // number of docs in this posting list
+ private int docUpto; // how many docs we've read
+ private int doc; // doc we last read
+ private long accum; // accumulator for doc deltas
+ private int freq; // freq we last read
+
+
+ private int nextSkipDoc = -1;
+
+ private long seekTo = -1;
+
+ public BlockImpactsDocsEnum(FieldInfo fieldInfo, IntBlockTermState termState) throws IOException {
+ indexHasFreqs = fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS) >= 0;
+ final boolean indexHasPositions = fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0;
+ final boolean indexHasOffsets = fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0;
+ final boolean indexHasPayloads = fieldInfo.hasPayloads();
+
+ this.docIn = Lucene84PostingsReader.this.docIn.clone();
+
+ docFreq = termState.docFreq;
+ docIn.seek(termState.docStartFP);
+
+ doc = -1;
+ accum = 0;
+ docUpto = 0;
+ docBufferUpto = BLOCK_SIZE;
+
+ skipper = new Lucene84ScoreSkipReader(docIn.clone(),
+ MAX_SKIP_LEVELS,
+ indexHasPositions,
+ indexHasOffsets,
+ indexHasPayloads);
+ skipper.init(termState.docStartFP+termState.skipOffset, termState.docStartFP, termState.posStartFP, termState.payStartFP, docFreq);
+
+ if (indexHasFreqs == false) {
+ Arrays.fill(freqBuffer, 1L);
+ }
+ }
+
+ @Override
+ public int freq() throws IOException {
+ return freq;
+ }
+
+ @Override
+ public int docID() {
+ return doc;
+ }
+
+ private void refillDocs() throws IOException {
+ final int left = docFreq - docUpto;
+ assert left >= 0;
+
+ if (left >= BLOCK_SIZE) {
+ forDeltaUtil.decodeAndPrefixSum(docIn, accum, docBuffer);
+ if (indexHasFreqs) {
+ pforUtil.decode(docIn, freqBuffer);
+ }
+ } else {
+ readVIntBlock(docIn, docBuffer, freqBuffer, left, indexHasFreqs);
+ prefixSum(docBuffer, left, accum);
+ Arrays.fill(docBuffer, left, BLOCK_SIZE, DocIdSetIterator.NO_MORE_DOCS);
+ }
+ accum = docBuffer[BLOCK_SIZE - 1];
+ docBufferUpto = 0;
+ }
+
+ @Override
+ public void advanceShallow(int target) throws IOException {
+ if (target > nextSkipDoc) {
+ // always plus one to fix the result, since skip position in Lucene84SkipReader
+ // is a little different from MultiLevelSkipListReader
+ final int newDocUpto = skipper.skipTo(target) + 1;
+
+ if (newDocUpto > docUpto) {
+ // Skipper moved
+ assert newDocUpto % BLOCK_SIZE == 0 : "got " + newDocUpto;
+ docUpto = newDocUpto;
+
+ // Force to read next block
+ docBufferUpto = BLOCK_SIZE;
+ accum = skipper.getDoc();
+ seekTo = skipper.getDocPointer(); // delay the seek
+ }
+ // next time we call advance, this is used to
+ // foresee whether skipper is necessary.
+ nextSkipDoc = skipper.getNextSkipDoc();
+ }
+ assert nextSkipDoc >= target;
+ }
+
+ @Override
+ public Impacts getImpacts() throws IOException {
+ advanceShallow(doc);
+ return skipper.getImpacts();
+ }
+
+ @Override
+ public int nextDoc() throws IOException {
+ return advance(doc + 1);
+ }
+
+ @Override
+ public int advance(int target) throws IOException {
+ if (target > nextSkipDoc) {
+ advanceShallow(target);
+ }
+ if (docBufferUpto == BLOCK_SIZE) {
+ if (seekTo >= 0) {
+ docIn.seek(seekTo);
+ seekTo = -1;
+ }
+ refillDocs();
+ }
+
+ int next = findFirstGreater(docBuffer, target, docBufferUpto);
+ if (next == BLOCK_SIZE) {
+ return doc = NO_MORE_DOCS;
+ }
+ this.doc = (int) docBuffer[next];
+ this.freq = (int) freqBuffer[next];
+ docUpto += next - docBufferUpto + 1;
+ docBufferUpto = next + 1;
+ return doc;
+ }
+
+ @Override
+ public int nextPosition() throws IOException {
+ return -1;
+ }
+
+ @Override
+ public int startOffset() {
+ return -1;
+ }
+
+ @Override
+ public int endOffset() {
+ return -1;
+ }
+
+ @Override
+ public BytesRef getPayload() {
+ return null;
+ }
+
+ @Override
+ public long cost() {
+ return docFreq;
+ }
+
+ }
+
+ final class BlockImpactsPostingsEnum extends ImpactsEnum {
+
+ final ForUtil forUtil = new ForUtil();
+ final ForDeltaUtil forDeltaUtil = new ForDeltaUtil(forUtil);
+ final PForUtil pforUtil = new PForUtil(forUtil);
+
+ private final long[] docBuffer = new long[BLOCK_SIZE];
+ private final long[] freqBuffer = new long[BLOCK_SIZE];
+ private final long[] posDeltaBuffer = new long[BLOCK_SIZE];
+
+ private int docBufferUpto;
+ private int posBufferUpto;
+
+ private final Lucene84ScoreSkipReader skipper;
+
+ final IndexInput docIn;
+ final IndexInput posIn;
+
+ final boolean indexHasOffsets;
+ final boolean indexHasPayloads;
+
+ private int docFreq; // number of docs in this posting list
+ private long totalTermFreq; // number of positions in this posting list
+ private int docUpto; // how many docs we've read
+ private int doc; // doc we last read
+ private long accum; // accumulator for doc deltas
+ private int freq; // freq we last read
+ private int position; // current position
+
+ // how many positions "behind" we are; nextPosition must
+ // skip these to "catch up":
+ private int posPendingCount;
+
+ // Lazy pos seek: if != -1 then we must seek to this FP
+ // before reading positions:
+ private long posPendingFP;
+
+ // Where this term's postings start in the .doc file:
+ private long docTermStartFP;
+
+ // Where this term's postings start in the .pos file:
+ private long posTermStartFP;
+
+ // Where this term's payloads/offsets start in the .pay
+ // file:
+ private long payTermStartFP;
+
+ // File pointer where the last (vInt encoded) pos delta
+ // block is. We need this to know whether to bulk
+ // decode vs vInt decode the block:
+ private long lastPosBlockFP;
+
+ private int nextSkipDoc = -1;
+
+ private long seekTo = -1;
+
+ public BlockImpactsPostingsEnum(FieldInfo fieldInfo, IntBlockTermState termState) throws IOException {
+ indexHasOffsets = fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0;
+ indexHasPayloads = fieldInfo.hasPayloads();
+
+ this.docIn = Lucene84PostingsReader.this.docIn.clone();
+
+ this.posIn = Lucene84PostingsReader.this.posIn.clone();
+
+ docFreq = termState.docFreq;
+ docTermStartFP = termState.docStartFP;
+ posTermStartFP = termState.posStartFP;
+ payTermStartFP = termState.payStartFP;
+ totalTermFreq = termState.totalTermFreq;
+ docIn.seek(docTermStartFP);
+ posPendingFP = posTermStartFP;
+ posPendingCount = 0;
+ if (termState.totalTermFreq < BLOCK_SIZE) {
+ lastPosBlockFP = posTermStartFP;
+ } else if (termState.totalTermFreq == BLOCK_SIZE) {
+ lastPosBlockFP = -1;
+ } else {
+ lastPosBlockFP = posTermStartFP + termState.lastPosBlockOffset;
+ }
+
+ doc = -1;
+ accum = 0;
+ docUpto = 0;
+ docBufferUpto = BLOCK_SIZE;
+
+ skipper = new Lucene84ScoreSkipReader(docIn.clone(),
+ MAX_SKIP_LEVELS,
+ true,
+ indexHasOffsets,
+ indexHasPayloads);
+ skipper.init(docTermStartFP+termState.skipOffset, docTermStartFP, posTermStartFP, payTermStartFP, docFreq);
+ }
+
+ @Override
+ public int freq() throws IOException {
+ return freq;
+ }
+
+ @Override
+ public int docID() {
+ return doc;
+ }
+
+ private void refillDocs() throws IOException {
+ final int left = docFreq - docUpto;
+ assert left >= 0;
+
+ if (left >= BLOCK_SIZE) {
+ forDeltaUtil.decodeAndPrefixSum(docIn, accum, docBuffer);
+ pforUtil.decode(docIn, freqBuffer);
+ } else {
+ readVIntBlock(docIn, docBuffer, freqBuffer, left, true);
+ prefixSum(docBuffer, left, accum);
+ Arrays.fill(docBuffer, left, BLOCK_SIZE, DocIdSetIterator.NO_MORE_DOCS);
+ }
+ accum = docBuffer[BLOCK_SIZE - 1];
+ docBufferUpto = 0;
+ }
+
+ private void refillPositions() throws IOException {
+ if (posIn.getFilePointer() == lastPosBlockFP) {
+ final int count = (int) (totalTermFreq % BLOCK_SIZE);
+ int payloadLength = 0;
+ for(int i=0;i<count;i++) {
+ int code = posIn.readVInt();
+ if (indexHasPayloads) {
+ if ((code & 1) != 0) {
+ payloadLength = posIn.readVInt();
+ }
+ posDeltaBuffer[i] = code >>> 1;
+ if (payloadLength != 0) {
+ posIn.seek(posIn.getFilePointer() + payloadLength);
+ }
+ } else {
+ posDeltaBuffer[i] = code;
+ }
+ if (indexHasOffsets) {
+ if ((posIn.readVInt() & 1) != 0) {
+ // offset length changed
+ posIn.readVInt();
+ }
+ }
+ }
+ } else {
+ pforUtil.decode(posIn, posDeltaBuffer);
+ }
+ }
+
+ @Override
+ public void advanceShallow(int target) throws IOException {
+ if (target > nextSkipDoc) {
+ // always plus one to fix the result, since skip position in Lucene84SkipReader
+ // is a little different from MultiLevelSkipListReader
+ final int newDocUpto = skipper.skipTo(target) + 1;
+
+ if (newDocUpto > docUpto) {
+ // Skipper moved
+ assert newDocUpto % BLOCK_SIZE == 0 : "got " + newDocUpto;
+ docUpto = newDocUpto;
+
+ // Force to read next block
+ docBufferUpto = BLOCK_SIZE;
+ accum = skipper.getDoc();
+ posPendingFP = skipper.getPosPointer();
+ posPendingCount = skipper.getPosBufferUpto();
+ seekTo = skipper.getDocPointer(); // delay the seek
+ }
+ // next time we call advance, this is used to
+ // foresee whether skipper is necessary.
+ nextSkipDoc = skipper.getNextSkipDoc();
+ }
+ assert nextSkipDoc >= target;
+ }
+
+ @Override
+ public Impacts getImpacts() throws IOException {
+ advanceShallow(doc);
+ return skipper.getImpacts();
+ }
+
+ @Override
+ public int nextDoc() throws IOException {
+ return advance(doc + 1);
+ }
+
+ @Override
+ public int advance(int target) throws IOException {
+ if (target > nextSkipDoc) {
+ advanceShallow(target);
+ }
+ if (docBufferUpto == BLOCK_SIZE) {
+ if (seekTo >= 0) {
+ docIn.seek(seekTo);
+ seekTo = -1;
+ }
+ refillDocs();
+ }
+
+ int next = findFirstGreater(docBuffer, target, docBufferUpto);
+ if (next == BLOCK_SIZE) {
+ return doc = NO_MORE_DOCS;
+ }
+ this.doc = (int) docBuffer[next];
+ this.freq = (int) freqBuffer[next];
+ for (int i = docBufferUpto; i <= next; ++i) {
+ posPendingCount += freqBuffer[i];
+ }
+ docUpto += next - docBufferUpto + 1;
+ docBufferUpto = next + 1;
+ position = 0;
+ return doc;
+ }
+
+ // TODO: in theory we could avoid loading frq block
+ // when not needed, ie, use skip data to load how far to
+ // seek the pos pointer ... instead of having to load frq
+ // blocks only to sum up how many positions to skip
+ private void skipPositions() throws IOException {
+ // Skip positions now:
+ int toSkip = posPendingCount - freq;
+
+ final int leftInBlock = BLOCK_SIZE - posBufferUpto;
+ if (toSkip < leftInBlock) {
+ posBufferUpto += toSkip;
+ } else {
+ toSkip -= leftInBlock;
+ while(toSkip >= BLOCK_SIZE) {
+ assert posIn.getFilePointer() != lastPosBlockFP;
+ pforUtil.skip(posIn);
+ toSkip -= BLOCK_SIZE;
+ }
+ refillPositions();
+ posBufferUpto = toSkip;
+ }
+
+ position = 0;
+ }
+
+ @Override
+ public int nextPosition() throws IOException {
+ assert posPendingCount > 0;
+
+ if (posPendingFP != -1) {
+ posIn.seek(posPendingFP);
+ posPendingFP = -1;
+
+ // Force buffer refill:
+ posBufferUpto = BLOCK_SIZE;
+ }
+
+ if (posPendingCount > freq) {
+ skipPositions();
+ posPendingCount = freq;
+ }
+
+ if (posBufferUpto == BLOCK_SIZE) {
+ refillPositions();
+ posBufferUpto = 0;
+ }
+ position += posDeltaBuffer[posBufferUpto++];
+
+ posPendingCount--;
+ return position;
+ }
+
+ @Override
+ public int startOffset() {
+ return -1;
+ }
+
+ @Override
+ public int endOffset() {
+ return -1;
+ }
+
+ @Override
+ public BytesRef getPayload() {
+ return null;
+ }
+
+ @Override
+ public long cost() {
+ return docFreq;
+ }
+
+ }
+
+ final class BlockImpactsEverythingEnum extends ImpactsEnum {
+
+ final ForUtil forUtil = new ForUtil();
+ final ForDeltaUtil forDeltaUtil = new ForDeltaUtil(forUtil);
+ final PForUtil pforUtil = new PForUtil(forUtil);
+
+ private final long[] docBuffer = new long[BLOCK_SIZE];
+ private final long[] freqBuffer = new long[BLOCK_SIZE];
+ private final long[] posDeltaBuffer = new long[BLOCK_SIZE];
+
+ private final long[] payloadLengthBuffer;
+ private final long[] offsetStartDeltaBuffer;
+ private final long[] offsetLengthBuffer;
+
+ private byte[] payloadBytes;
+ private int payloadByteUpto;
+ private int payloadLength;
+
+ private int lastStartOffset;
+ private int startOffset = -1;
+ private int endOffset = -1;
+
+ private int docBufferUpto;
+ private int posBufferUpto;
+
+ private final Lucene84ScoreSkipReader skipper;
+
+ final IndexInput docIn;
+ final IndexInput posIn;
+ final IndexInput payIn;
+ final BytesRef payload;
+
+ final boolean indexHasFreq;
+ final boolean indexHasPos;
+ final boolean indexHasOffsets;
+ final boolean indexHasPayloads;
+
+ private int docFreq; // number of docs in this posting list
+ private long totalTermFreq; // number of positions in this posting list
+ private int docUpto; // how many docs we've read
+ private int posDocUpTo; // for how many docs we've read positions, offsets, and payloads
+ private int doc; // doc we last read
+ private long accum; // accumulator for doc deltas
+ private int position; // current position
+
+ // how many positions "behind" we are; nextPosition must
+ // skip these to "catch up":
+ private int posPendingCount;
+
+ // Lazy pos seek: if != -1 then we must seek to this FP
+ // before reading positions:
+ private long posPendingFP;
+
+ // Lazy pay seek: if != -1 then we must seek to this FP
+ // before reading payloads/offsets:
+ private long payPendingFP;
+
+ // Where this term's postings start in the .doc file:
+ private long docTermStartFP;
+
+ // Where this term's postings start in the .pos file:
+ private long posTermStartFP;
+
+ // Where this term's payloads/offsets start in the .pay
+ // file:
+ private long payTermStartFP;
+
+ // File pointer where the last (vInt encoded) pos delta
+ // block is. We need this to know whether to bulk
+ // decode vs vInt decode the block:
+ private long lastPosBlockFP;
+
+ private int nextSkipDoc = -1;
+
+ private final boolean needsPositions;
+ private final boolean needsOffsets; // true if we actually need offsets
+ private final boolean needsPayloads; // true if we actually need payloads
+
+ private boolean isFreqsRead; // shows if freqBuffer for the current doc block are read into freqBuffer
+
+ private long seekTo = -1;
+
+ public BlockImpactsEverythingEnum(FieldInfo fieldInfo, IntBlockTermState termState, int flags) throws IOException {
+ indexHasFreq = fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS) >= 0;
+ indexHasPos = fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0;
+ indexHasOffsets = fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0;
+ indexHasPayloads = fieldInfo.hasPayloads();
+
+ needsPositions = PostingsEnum.featureRequested(flags, PostingsEnum.POSITIONS);
+ needsOffsets = PostingsEnum.featureRequested(flags, PostingsEnum.OFFSETS);
+ needsPayloads = PostingsEnum.featureRequested(flags, PostingsEnum.PAYLOADS);
+
+ this.docIn = Lucene84PostingsReader.this.docIn.clone();
+
+ if (indexHasPos && needsPositions) {
+ this.posIn = Lucene84PostingsReader.this.posIn.clone();
+ } else {
+ this.posIn = null;
+ }
+
+ if ((indexHasOffsets && needsOffsets) || (indexHasPayloads && needsPayloads)) {
+ this.payIn = Lucene84PostingsReader.this.payIn.clone();
+ } else {
+ this.payIn = null;
+ }
+
+ if (indexHasOffsets) {
+ offsetStartDeltaBuffer = new long[BLOCK_SIZE];
+ offsetLengthBuffer = new long[BLOCK_SIZE];
+ } else {
+ offsetStartDeltaBuffer = null;
+ offsetLengthBuffer = null;
+ startOffset = -1;
+ endOffset = -1;
+ }
+
+ if (indexHasPayloads) {
+ payloadLengthBuffer = new long[BLOCK_SIZE];
+ payloadBytes = new byte[128];
+ payload = new BytesRef();
+ } else {
+ payloadLengthBuffer = null;
+ payloadBytes = null;
+ payload = null;
+ }
+
+ docFreq = termState.docFreq;
+ docTermStartFP = termState.docStartFP;
+ posTermStartFP = termState.posStartFP;
+ payTermStartFP = termState.payStartFP;
+ totalTermFreq = termState.totalTermFreq;
+ docIn.seek(docTermStartFP);
+ posPendingFP = posTermStartFP;
+ payPendingFP = payTermStartFP;
+ posPendingCount = 0;
+ if (termState.totalTermFreq < BLOCK_SIZE) {
+ lastPosBlockFP = posTermStartFP;
+ } else if (termState.totalTermFreq == BLOCK_SIZE) {
+ lastPosBlockFP = -1;
+ } else {
+ lastPosBlockFP = posTermStartFP + termState.lastPosBlockOffset;
+ }
+
+ doc = -1;
+ accum = 0;
+ docUpto = 0;
+ posDocUpTo = 0;
+ isFreqsRead = true;
+ docBufferUpto = BLOCK_SIZE;
+
+ skipper = new Lucene84ScoreSkipReader(docIn.clone(),
+ MAX_SKIP_LEVELS,
+ indexHasPos,
+ indexHasOffsets,
+ indexHasPayloads);
+ skipper.init(docTermStartFP+termState.skipOffset, docTermStartFP, posTermStartFP, payTermStartFP, docFreq);
+
+ if (indexHasFreq == false) {
+ for (int i = 0; i < ForUtil.BLOCK_SIZE; ++i) {
+ freqBuffer[i] = 1;
+ }
+ }
+ }
+
+ @Override
+ public int freq() throws IOException {
+ if (indexHasFreq && (isFreqsRead == false)) {
+ pforUtil.decode(docIn, freqBuffer); // read freqBuffer for this block
+ isFreqsRead = true;
+ }
+ return (int) freqBuffer[docBufferUpto-1];
+ }
+
+ @Override
+ public int docID() {
+ return doc;
+ }
+
+ private void refillDocs() throws IOException {
+ if (indexHasFreq) {
+ if (isFreqsRead == false) { // previous freq block was not read
+ // check if we need to load the previous freq block to catch up on positions or we can skip it
+ if (indexHasPos && needsPositions && (posDocUpTo < docUpto)) {
+ pforUtil.decode(docIn, freqBuffer); // load the previous freq block
+ } else {
+ pforUtil.skip(docIn); // skip it
+ }
+ isFreqsRead = true;
+ }
+ if (indexHasPos && needsPositions) {
+ while (posDocUpTo < docUpto) { // catch on positions, bring posPendingCount upto the current doc
+ posPendingCount += freqBuffer[docBufferUpto - (docUpto - posDocUpTo)];
+ posDocUpTo++;
+ }
+ }
+ }
+
+ final int left = docFreq - docUpto;
+ assert left >= 0;
+
+ if (left >= BLOCK_SIZE) {
+ forDeltaUtil.decodeAndPrefixSum(docIn, accum, docBuffer);
+ if (indexHasFreq) {
+ isFreqsRead = false; // freq block will be loaded lazily when necessary, we don't load it here
+ }
+ } else {
+ readVIntBlock(docIn, docBuffer, freqBuffer, left, indexHasFreq);
+ prefixSum(docBuffer, left, accum);
+ Arrays.fill(docBuffer, left, BLOCK_SIZE, DocIdSetIterator.NO_MORE_DOCS);
+ }
+ accum = docBuffer[BLOCK_SIZE - 1];
+ docBufferUpto = 0;
+ }
+
+ private void refillPositions() throws IOException {
+ if (posIn.getFilePointer() == lastPosBlockFP) {
+ final int count = (int) (totalTermFreq % BLOCK_SIZE);
+ int payloadLength = 0;
+ int offsetLength = 0;
+ payloadByteUpto = 0;
+ for(int i=0;i<count;i++) {
+ int code = posIn.readVInt();
+ if (indexHasPayloads) {
+ if ((code & 1) != 0) {
+ payloadLength = posIn.readVInt();
+ }
+ payloadLengthBuffer[i] = payloadLength;
+ posDeltaBuffer[i] = code >>> 1;
+ if (payloadLength != 0) {
+ if (payloadByteUpto + payloadLength > payloadBytes.length) {
+ payloadBytes = ArrayUtil.grow(payloadBytes, payloadByteUpto + payloadLength);
+ }
+ posIn.readBytes(payloadBytes, payloadByteUpto, payloadLength);
+ payloadByteUpto += payloadLength;
+ }
+ } else {
+ posDeltaBuffer[i] = code;
+ }
+
+ if (indexHasOffsets) {
+ int deltaCode = posIn.readVInt();
+ if ((deltaCode & 1) != 0) {
+ offsetLength = posIn.readVInt();
+ }
+ offsetStartDeltaBuffer[i] = deltaCode >>> 1;
+ offsetLengthBuffer[i] = offsetLength;
+ }
+ }
+ payloadByteUpto = 0;
+ } else {
+ pforUtil.decode(posIn, posDeltaBuffer);
+
+ if (indexHasPayloads && payIn != null) {
+ if (needsPayloads) {
+ pforUtil.decode(payIn, payloadLengthBuffer);
+ int numBytes = payIn.readVInt();
+
+ if (numBytes > payloadBytes.length) {
+ payloadBytes = ArrayUtil.grow(payloadBytes, numBytes);
+ }
+ payIn.readBytes(payloadBytes, 0, numBytes);
+ } else {
+ // this works, because when writing a vint block we always force the first length to be written
+ pforUtil.skip(payIn); // skip over lengths
+ int numBytes = payIn.readVInt(); // read length of payloadBytes
+ payIn.seek(payIn.getFilePointer() + numBytes); // skip over payloadBytes
+ }
+ payloadByteUpto = 0;
+ }
+
+ if (indexHasOffsets && payIn != null) {
+ if (needsOffsets) {
+ pforUtil.decode(payIn, offsetStartDeltaBuffer);
+ pforUtil.decode(payIn, offsetLengthBuffer);
+ } else {
+ // this works, because when writing a vint block we always force the first length to be written
+ pforUtil.skip(payIn); // skip over starts
+ pforUtil.skip(payIn); // skip over lengths
+ }
+ }
+ }
+ }
+
+ @Override
+ public void advanceShallow(int target) throws IOException {
+ if (target > nextSkipDoc) {
+ // always plus one to fix the result, since skip position in Lucene84SkipReader
+ // is a little different from MultiLevelSkipListReader
+ final int newDocUpto = skipper.skipTo(target) + 1;
+
+ if (newDocUpto > docUpto) {
+ // Skipper moved
+ assert newDocUpto % BLOCK_SIZE == 0 : "got " + newDocUpto;
+ docUpto = newDocUpto;
+ posDocUpTo = docUpto;
+
+ // Force to read next block
+ docBufferUpto = BLOCK_SIZE;
+ accum = skipper.getDoc();
+ posPendingFP = skipper.getPosPointer();
+ payPendingFP = skipper.getPayPointer();
+ posPendingCount = skipper.getPosBufferUpto();
+ lastStartOffset = 0; // new document
+ payloadByteUpto = skipper.getPayloadByteUpto(); // actually, this is just lastSkipEntry
+ seekTo = skipper.getDocPointer(); // delay the seek
+ }
+ // next time we call advance, this is used to
+ // foresee whether skipper is necessary.
+ nextSkipDoc = skipper.getNextSkipDoc();
+ }
+ assert nextSkipDoc >= target;
+ }
+
+ @Override
+ public Impacts getImpacts() throws IOException {
+ advanceShallow(doc);
+ return skipper.getImpacts();
+ }
+
+ @Override
+ public int nextDoc() throws IOException {
+ return advance(doc + 1);
+ }
+
+ @Override
+ public int advance(int target) throws IOException {
+ if (target > nextSkipDoc) {
+ advanceShallow(target);
+ }
+ if (docBufferUpto == BLOCK_SIZE) {
+ if (seekTo >= 0) {
+ docIn.seek(seekTo);
+ seekTo = -1;
+ isFreqsRead = true; // reset isFreqsRead
+ }
+ refillDocs();
+ }
+
+ // Now scan:
+ long doc;
+ while (true) {
+ doc = docBuffer[docBufferUpto];
+ docBufferUpto++;
+ docUpto++;
+
+ if (doc >= target) {
+ break;
+ }
+
+ if (docBufferUpto == BLOCK_SIZE) {
+ return this.doc = NO_MORE_DOCS;
+ }
+ }
+ position = 0;
+ lastStartOffset = 0;
+
+ return this.doc = (int) doc;
+ }
+
+ // TODO: in theory we could avoid loading frq block
+ // when not needed, ie, use skip data to load how far to
+ // seek the pos pointer ... instead of having to load frq
+ // blocks only to sum up how many positions to skip
+ private void skipPositions() throws IOException {
+ // Skip positions now:
+ int toSkip = posPendingCount - (int) freqBuffer[docBufferUpto-1];
+ // if (DEBUG) {
+ // System.out.println(" FPR.skipPositions: toSkip=" + toSkip);
+ // }
+
+ final int leftInBlock = BLOCK_SIZE - posBufferUpto;
+ if (toSkip < leftInBlock) {
+ int end = posBufferUpto + toSkip;
+ while(posBufferUpto < end) {
+ if (indexHasPayloads) {
+ payloadByteUpto += payloadLengthBuffer[posBufferUpto];
+ }
+ posBufferUpto++;
+ }
+ } else {
+ toSkip -= leftInBlock;
+ while(toSkip >= BLOCK_SIZE) {
+ assert posIn.getFilePointer() != lastPosBlockFP;
+ pforUtil.skip(posIn);
+
+ if (indexHasPayloads && payIn != null) {
+ // Skip payloadLength block:
+ pforUtil.skip(payIn);
+
+ // Skip payloadBytes block:
+ int numBytes = payIn.readVInt();
+ payIn.seek(payIn.getFilePointer() + numBytes);
+ }
+
+ if (indexHasOffsets && payIn != null) {
+ pforUtil.skip(payIn);
+ pforUtil.skip(payIn);
+ }
+ toSkip -= BLOCK_SIZE;
+ }
+ refillPositions();
+ payloadByteUpto = 0;
+ posBufferUpto = 0;
+ while(posBufferUpto < toSkip) {
+ if (indexHasPayloads) {
+ payloadByteUpto += payloadLengthBuffer[posBufferUpto];
+ }
+ posBufferUpto++;
+ }
+ }
+
+ position = 0;
+ lastStartOffset = 0;
+ }
+
+ @Override
+ public int nextPosition() throws IOException {
+ if (indexHasPos == false || needsPositions == false) {
+ return -1;
+ }
+
+ if (isFreqsRead == false) {
+ pforUtil.decode(docIn, freqBuffer); // read freqBuffer for this docs block
+ isFreqsRead = true;
+ }
+ while (posDocUpTo < docUpto) { // bring posPendingCount upto the current doc
+ posPendingCount += freqBuffer[docBufferUpto - (docUpto - posDocUpTo)];
+ posDocUpTo++;
+ }
+
+ assert posPendingCount > 0;
+
+ if (posPendingFP != -1) {
+ posIn.seek(posPendingFP);
+ posPendingFP = -1;
+
+ if (payPendingFP != -1 && payIn != null) {
+ payIn.seek(payPendingFP);
+ payPendingFP = -1;
+ }
+
+ // Force buffer refill:
+ posBufferUpto = BLOCK_SIZE;
+ }
+
+ if (posPendingCount > freqBuffer[docBufferUpto-1]) {
+ skipPositions();
+ posPendingCount = (int) freqBuffer[docBufferUpto-1];
+ }
+
+ if (posBufferUpto == BLOCK_SIZE) {
+ refillPositions();
+ posBufferUpto = 0;
+ }
+ position += posDeltaBuffer[posBufferUpto];
+
+ if (indexHasPayloads) {
+ payloadLength = (int) payloadLengthBuffer[posBufferUpto];
+ payload.bytes = payloadBytes;
+ payload.offset = payloadByteUpto;
+ payload.length = payloadLength;
+ payloadByteUpto += payloadLength;
+ }
+
+ if (indexHasOffsets && needsOffsets) {
+ startOffset = lastStartOffset + (int) offsetStartDeltaBuffer[posBufferUpto];
+ endOffset = startOffset + (int) offsetLengthBuffer[posBufferUpto];
+ lastStartOffset = startOffset;
+ }
+
+ posBufferUpto++;
+ posPendingCount--;
+ return position;
+ }
+
+ @Override
+ public int startOffset() {
+ return startOffset;
+ }
+
+ @Override
+ public int endOffset() {
+ return endOffset;
+ }
+
+ @Override
+ public BytesRef getPayload() {
+ if (payloadLength == 0) {
+ return null;
+ } else {
+ return payload;
+ }
+ }
+
+ @Override
+ public long cost() {
+ return docFreq;
+ }
+
+ }
+
+ @Override
+ public long ramBytesUsed() {
+ return BASE_RAM_BYTES_USED;
+ }
+
+ @Override
+ public void checkIntegrity() throws IOException {
+ if (docIn != null) {
+ CodecUtil.checksumEntireFile(docIn);
+ }
+ if (posIn != null) {
+ CodecUtil.checksumEntireFile(posIn);
+ }
+ if (payIn != null) {
+ CodecUtil.checksumEntireFile(payIn);
+ }
+ }
+
+ @Override
+ public String toString() {
+ return getClass().getSimpleName() + "(positions=" + (posIn != null) + ",payloads=" + (payIn != null) +")";
+ }
+}
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene84/Lucene84PostingsWriter.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene84/Lucene84PostingsWriter.java
new file mode 100644
index 00000000000..e42669af415
--- /dev/null
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene84/Lucene84PostingsWriter.java
@@ -0,0 +1,519 @@
+/*
+ * 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.
+ */
+package org.apache.lucene.codecs.lucene84;
+
+import static org.apache.lucene.codecs.lucene84.ForUtil.BLOCK_SIZE;
+import static org.apache.lucene.codecs.lucene84.Lucene84PostingsFormat.DOC_CODEC;
+import static org.apache.lucene.codecs.lucene84.Lucene84PostingsFormat.MAX_SKIP_LEVELS;
+import static org.apache.lucene.codecs.lucene84.Lucene84PostingsFormat.PAY_CODEC;
+import static org.apache.lucene.codecs.lucene84.Lucene84PostingsFormat.POS_CODEC;
+import static org.apache.lucene.codecs.lucene84.Lucene84PostingsFormat.TERMS_CODEC;
+import static org.apache.lucene.codecs.lucene84.Lucene84PostingsFormat.VERSION_CURRENT;
+
+import java.io.IOException;
+import java.nio.ByteOrder;
+
+import org.apache.lucene.codecs.BlockTermState;
+import org.apache.lucene.codecs.CodecUtil;
+import org.apache.lucene.codecs.CompetitiveImpactAccumulator;
+import org.apache.lucene.codecs.PushPostingsWriterBase;
+import org.apache.lucene.codecs.lucene84.Lucene84PostingsFormat.IntBlockTermState;
+import org.apache.lucene.index.CorruptIndexException;
+import org.apache.lucene.index.FieldInfo;
+import org.apache.lucene.index.IndexFileNames;
+import org.apache.lucene.index.IndexWriter;
+import org.apache.lucene.index.NumericDocValues;
+import org.apache.lucene.index.SegmentWriteState;
+import org.apache.lucene.store.DataOutput;
+import org.apache.lucene.store.IndexOutput;
+import org.apache.lucene.util.ArrayUtil;
+import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.IOUtils;
+
+/**
+ * Concrete class that writes docId(maybe frq,pos,offset,payloads) list
+ * with postings format.
+ *
+ * Postings list for each term will be stored separately.
+ *
+ * @see Lucene84SkipWriter for details about skipping setting and postings layout.
+ * @lucene.experimental
+ */
+public final class Lucene84PostingsWriter extends PushPostingsWriterBase {
+
+ IndexOutput docOut;
+ IndexOutput posOut;
+ IndexOutput payOut;
+
+ final static IntBlockTermState emptyState = new IntBlockTermState();
+ IntBlockTermState lastState;
+
+ // Holds starting file pointers for current term:
+ private long docStartFP;
+ private long posStartFP;
+ private long payStartFP;
+
+ final long[] docDeltaBuffer;
+ final long[] freqBuffer;
+ private int docBufferUpto;
+
+ final long[] posDeltaBuffer;
+ final long[] payloadLengthBuffer;
+ final long[] offsetStartDeltaBuffer;
+ final long[] offsetLengthBuffer;
+ private int posBufferUpto;
+
+ private byte[] payloadBytes;
+ private int payloadByteUpto;
+
+ private int lastBlockDocID;
+ private long lastBlockPosFP;
+ private long lastBlockPayFP;
+ private int lastBlockPosBufferUpto;
+ private int lastBlockPayloadByteUpto;
+
+ private int lastDocID;
+ private int lastPosition;
+ private int lastStartOffset;
+ private int docCount;
+
+ private final PForUtil pforUtil;
+ private final ForDeltaUtil forDeltaUtil;
+ private final Lucene84SkipWriter skipWriter;
+
+ private boolean fieldHasNorms;
+ private NumericDocValues norms;
+ private final CompetitiveImpactAccumulator competitiveFreqNormAccumulator = new CompetitiveImpactAccumulator();
+
+ /** Creates a postings writer */
+ public Lucene84PostingsWriter(SegmentWriteState state) throws IOException {
+
+ String docFileName = IndexFileNames.segmentFileName(state.segmentInfo.name, state.segmentSuffix, Lucene84PostingsFormat.DOC_EXTENSION);
+ docOut = state.directory.createOutput(docFileName, state.context);
+ IndexOutput posOut = null;
+ IndexOutput payOut = null;
+ boolean success = false;
+ try {
+ CodecUtil.writeIndexHeader(docOut, DOC_CODEC, VERSION_CURRENT,
+ state.segmentInfo.getId(), state.segmentSuffix);
+ ByteOrder byteOrder = ByteOrder.nativeOrder();
+ if (byteOrder == ByteOrder.BIG_ENDIAN) {
+ docOut.writeByte((byte) 'B');
+ } else if (byteOrder == ByteOrder.LITTLE_ENDIAN) {
+ docOut.writeByte((byte) 'L');
+ } else {
+ throw new Error();
+ }
+ final ForUtil forUtil = new ForUtil();
+ forDeltaUtil = new ForDeltaUtil(forUtil);
+ pforUtil = new PForUtil(forUtil);
+ if (state.fieldInfos.hasProx()) {
+ posDeltaBuffer = new long[BLOCK_SIZE];
+ String posFileName = IndexFileNames.segmentFileName(state.segmentInfo.name, state.segmentSuffix, Lucene84PostingsFormat.POS_EXTENSION);
+ posOut = state.directory.createOutput(posFileName, state.context);
+ CodecUtil.writeIndexHeader(posOut, POS_CODEC, VERSION_CURRENT,
+ state.segmentInfo.getId(), state.segmentSuffix);
+
+ if (state.fieldInfos.hasPayloads()) {
+ payloadBytes = new byte[128];
+ payloadLengthBuffer = new long[BLOCK_SIZE];
+ } else {
+ payloadBytes = null;
+ payloadLengthBuffer = null;
+ }
+
+ if (state.fieldInfos.hasOffsets()) {
+ offsetStartDeltaBuffer = new long[BLOCK_SIZE];
+ offsetLengthBuffer = new long[BLOCK_SIZE];
+ } else {
+ offsetStartDeltaBuffer = null;
+ offsetLengthBuffer = null;
+ }
+
+ if (state.fieldInfos.hasPayloads() || state.fieldInfos.hasOffsets()) {
+ String payFileName = IndexFileNames.segmentFileName(state.segmentInfo.name, state.segmentSuffix, Lucene84PostingsFormat.PAY_EXTENSION);
+ payOut = state.directory.createOutput(payFileName, state.context);
+ CodecUtil.writeIndexHeader(payOut, PAY_CODEC, VERSION_CURRENT,
+ state.segmentInfo.getId(), state.segmentSuffix);
+ }
+ } else {
+ posDeltaBuffer = null;
+ payloadLengthBuffer = null;
+ offsetStartDeltaBuffer = null;
+ offsetLengthBuffer = null;
+ payloadBytes = null;
+ }
+ this.payOut = payOut;
+ this.posOut = posOut;
+ success = true;
+ } finally {
+ if (!success) {
+ IOUtils.closeWhileHandlingException(docOut, posOut, payOut);
+ }
+ }
+
+ docDeltaBuffer = new long[BLOCK_SIZE];
+ freqBuffer = new long[BLOCK_SIZE];
+
+ // TODO: should we try skipping every 2/4 blocks...?
+ skipWriter = new Lucene84SkipWriter(MAX_SKIP_LEVELS,
+ BLOCK_SIZE,
+ state.segmentInfo.maxDoc(),
+ docOut,
+ posOut,
+ payOut);
+ }
+
+ @Override
+ public IntBlockTermState newTermState() {
+ return new IntBlockTermState();
+ }
+
+ @Override
+ public void init(IndexOutput termsOut, SegmentWriteState state) throws IOException {
+ CodecUtil.writeIndexHeader(termsOut, TERMS_CODEC, VERSION_CURRENT, state.segmentInfo.getId(), state.segmentSuffix);
+ termsOut.writeVInt(BLOCK_SIZE);
+ }
+
+ @Override
+ public int setField(FieldInfo fieldInfo) {
+ super.setField(fieldInfo);
+ skipWriter.setField(writePositions, writeOffsets, writePayloads);
+ lastState = emptyState;
+ fieldHasNorms = fieldInfo.hasNorms();
+ if (writePositions) {
+ if (writePayloads || writeOffsets) {
+ return 3; // doc + pos + pay FP
+ } else {
+ return 2; // doc + pos FP
+ }
+ } else {
+ return 1; // doc FP
+ }
+ }
+
+ @Override
+ public void startTerm(NumericDocValues norms) {
+ docStartFP = docOut.getFilePointer();
+ if (writePositions) {
+ posStartFP = posOut.getFilePointer();
+ if (writePayloads || writeOffsets) {
+ payStartFP = payOut.getFilePointer();
+ }
+ }
+ lastDocID = 0;
+ lastBlockDocID = -1;
+ skipWriter.resetSkip();
+ this.norms = norms;
+ competitiveFreqNormAccumulator.clear();
+ }
+
+ @Override
+ public void startDoc(int docID, int termDocFreq) throws IOException {
+ // Have collected a block of docs, and get a new doc.
+ // Should write skip data as well as postings list for
+ // current block.
+ if (lastBlockDocID != -1 && docBufferUpto == 0) {
+ skipWriter.bufferSkip(lastBlockDocID, competitiveFreqNormAccumulator, docCount,
+ lastBlockPosFP, lastBlockPayFP, lastBlockPosBufferUpto, lastBlockPayloadByteUpto);
+ competitiveFreqNormAccumulator.clear();
+ }
+
+ final int docDelta = docID - lastDocID;
+
+ if (docID < 0 || (docCount > 0 && docDelta <= 0)) {
+ throw new CorruptIndexException("docs out of order (" + docID + " <= " + lastDocID + " )", docOut);
+ }
+
+ docDeltaBuffer[docBufferUpto] = docDelta;
+ if (writeFreqs) {
+ freqBuffer[docBufferUpto] = termDocFreq;
+ }
+
+ docBufferUpto++;
+ docCount++;
+
+ if (docBufferUpto == BLOCK_SIZE) {
+ forDeltaUtil.encodeDeltas(docDeltaBuffer, docOut);
+ if (writeFreqs) {
+ pforUtil.encode(freqBuffer, docOut);
+ }
+ // NOTE: don't set docBufferUpto back to 0 here;
+ // finishDoc will do so (because it needs to see that
+ // the block was filled so it can save skip data)
+ }
+
+
+ lastDocID = docID;
+ lastPosition = 0;
+ lastStartOffset = 0;
+
+ long norm;
+ if (fieldHasNorms) {
+ boolean found = norms.advanceExact(docID);
+ if (found == false) {
+ // This can happen if indexing hits a problem after adding a doc to the
+ // postings but before buffering the norm. Such documents are written
+ // deleted and will go away on the first merge.
+ norm = 1L;
+ } else {
+ norm = norms.longValue();
+ assert norm != 0 : docID;
+ }
+ } else {
+ norm = 1L;
+ }
+
+ competitiveFreqNormAccumulator.add(writeFreqs ? termDocFreq : 1, norm);
+ }
+
+ @Override
+ public void addPosition(int position, BytesRef payload, int startOffset, int endOffset) throws IOException {
+ if (position > IndexWriter.MAX_POSITION) {
+ throw new CorruptIndexException("position=" + position + " is too large (> IndexWriter.MAX_POSITION=" + IndexWriter.MAX_POSITION + ")", docOut);
+ }
+ if (position < 0) {
+ throw new CorruptIndexException("position=" + position + " is < 0", docOut);
+ }
+ posDeltaBuffer[posBufferUpto] = position - lastPosition;
+ if (writePayloads) {
+ if (payload == null || payload.length == 0) {
+ // no payload
+ payloadLengthBuffer[posBufferUpto] = 0;
+ } else {
+ payloadLengthBuffer[posBufferUpto] = payload.length;
+ if (payloadByteUpto + payload.length > payloadBytes.length) {
+ payloadBytes = ArrayUtil.grow(payloadBytes, payloadByteUpto + payload.length);
+ }
+ System.arraycopy(payload.bytes, payload.offset, payloadBytes, payloadByteUpto, payload.length);
+ payloadByteUpto += payload.length;
+ }
+ }
+
+ if (writeOffsets) {
+ assert startOffset >= lastStartOffset;
+ assert endOffset >= startOffset;
+ offsetStartDeltaBuffer[posBufferUpto] = startOffset - lastStartOffset;
+ offsetLengthBuffer[posBufferUpto] = endOffset - startOffset;
+ lastStartOffset = startOffset;
+ }
+
+ posBufferUpto++;
+ lastPosition = position;
+ if (posBufferUpto == BLOCK_SIZE) {
+ pforUtil.encode(posDeltaBuffer, posOut);
+
+ if (writePayloads) {
+ pforUtil.encode(payloadLengthBuffer, payOut);
+ payOut.writeVInt(payloadByteUpto);
+ payOut.writeBytes(payloadBytes, 0, payloadByteUpto);
+ payloadByteUpto = 0;
+ }
+ if (writeOffsets) {
+ pforUtil.encode(offsetStartDeltaBuffer, payOut);
+ pforUtil.encode(offsetLengthBuffer, payOut);
+ }
+ posBufferUpto = 0;
+ }
+ }
+
+ @Override
+ public void finishDoc() throws IOException {
+ // Since we don't know df for current term, we had to buffer
+ // those skip data for each block, and when a new doc comes,
+ // write them to skip file.
+ if (docBufferUpto == BLOCK_SIZE) {
+ lastBlockDocID = lastDocID;
+ if (posOut != null) {
+ if (payOut != null) {
+ lastBlockPayFP = payOut.getFilePointer();
+ }
+ lastBlockPosFP = posOut.getFilePointer();
+ lastBlockPosBufferUpto = posBufferUpto;
+ lastBlockPayloadByteUpto = payloadByteUpto;
+ }
+ docBufferUpto = 0;
+ }
+ }
+
+ /** Called when we are done adding docs to this term */
+ @Override
+ public void finishTerm(BlockTermState _state) throws IOException {
+ IntBlockTermState state = (IntBlockTermState) _state;
+ assert state.docFreq > 0;
+
+ // TODO: wasteful we are counting this (counting # docs
+ // for this term) in two places?
+ assert state.docFreq == docCount: state.docFreq + " vs " + docCount;
+
+ // docFreq == 1, don't write the single docid/freq to a separate file along with a pointer to it.
+ final int singletonDocID;
+ if (state.docFreq == 1) {
+ // pulse the singleton docid into the term dictionary, freq is implicitly totalTermFreq
+ singletonDocID = (int) docDeltaBuffer[0];
+ } else {
+ singletonDocID = -1;
+ // vInt encode the remaining doc deltas and freqs:
+ for(int i=0;i<docBufferUpto;i++) {
+ final int docDelta = (int) docDeltaBuffer[i];
+ final int freq = (int) freqBuffer[i];
+ if (!writeFreqs) {
+ docOut.writeVInt(docDelta);
+ } else if (freq == 1) {
+ docOut.writeVInt((docDelta<<1)|1);
+ } else {
+ docOut.writeVInt(docDelta<<1);
+ docOut.writeVInt(freq);
+ }
+ }
+ }
+
+ final long lastPosBlockOffset;
+
+ if (writePositions) {
+ // totalTermFreq is just total number of positions(or payloads, or offsets)
+ // associated with current term.
+ assert state.totalTermFreq != -1;
+ if (state.totalTermFreq > BLOCK_SIZE) {
+ // record file offset for last pos in last block
+ lastPosBlockOffset = posOut.getFilePointer() - posStartFP;
+ } else {
+ lastPosBlockOffset = -1;
+ }
+ if (posBufferUpto > 0) {
+ // TODO: should we send offsets/payloads to
+ // .pay...? seems wasteful (have to store extra
+ // vLong for low (< BLOCK_SIZE) DF terms = vast vast
+ // majority)
+
+ // vInt encode the remaining positions/payloads/offsets:
+ int lastPayloadLength = -1; // force first payload length to be written
+ int lastOffsetLength = -1; // force first offset length to be written
+ int payloadBytesReadUpto = 0;
+ for(int i=0;i<posBufferUpto;i++) {
+ final int posDelta = (int) posDeltaBuffer[i];
+ if (writePayloads) {
+ final int payloadLength = (int) payloadLengthBuffer[i];
+ if (payloadLength != lastPayloadLength) {
+ lastPayloadLength = payloadLength;
+ posOut.writeVInt((posDelta<<1)|1);
+ posOut.writeVInt(payloadLength);
+ } else {
+ posOut.writeVInt(posDelta<<1);
+ }
+
+ if (payloadLength != 0) {
+ posOut.writeBytes(payloadBytes, payloadBytesReadUpto, payloadLength);
+ payloadBytesReadUpto += payloadLength;
+ }
+ } else {
+ posOut.writeVInt(posDelta);
+ }
+
+ if (writeOffsets) {
+ int delta = (int) offsetStartDeltaBuffer[i];
+ int length = (int) offsetLengthBuffer[i];
+ if (length == lastOffsetLength) {
+ posOut.writeVInt(delta << 1);
+ } else {
+ posOut.writeVInt(delta << 1 | 1);
+ posOut.writeVInt(length);
+ lastOffsetLength = length;
+ }
+ }
+ }
+
+ if (writePayloads) {
+ assert payloadBytesReadUpto == payloadByteUpto;
+ payloadByteUpto = 0;
+ }
+ }
+ } else {
+ lastPosBlockOffset = -1;
+ }
+
+ long skipOffset;
+ if (docCount > BLOCK_SIZE) {
+ skipOffset = skipWriter.writeSkip(docOut) - docStartFP;
+ } else {
+ skipOffset = -1;
+ }
+
+ state.docStartFP = docStartFP;
+ state.posStartFP = posStartFP;
+ state.payStartFP = payStartFP;
+ state.singletonDocID = singletonDocID;
+ state.skipOffset = skipOffset;
+ state.lastPosBlockOffset = lastPosBlockOffset;
+ docBufferUpto = 0;
+ posBufferUpto = 0;
+ lastDocID = 0;
+ docCount = 0;
+ }
+
+ @Override
+ public void encodeTerm(long[] longs, DataOutput out, FieldInfo fieldInfo, BlockTermState _state, boolean absolute) throws IOException {
+ IntBlockTermState state = (IntBlockTermState)_state;
+ if (absolute) {
+ lastState = emptyState;
+ }
+ longs[0] = state.docStartFP - lastState.docStartFP;
+ if (writePositions) {
+ longs[1] = state.posStartFP - lastState.posStartFP;
+ if (writePayloads || writeOffsets) {
+ longs[2] = state.payStartFP - lastState.payStartFP;
+ }
+ }
+ if (state.singletonDocID != -1) {
+ out.writeVInt(state.singletonDocID);
+ }
+ if (writePositions) {
+ if (state.lastPosBlockOffset != -1) {
+ out.writeVLong(state.lastPosBlockOffset);
+ }
+ }
+ if (state.skipOffset != -1) {
+ out.writeVLong(state.skipOffset);
+ }
+ lastState = state;
+ }
+
+ @Override
+ public void close() throws IOException {
+ // TODO: add a finish() at least to PushBase? DV too...?
+ boolean success = false;
+ try {
+ if (docOut != null) {
+ CodecUtil.writeFooter(docOut);
+ }
+ if (posOut != null) {
+ CodecUtil.writeFooter(posOut);
+ }
+ if (payOut != null) {
+ CodecUtil.writeFooter(payOut);
+ }
+ success = true;
+ } finally {
+ if (success) {
+ IOUtils.close(docOut, posOut, payOut);
+ } else {
+ IOUtils.closeWhileHandlingException(docOut, posOut, payOut);
+ }
+ docOut = posOut = payOut = null;
+ }
+ }
+}
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene84/Lucene84ScoreSkipReader.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene84/Lucene84ScoreSkipReader.java
new file mode 100644
index 00000000000..3a5a86f3bda
--- /dev/null
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene84/Lucene84ScoreSkipReader.java
@@ -0,0 +1,156 @@
+/*
+ * 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.
+ */
+package org.apache.lucene.codecs.lucene84;
+
+import java.io.IOException;
+import java.util.AbstractList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.RandomAccess;
+
+import org.apache.lucene.index.Impact;
+import org.apache.lucene.index.Impacts;
+import org.apache.lucene.store.ByteArrayDataInput;
+import org.apache.lucene.store.IndexInput;
+import org.apache.lucene.util.ArrayUtil;
+
+final class Lucene84ScoreSkipReader extends Lucene84SkipReader {
+
+ private final byte[][] impactData;
+ private final int[] impactDataLength;
+ private final ByteArrayDataInput badi = new ByteArrayDataInput();
+ private final Impacts impacts;
+ private int numLevels = 1;
+ private final MutableImpactList[] perLevelImpacts;
+
+ public Lucene84ScoreSkipReader(IndexInput skipStream, int maxSkipLevels,
+ boolean hasPos, boolean hasOffsets, boolean hasPayloads) {
+ super(skipStream, maxSkipLevels, hasPos, hasOffsets, hasPayloads);
+ this.impactData = new byte[maxSkipLevels][];
+ Arrays.fill(impactData, new byte[0]);
+ this.impactDataLength = new int[maxSkipLevels];
+ this.perLevelImpacts = new MutableImpactList[maxSkipLevels];
+ for (int i = 0; i < perLevelImpacts.length; ++i) {
+ perLevelImpacts[i] = new MutableImpactList();
+ }
+ impacts = new Impacts() {
+
+ @Override
+ public int numLevels() {
+ return numLevels;
+ }
+
+ @Override
+ public int getDocIdUpTo(int level) {
+ return skipDoc[level];
+ }
+
+ @Override
+ public List<Impact> getImpacts(int level) {
+ assert level < numLevels;
+ if (impactDataLength[level] > 0) {
+ badi.reset(impactData[level], 0, impactDataLength[level]);
+ perLevelImpacts[level] = readImpacts(badi, perLevelImpacts[level]);
+ impactDataLength[level] = 0;
+ }
+ return perLevelImpacts[level];
+ }
+ };
+ }
+
+ @Override
+ public int skipTo(int target) throws IOException {
+ int result = super.skipTo(target);
+ if (numberOfSkipLevels > 0) {
+ numLevels = numberOfSkipLevels;
+ } else {
+ // End of postings don't have skip data anymore, so we fill with dummy data
+ // like SlowImpactsEnum.
+ numLevels = 1;
+ perLevelImpacts[0].length = 1;
+ perLevelImpacts[0].impacts[0].freq = Integer.MAX_VALUE;
+ perLevelImpacts[0].impacts[0].norm = 1L;
+ impactDataLength[0] = 0;
+ }
+ return result;
+ }
+
+ Impacts getImpacts() {
+ return impacts;
+ }
+
+ @Override
+ protected void readImpacts(int level, IndexInput skipStream) throws IOException {
+ int length = skipStream.readVInt();
+ if (impactData[level].length < length) {
+ impactData[level] = new byte[ArrayUtil.oversize(length, Byte.BYTES)];
+ }
+ skipStream.readBytes(impactData[level], 0, length);
+ impactDataLength[level] = length;
+ }
+
+ static MutableImpactList readImpacts(ByteArrayDataInput in, MutableImpactList reuse) {
+ int maxNumImpacts = in.length(); // at most one impact per byte
+ if (reuse.impacts.length < maxNumImpacts) {
+ int oldLength = reuse.impacts.length;
+ reuse.impacts = ArrayUtil.grow(reuse.impacts, maxNumImpacts);
+ for (int i = oldLength; i < reuse.impacts.length; ++i) {
+ reuse.impacts[i] = new Impact(Integer.MAX_VALUE, 1L);
+ }
+ }
+
+ int freq = 0;
+ long norm = 0;
+ int length = 0;
+ while (in.getPosition() < in.length()) {
+ int freqDelta = in.readVInt();
+ if ((freqDelta & 0x01) != 0) {
+ freq += 1 + (freqDelta >>> 1);
+ try {
+ norm += 1 + in.readZLong();
+ } catch (IOException e) {
+ throw new RuntimeException(e); // cannot happen on a BADI
+ }
+ } else {
+ freq += 1 + (freqDelta >>> 1);
+ norm++;
+ }
+ Impact impact = reuse.impacts[length];
+ impact.freq = freq;
+ impact.norm = norm;
+ length++;
+ }
+ reuse.length = length;
+ return reuse;
+ }
+
+ static class MutableImpactList extends AbstractList<Impact> implements RandomAccess {
+ int length = 1;
+ Impact[] impacts = new Impact[] { new Impact(Integer.MAX_VALUE, 1L) };
+
+ @Override
+ public Impact get(int index) {
+ return impacts[index];
+ }
+
+ @Override
+ public int size() {
+ return length;
+ }
+ }
+
+}
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene84/Lucene84SkipReader.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene84/Lucene84SkipReader.java
new file mode 100644
index 00000000000..9837645adbd
--- /dev/null
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene84/Lucene84SkipReader.java
@@ -0,0 +1,204 @@
+/*
+ * 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.
+ */
+package org.apache.lucene.codecs.lucene84;
+
+
+import java.io.IOException;
+import java.util.Arrays;
+
+import org.apache.lucene.codecs.MultiLevelSkipListReader;
+import org.apache.lucene.store.IndexInput;
+
+/**
+ * Implements the skip list reader for block postings format
+ * that stores positions and payloads.
+ *
+ * Although this skipper uses MultiLevelSkipListReader as an interface,
+ * its definition of skip position will be a little different.
+ *
+ * For example, when skipInterval = blockSize = 3, df = 2*skipInterval = 6,
+ *
+ * 0 1 2 3 4 5
+ * d d d d d d (posting list)
+ * ^ ^ (skip point in MultiLeveSkipWriter)
+ * ^ (skip point in Lucene84SkipWriter)
+ *
+ * In this case, MultiLevelSkipListReader will use the last document as a skip point,
+ * while Lucene84SkipReader should assume no skip point will comes.
+ *
+ * If we use the interface directly in Lucene84SkipReader, it may silly try to read
+ * another skip data after the only skip point is loaded.
+ *
+ * To illustrate this, we can call skipTo(d[5]), since skip point d[3] has smaller docId,
+ * and numSkipped+blockSize== df, the MultiLevelSkipListReader will assume the skip list
+ * isn't exhausted yet, and try to load a non-existed skip point
+ *
+ * Therefore, we'll trim df before passing it to the interface. see trim(int)
+ *
+ */
+class Lucene84SkipReader extends MultiLevelSkipListReader {
+ private long docPointer[];
+ private long posPointer[];
+ private long payPointer[];
+ private int posBufferUpto[];
+ private int payloadByteUpto[];
+
+ private long lastPosPointer;
+ private long lastPayPointer;
+ private int lastPayloadByteUpto;
+ private long lastDocPointer;
+ private int lastPosBufferUpto;
+
+ public Lucene84SkipReader(
+ IndexInput skipStream, int maxSkipLevels,
+ boolean hasPos, boolean hasOffsets, boolean hasPayloads) {
+ super(skipStream, maxSkipLevels, ForUtil.BLOCK_SIZE, 8);
+ docPointer = new long[maxSkipLevels];
+ if (hasPos) {
+ posPointer = new long[maxSkipLevels];
+ posBufferUpto = new int[maxSkipLevels];
+ if (hasPayloads) {
+ payloadByteUpto = new int[maxSkipLevels];
+ } else {
+ payloadByteUpto = null;
+ }
+ if (hasOffsets || hasPayloads) {
+ payPointer = new long[maxSkipLevels];
+ } else {
+ payPointer = null;
+ }
+ } else {
+ posPointer = null;
+ }
+ }
+
+ /**
+ * Trim original docFreq to tell skipReader read proper number of skip points.
+ *
+ * Since our definition in Lucene84Skip* is a little different from MultiLevelSkip*
+ * This trimmed docFreq will prevent skipReader from:
+ * 1. silly reading a non-existed skip point after the last block boundary
+ * 2. moving into the vInt block
+ *
+ */
+ protected int trim(int df) {
+ return df % ForUtil.BLOCK_SIZE == 0? df - 1: df;
+ }
+
+ public void init(long skipPointer, long docBasePointer, long posBasePointer, long payBasePointer, int df) throws IOException {
+ super.init(skipPointer, trim(df));
+ lastDocPointer = docBasePointer;
+ lastPosPointer = posBasePointer;
+ lastPayPointer = payBasePointer;
+
+ Arrays.fill(docPointer, docBasePointer);
+ if (posPointer != null) {
+ Arrays.fill(posPointer, posBasePointer);
+ if (payPointer != null) {
+ Arrays.fill(payPointer, payBasePointer);
+ }
+ } else {
+ assert posBasePointer == 0;
+ }
+ }
+
+ /** Returns the doc pointer of the doc to which the last call of
+ * {@link MultiLevelSkipListReader#skipTo(int)} has skipped. */
+ public long getDocPointer() {
+ return lastDocPointer;
+ }
+
+ public long getPosPointer() {
+ return lastPosPointer;
+ }
+
+ public int getPosBufferUpto() {
+ return lastPosBufferUpto;
+ }
+
+ public long getPayPointer() {
+ return lastPayPointer;
+ }
+
+ public int getPayloadByteUpto() {
+ return lastPayloadByteUpto;
+ }
+
+ public int getNextSkipDoc() {
+ return skipDoc[0];
+ }
+
+ @Override
+ protected void seekChild(int level) throws IOException {
+ super.seekChild(level);
+ docPointer[level] = lastDocPointer;
+ if (posPointer != null) {
+ posPointer[level] = lastPosPointer;
+ posBufferUpto[level] = lastPosBufferUpto;
+ if (payloadByteUpto != null) {
+ payloadByteUpto[level] = lastPayloadByteUpto;
+ }
+ if (payPointer != null) {
+ payPointer[level] = lastPayPointer;
+ }
+ }
+ }
+
+ @Override
+ protected void setLastSkipData(int level) {
+ super.setLastSkipData(level);
+ lastDocPointer = docPointer[level];
+
+ if (posPointer != null) {
+ lastPosPointer = posPointer[level];
+ lastPosBufferUpto = posBufferUpto[level];
+ if (payPointer != null) {
+ lastPayPointer = payPointer[level];
+ }
+ if (payloadByteUpto != null) {
+ lastPayloadByteUpto = payloadByteUpto[level];
+ }
+ }
+ }
+
+ @Override
+ protected int readSkipData(int level, IndexInput skipStream) throws IOException {
+ int delta = skipStream.readVInt();
+ docPointer[level] += skipStream.readVLong();
+
+ if (posPointer != null) {
+ posPointer[level] += skipStream.readVLong();
+ posBufferUpto[level] = skipStream.readVInt();
+
+ if (payloadByteUpto != null) {
+ payloadByteUpto[level] = skipStream.readVInt();
+ }
+
+ if (payPointer != null) {
+ payPointer[level] += skipStream.readVLong();
+ }
+ }
+ readImpacts(level, skipStream);
+ return delta;
+ }
+
+ // The default impl skips impacts
+ protected void readImpacts(int level, IndexInput skipStream) throws IOException {
+ skipStream.skipBytes(skipStream.readVInt());
+ }
+
+}
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene84/Lucene84SkipWriter.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene84/Lucene84SkipWriter.java
new file mode 100644
index 00000000000..75131507844
--- /dev/null
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene84/Lucene84SkipWriter.java
@@ -0,0 +1,225 @@
+/*
+ * 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.
+ */
+package org.apache.lucene.codecs.lucene84;
+
+
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.Set;
+import java.util.SortedSet;
+
+import org.apache.lucene.codecs.CompetitiveImpactAccumulator;
+import org.apache.lucene.codecs.MultiLevelSkipListWriter;
+import org.apache.lucene.index.Impact;
+import org.apache.lucene.store.ByteBuffersDataOutput;
+import org.apache.lucene.store.DataOutput;
+import org.apache.lucene.store.IndexOutput;
+
+/**
+ * Write skip lists with multiple levels, and support skip within block ints.
+ *
+ * Assume that docFreq = 28, skipInterval = blockSize = 12
+ *
+ * | block#0 | | block#1 | |vInts|
+ * d d d d d d d d d d d d d d d d d d d d d d d d d d d d (posting list)
+ * ^ ^ (level 0 skip point)
+ *
+ * Note that skipWriter will ignore first document in block#0, since
+ * it is useless as a skip point. Also, we'll never skip into the vInts
+ * block, only record skip data at the start its start point(if it exist).
+ *
+ * For each skip point, we will record:
+ * 1. docID in former position, i.e. for position 12, record docID[11], etc.
+ * 2. its related file points(position, payload),
+ * 3. related numbers or uptos(position, payload).
+ * 4. start offset.
+ *
+ */
+final class Lucene84SkipWriter extends MultiLevelSkipListWriter {
+ private int[] lastSkipDoc;
+ private long[] lastSkipDocPointer;
+ private long[] lastSkipPosPointer;
+ private long[] lastSkipPayPointer;
+ private int[] lastPayloadByteUpto;
+
+ private final IndexOutput docOut;
+ private final IndexOutput posOut;
+ private final IndexOutput payOut;
+
+ private int curDoc;
+ private long curDocPointer;
+ private long curPosPointer;
+ private long curPayPointer;
+ private int curPosBufferUpto;
+ private int curPayloadByteUpto;
+ private CompetitiveImpactAccumulator[] curCompetitiveFreqNorms;
+ private boolean fieldHasPositions;
+ private boolean fieldHasOffsets;
+ private boolean fieldHasPayloads;
+
+ public Lucene84SkipWriter(int maxSkipLevels, int blockSize, int docCount, IndexOutput docOut, IndexOutput posOut, IndexOutput payOut) {
+ super(blockSize, 8, maxSkipLevels, docCount);
+ this.docOut = docOut;
+ this.posOut = posOut;
+ this.payOut = payOut;
+
+ lastSkipDoc = new int[maxSkipLevels];
+ lastSkipDocPointer = new long[maxSkipLevels];
+ if (posOut != null) {
+ lastSkipPosPointer = new long[maxSkipLevels];
+ if (payOut != null) {
+ lastSkipPayPointer = new long[maxSkipLevels];
+ }
+ lastPayloadByteUpto = new int[maxSkipLevels];
+ }
+ curCompetitiveFreqNorms = new CompetitiveImpactAccumulator[maxSkipLevels];
+ for (int i = 0; i < maxSkipLevels; ++i) {
+ curCompetitiveFreqNorms[i] = new CompetitiveImpactAccumulator();
+ }
+ }
+
+ public void setField(boolean fieldHasPositions, boolean fieldHasOffsets, boolean fieldHasPayloads) {
+ this.fieldHasPositions = fieldHasPositions;
+ this.fieldHasOffsets = fieldHasOffsets;
+ this.fieldHasPayloads = fieldHasPayloads;
+ }
+
+ // tricky: we only skip data for blocks (terms with more than 128 docs), but re-init'ing the skipper
+ // is pretty slow for rare terms in large segments as we have to fill O(log #docs in segment) of junk.
+ // this is the vast majority of terms (worst case: ID field or similar). so in resetSkip() we save
+ // away the previous pointers, and lazy-init only if we need to buffer skip data for the term.
+ private boolean initialized;
+ long lastDocFP;
+ long lastPosFP;
+ long lastPayFP;
+
+ @Override
+ public void resetSkip() {
+ lastDocFP = docOut.getFilePointer();
+ if (fieldHasPositions) {
+ lastPosFP = posOut.getFilePointer();
+ if (fieldHasOffsets || fieldHasPayloads) {
+ lastPayFP = payOut.getFilePointer();
+ }
+ }
+ if (initialized) {
+ for (CompetitiveImpactAccumulator acc : curCompetitiveFreqNorms) {
+ acc.clear();
+ }
+ }
+ initialized = false;
+ }
+
+ private void initSkip() {
+ if (!initialized) {
+ super.resetSkip();
+ Arrays.fill(lastSkipDoc, 0);
+ Arrays.fill(lastSkipDocPointer, lastDocFP);
+ if (fieldHasPositions) {
+ Arrays.fill(lastSkipPosPointer, lastPosFP);
+ if (fieldHasPayloads) {
+ Arrays.fill(lastPayloadByteUpto, 0);
+ }
+ if (fieldHasOffsets || fieldHasPayloads) {
+ Arrays.fill(lastSkipPayPointer, lastPayFP);
+ }
+ }
+ // sets of competitive freq,norm pairs should be empty at this point
+ assert Arrays.stream(curCompetitiveFreqNorms)
+ .map(CompetitiveImpactAccumulator::getCompetitiveFreqNormPairs)
+ .mapToInt(Set::size)
+ .sum() == 0;
+ initialized = true;
+ }
+ }
+
+ /**
+ * Sets the values for the current skip data.
+ */
+ public void bufferSkip(int doc, CompetitiveImpactAccumulator competitiveFreqNorms,
+ int numDocs, long posFP, long payFP, int posBufferUpto, int payloadByteUpto) throws IOException {
+ initSkip();
+ this.curDoc = doc;
+ this.curDocPointer = docOut.getFilePointer();
+ this.curPosPointer = posFP;
+ this.curPayPointer = payFP;
+ this.curPosBufferUpto = posBufferUpto;
+ this.curPayloadByteUpto = payloadByteUpto;
+ this.curCompetitiveFreqNorms[0].addAll(competitiveFreqNorms);
+ bufferSkip(numDocs);
+ }
+
+ private final ByteBuffersDataOutput freqNormOut = ByteBuffersDataOutput.newResettableInstance();
+
+ @Override
+ protected void writeSkipData(int level, DataOutput skipBuffer) throws IOException {
+
+ int delta = curDoc - lastSkipDoc[level];
+
+ skipBuffer.writeVInt(delta);
+ lastSkipDoc[level] = curDoc;
+
+ skipBuffer.writeVLong(curDocPointer - lastSkipDocPointer[level]);
+ lastSkipDocPointer[level] = curDocPointer;
+
+ if (fieldHasPositions) {
+
+ skipBuffer.writeVLong(curPosPointer - lastSkipPosPointer[level]);
+ lastSkipPosPointer[level] = curPosPointer;
+ skipBuffer.writeVInt(curPosBufferUpto);
+
+ if (fieldHasPayloads) {
+ skipBuffer.writeVInt(curPayloadByteUpto);
+ }
+
+ if (fieldHasOffsets || fieldHasPayloads) {
+ skipBuffer.writeVLong(curPayPointer - lastSkipPayPointer[level]);
+ lastSkipPayPointer[level] = curPayPointer;
+ }
+ }
+
+ CompetitiveImpactAccumulator competitiveFreqNorms = curCompetitiveFreqNorms[level];
+ assert competitiveFreqNorms.getCompetitiveFreqNormPairs().size() > 0;
+ if (level + 1 < numberOfSkipLevels) {
+ curCompetitiveFreqNorms[level + 1].addAll(competitiveFreqNorms);
+ }
+ writeImpacts(competitiveFreqNorms, freqNormOut);
+ skipBuffer.writeVInt(Math.toIntExact(freqNormOut.size()));
+ freqNormOut.copyTo(skipBuffer);
+ freqNormOut.reset();
+ competitiveFreqNorms.clear();
+ }
+
+ static void writeImpacts(CompetitiveImpactAccumulator acc, DataOutput out) throws IOException {
+ SortedSet<Impact> impacts = acc.getCompetitiveFreqNormPairs();
+ Impact previous = new Impact(0, 0);
+ for (Impact impact : impacts) {
+ assert impact.freq > previous.freq;
+ assert Long.compareUnsigned(impact.norm, previous.norm) > 0;
+ int freqDelta = impact.freq - previous.freq - 1;
+ long normDelta = impact.norm - previous.norm - 1;
+ if (normDelta == 0) {
+ // most of time, norm only increases by 1, so we can fold everything in a single byte
+ out.writeVInt(freqDelta << 1);
+ } else {
+ out.writeVInt((freqDelta << 1) | 1);
+ out.writeZLong(normDelta);
+ }
+ previous = impact;
+ }
+ }
+}
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene84/PForUtil.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene84/PForUtil.java
new file mode 100644
index 00000000000..81fab5ec988
--- /dev/null
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene84/PForUtil.java
@@ -0,0 +1,130 @@
+/*
+ * 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.
+ */
+package org.apache.lucene.codecs.lucene84;
+
+import java.io.IOException;
+import java.util.Arrays;
+
+import org.apache.lucene.store.DataInput;
+import org.apache.lucene.store.DataOutput;
+import org.apache.lucene.util.packed.PackedInts;
+
+/**
+ * Utility class to encode sequences of 128 small positive integers.
+ */
+final class PForUtil {
+
+ static boolean allEqual(long[] l) {
+ for (int i = 1; i < ForUtil.BLOCK_SIZE; ++i) {
+ if (l[i] != l[0]) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ private final ForUtil forUtil;
+
+ PForUtil(ForUtil forUtil) {
+ this.forUtil = forUtil;
+ }
+
+ /**
+ * Encode 128 integers from {@code longs} into {@code out}.
+ */
+ void encode(long[] longs, DataOutput out) throws IOException {
+ // At most 3 exceptions
+ final long[] top4 = new long[4];
+ Arrays.fill(top4, -1L);
+ for (int i = 0; i < ForUtil.BLOCK_SIZE; ++i) {
+ if (longs[i] > top4[0]) {
+ top4[0] = longs[i];
+ Arrays.sort(top4); // For only 4 entries we just sort on every iteration instead of maintaining a PQ
+ }
+ }
+
+ final int maxBitsRequired = PackedInts.bitsRequired(top4[3]);
+ // We store the patch on a byte, so we can't decrease the number of bits required by more than 8
+ final int patchedBitsRequired = Math.max(PackedInts.bitsRequired(top4[0]), maxBitsRequired - 8);
+ int numExceptions = 0;
+ final long maxUnpatchedValue = (1L << patchedBitsRequired) - 1;
+ for (int i = 1; i < 4; ++i) {
+ if (top4[i] > maxUnpatchedValue) {
+ numExceptions++;
+ }
+ }
+ final byte[] exceptions = new byte[numExceptions*2];
+ if (numExceptions > 0) {
+ int exceptionCount = 0;
+ for (int i = 0; i < ForUtil.BLOCK_SIZE; ++i) {
+ if (longs[i] > (1L << patchedBitsRequired) - 1) {
+ exceptions[exceptionCount*2] = (byte) i;
+ exceptions[exceptionCount*2+1] = (byte) (longs[i] >>> patchedBitsRequired);
+ longs[i] &= maxUnpatchedValue;
+ exceptionCount++;
+ }
+ }
+ assert exceptionCount == numExceptions : exceptionCount + " " + numExceptions;
+ }
+
+ if (allEqual(longs) && maxBitsRequired <= 8) {
+ for (int i = 0; i < numExceptions; ++i) {
+ exceptions[2*i + 1] = (byte) (Byte.toUnsignedLong(exceptions[2*i + 1]) << patchedBitsRequired);
+ }
+ out.writeByte((byte) (numExceptions << 5));
+ out.writeVLong(longs[0]);
+ } else {
+ final int token = (numExceptions << 5) | patchedBitsRequired;
+ out.writeByte((byte) token);
+ forUtil.encode(longs, patchedBitsRequired, out);
+ }
+ out.writeBytes(exceptions, exceptions.length);
+ }
+
+ /**
+ * Decode 128 integers into {@code ints}.
+ */
+ void decode(DataInput in, long[] longs) throws IOException {
+ final int token = Byte.toUnsignedInt(in.readByte());
+ final int bitsPerValue = token & 0x1f;
+ final int numExceptions = token >>> 5;
+ if (bitsPerValue == 0) {
+ Arrays.fill(longs, 0, ForUtil.BLOCK_SIZE, in.readVLong());
+ } else {
+ forUtil.decode(bitsPerValue, in, longs);
+ }
+ for (int i = 0; i < numExceptions; ++i) {
+ longs[Byte.toUnsignedInt(in.readByte())] |= Byte.toUnsignedLong(in.readByte()) << bitsPerValue;
+ }
+ }
+
+ /**
+ * Skip 128 integers.
+ */
+ void skip(DataInput in) throws IOException {
+ final int token = Byte.toUnsignedInt(in.readByte());
+ final int bitsPerValue = token & 0x1f;
+ final int numExceptions = token >>> 5;
+ if (bitsPerValue == 0) {
+ in.readVLong();
+ in.skipBytes((numExceptions << 1));
+ } else {
+ in.skipBytes(forUtil.numBytes(bitsPerValue) + (numExceptions << 1));
+ }
+ }
+
+}
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene84/gen_ForUtil.py b/lucene/core/src/java/org/apache/lucene/codecs/lucene84/gen_ForUtil.py
new file mode 100644
index 00000000000..dfcfa01fedb
--- /dev/null
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene84/gen_ForUtil.py
@@ -0,0 +1,481 @@
+#! /usr/bin/env python
+
+# 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.
+
+from fractions import gcd
+
+"""Code generation for ForUtil.java"""
+
+MAX_SPECIALIZED_BITS_PER_VALUE = 24
+OUTPUT_FILE = "ForUtil.java"
+HEADER = """// This file has been automatically generated, DO NOT EDIT
+
+/*
+ * 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.
+ */
+package org.apache.lucene.codecs.lucene84;
+
+import java.io.IOException;
+import java.util.Arrays;
+
+import org.apache.lucene.store.DataInput;
+import org.apache.lucene.store.DataOutput;
+
+// Inspired from https://fulmicoton.com/posts/bitpacking/
+// Encodes multiple integers in a long to get SIMD-like speedups.
+// If bitsPerValue <= 8 then we pack 8 ints per long
+// else if bitsPerValue <= 16 we pack 4 ints per long
+// else we pack 2 ints per long
+final class ForUtil {
+
+ static final int BLOCK_SIZE = 128;
+ private static final int BLOCK_SIZE_LOG2 = 7;
+
+ private static long expandMask32(long mask32) {
+ return mask32 | (mask32 << 32);
+ }
+
+ private static long expandMask16(long mask16) {
+ return expandMask32(mask16 | (mask16 << 16));
+ }
+
+ private static long expandMask8(long mask8) {
+ return expandMask16(mask8 | (mask8 << 8));
+ }
+
+ private static long mask32(int bitsPerValue) {
+ return expandMask32((1L << bitsPerValue) - 1);
+ }
+
+ private static long mask16(int bitsPerValue) {
+ return expandMask16((1L << bitsPerValue) - 1);
+ }
+
+ private static long mask8(int bitsPerValue) {
+ return expandMask8((1L << bitsPerValue) - 1);
+ }
+
+ private static void expand8(long[] arr) {
+ for (int i = 0; i < 16; ++i) {
+ long l = arr[i];
+ arr[i] = (l >>> 56) & 0xFFL;
+ arr[16+i] = (l >>> 48) & 0xFFL;
+ arr[32+i] = (l >>> 40) & 0xFFL;
+ arr[48+i] = (l >>> 32) & 0xFFL;
+ arr[64+i] = (l >>> 24) & 0xFFL;
+ arr[80+i] = (l >>> 16) & 0xFFL;
+ arr[96+i] = (l >>> 8) & 0xFFL;
+ arr[112+i] = l & 0xFFL;
+ }
+ }
+
+ private static void expand8To32(long[] arr) {
+ for (int i = 0; i < 16; ++i) {
+ long l = arr[i];
+ arr[i] = (l >>> 24) & 0x000000FF000000FFL;
+ arr[16+i] = (l >>> 16) & 0x000000FF000000FFL;
+ arr[32+i] = (l >>> 8) & 0x000000FF000000FFL;
+ arr[48+i] = l & 0x000000FF000000FFL;
+ }
+ }
+
+ private static void collapse8(long[] arr) {
+ for (int i = 0; i < 16; ++i) {
+ arr[i] = (arr[i] << 56) | (arr[16+i] << 48) | (arr[32+i] << 40) | (arr[48+i] << 32) | (arr[64+i] << 24) | (arr[80+i] << 16) | (arr[96+i] << 8) | arr[112+i];
+ }
+ }
+
+ private static void expand16(long[] arr) {
+ for (int i = 0; i < 32; ++i) {
+ long l = arr[i];
+ arr[i] = (l >>> 48) & 0xFFFFL;
+ arr[32+i] = (l >>> 32) & 0xFFFFL;
+ arr[64+i] = (l >>> 16) & 0xFFFFL;
+ arr[96+i] = l & 0xFFFFL;
+ }
+ }
+
+ private static void expand16To32(long[] arr) {
+ for (int i = 0; i < 32; ++i) {
+ long l = arr[i];
+ arr[i] = (l >>> 16) & 0x0000FFFF0000FFFFL;
+ arr[32+i] = l & 0x0000FFFF0000FFFFL;
+ }
+ }
+
+ private static void collapse16(long[] arr) {
+ for (int i = 0; i < 32; ++i) {
+ arr[i] = (arr[i] << 48) | (arr[32+i] << 32) | (arr[64+i] << 16) | arr[96+i];
+ }
+ }
+
+ private static void expand32(long[] arr) {
+ for (int i = 0; i < 64; ++i) {
+ long l = arr[i];
+ arr[i] = l >>> 32;
+ arr[64 + i] = l & 0xFFFFFFFFL;
+ }
+ }
+
+ private static void collapse32(long[] arr) {
+ for (int i = 0; i < 64; ++i) {
+ arr[i] = (arr[i] << 32) | arr[64+i];
+ }
+ }
+
+ private static void prefixSum8(long[] arr, long base) {
+ expand8To32(arr);
+ prefixSum32(arr, base);
+ }
+
+ private static void prefixSum16(long[] arr, long base) {
+ // We need to move to the next primitive size to avoid overflows
+ expand16To32(arr);
+ prefixSum32(arr, base);
+ }
+
+ private static void prefixSum32(long[] arr, long base) {
+ arr[0] += base << 32;
+ innerPrefixSum32(arr);
+ expand32(arr);
+ final long l = arr[BLOCK_SIZE/2-1];
+ for (int i = BLOCK_SIZE/2; i < BLOCK_SIZE; ++i) {
+ arr[i] += l;
+ }
+ }
+
+ // For some reason unrolling seems to help
+ private static void innerPrefixSum32(long[] arr) {
+ arr[1] += arr[0];
+ arr[2] += arr[1];
+ arr[3] += arr[2];
+ arr[4] += arr[3];
+ arr[5] += arr[4];
+ arr[6] += arr[5];
+ arr[7] += arr[6];
+ arr[8] += arr[7];
+ arr[9] += arr[8];
+ arr[10] += arr[9];
+ arr[11] += arr[10];
+ arr[12] += arr[11];
+ arr[13] += arr[12];
+ arr[14] += arr[13];
+ arr[15] += arr[14];
+ arr[16] += arr[15];
+ arr[17] += arr[16];
+ arr[18] += arr[17];
+ arr[19] += arr[18];
+ arr[20] += arr[19];
+ arr[21] += arr[20];
+ arr[22] += arr[21];
+ arr[23] += arr[22];
+ arr[24] += arr[23];
+ arr[25] += arr[24];
+ arr[26] += arr[25];
+ arr[27] += arr[26];
+ arr[28] += arr[27];
+ arr[29] += arr[28];
+ arr[30] += arr[29];
+ arr[31] += arr[30];
+ arr[32] += arr[31];
+ arr[33] += arr[32];
+ arr[34] += arr[33];
+ arr[35] += arr[34];
+ arr[36] += arr[35];
+ arr[37] += arr[36];
+ arr[38] += arr[37];
+ arr[39] += arr[38];
+ arr[40] += arr[39];
+ arr[41] += arr[40];
+ arr[42] += arr[41];
+ arr[43] += arr[42];
+ arr[44] += arr[43];
+ arr[45] += arr[44];
+ arr[46] += arr[45];
+ arr[47] += arr[46];
+ arr[48] += arr[47];
+ arr[49] += arr[48];
+ arr[50] += arr[49];
+ arr[51] += arr[50];
+ arr[52] += arr[51];
+ arr[53] += arr[52];
+ arr[54] += arr[53];
+ arr[55] += arr[54];
+ arr[56] += arr[55];
+ arr[57] += arr[56];
+ arr[58] += arr[57];
+ arr[59] += arr[58];
+ arr[60] += arr[59];
+ arr[61] += arr[60];
+ arr[62] += arr[61];
+ arr[63] += arr[62];
+ }
+
+ private final long[] tmp = new long[BLOCK_SIZE/2];
+
+ /**
+ * Encode 128 integers from {@code longs} into {@code out}.
+ */
+ void encode(long[] longs, int bitsPerValue, DataOutput out) throws IOException {
+ final int nextPrimitive;
+ final int numLongs;
+ if (bitsPerValue <= 8) {
+ nextPrimitive = 8;
+ numLongs = BLOCK_SIZE / 8;
+ collapse8(longs);
+ } else if (bitsPerValue <= 16) {
+ nextPrimitive = 16;
+ numLongs = BLOCK_SIZE / 4;
+ collapse16(longs);
+ } else {
+ nextPrimitive = 32;
+ numLongs = BLOCK_SIZE / 2;
+ collapse32(longs);
+ }
+
+ final int numLongsPerShift = bitsPerValue * 2;
+ Arrays.fill(tmp, 0L);
+ int idx = 0;
+ for (int shift = nextPrimitive - bitsPerValue; shift >= 0; shift -= bitsPerValue) {
+ for (int i = 0; i < numLongsPerShift; ++i) {
+ tmp[i] |= longs[idx++] << shift;
+ }
+ }
+
+ final int remainingBitsPerLong = nextPrimitive % bitsPerValue;
+ final long maskRemainingBitsPerLong;
+ if (nextPrimitive == 8) {
+ maskRemainingBitsPerLong = mask8(remainingBitsPerLong);
+ } else if (nextPrimitive == 16) {
+ maskRemainingBitsPerLong = mask16(remainingBitsPerLong);
+ } else {
+ maskRemainingBitsPerLong = mask32(remainingBitsPerLong);
+ }
+ int tmpIdx = 0;
+ int remainingBitsPerValue = bitsPerValue;
+ while (idx < numLongs) {
+ if (remainingBitsPerValue > remainingBitsPerLong) {
+ remainingBitsPerValue -= remainingBitsPerLong;
+ tmp[tmpIdx++] |= (longs[idx] >>> remainingBitsPerValue) & maskRemainingBitsPerLong;
+ if (remainingBitsPerValue == 0) {
+ idx++;
+ remainingBitsPerValue = bitsPerValue;
+ }
+ } else {
+ final long mask1, mask2;
+ if (nextPrimitive == 8) {
+ mask1 = mask8(remainingBitsPerValue);
+ mask2 = mask8(remainingBitsPerLong - remainingBitsPerValue);
+ } else if (nextPrimitive == 16) {
+ mask1 = mask16(remainingBitsPerValue);
+ mask2 = mask16(remainingBitsPerLong - remainingBitsPerValue);
+ } else {
+ mask1 = mask32(remainingBitsPerValue);
+ mask2 = mask32(remainingBitsPerLong - remainingBitsPerValue);
+ }
+ tmp[tmpIdx] |= (longs[idx++] & mask1) << (remainingBitsPerLong - remainingBitsPerValue);
+ remainingBitsPerValue = bitsPerValue - remainingBitsPerLong + remainingBitsPerValue;
+ tmp[tmpIdx++] |= (longs[idx] >>> remainingBitsPerValue) & mask2;
+ }
+ }
+
+ for (int i = 0; i < numLongsPerShift; ++i) {
+ // Java longs are big endian and we want to read little endian longs, so we need to reverse bytes
+ long l = Long.reverseBytes(tmp[i]);
+ out.writeLong(l);
+ }
+ }
+
+ /**
+ * Number of bytes required to encode 128 integers of {@code bitsPerValue} bits per value.
+ */
+ int numBytes(int bitsPerValue) throws IOException {
+ return bitsPerValue << (BLOCK_SIZE_LOG2 - 3);
+ }
+
+ private static void decodeSlow(int bitsPerValue, DataInput in, long[] tmp, long[] longs) throws IOException {
+ final int numLongs = bitsPerValue << 1;
+ in.readLELongs(tmp, 0, numLongs);
+ final long mask = mask32(bitsPerValue);
+ int longsIdx = 0;
+ int shift = 32 - bitsPerValue;
+ for (; shift >= 0; shift -= bitsPerValue) {
+ shiftLongs(tmp, numLongs, longs, longsIdx, shift, mask);
+ longsIdx += numLongs;
+ }
+ final int remainingBitsPerLong = shift + bitsPerValue;
+ final long mask32RemainingBitsPerLong = mask32(remainingBitsPerLong);
+ int tmpIdx = 0;
+ int remainingBits = remainingBitsPerLong;
+ for (; longsIdx < BLOCK_SIZE / 2; ++longsIdx) {
+ int b = bitsPerValue - remainingBits;
+ long l = (tmp[tmpIdx++] & mask32(remainingBits)) << b;
+ while (b >= remainingBitsPerLong) {
+ b -= remainingBitsPerLong;
+ l |= (tmp[tmpIdx++] & mask32RemainingBitsPerLong) << b;
+ }
+ if (b > 0) {
+ l |= (tmp[tmpIdx] >>> (remainingBitsPerLong-b)) & mask32(b);
+ remainingBits = remainingBitsPerLong - b;
+ } else {
+ remainingBits = remainingBitsPerLong;
+ }
+ longs[longsIdx] = l;
+ }
+ }
+
+ /**
+ * The pattern that this shiftLongs method applies is recognized by the C2
+ * compiler, which generates SIMD instructions for it in order to shift
+ * multiple longs at once.
+ */
+ private static void shiftLongs(long[] a, int count, long[] b, int bi, int shift, long mask) {
+ for (int i = 0; i < count; ++i) {
+ b[bi+i] = (a[i] >>> shift) & mask;
+ }
+ }
+
+"""
+
+def writeRemainder(bpv, next_primitive, remaining_bits_per_long, o, num_values, f):
+ iteration = 1
+ num_longs = bpv * num_values / remaining_bits_per_long
+ while num_longs % 2 == 0 and num_values % 2 == 0:
+ num_longs /= 2
+ num_values /= 2
+ iteration *= 2
+ f.write(' for (int iter = 0, tmpIdx = 0, longsIdx = %d; iter < %d; ++iter, tmpIdx += %d, longsIdx += %d) {\n' %(o, iteration, num_longs, num_values))
+ i = 0
+ remaining_bits = 0
+ tmp_idx = 0
+ for i in range(num_values):
+ b = bpv
+ if remaining_bits == 0:
+ b -= remaining_bits_per_long
+ f.write(' long l%d = (tmp[tmpIdx+%d] & MASK%d_%d) << %d;\n' %(i, tmp_idx, next_primitive, remaining_bits_per_long, b))
+ else:
+ b -= remaining_bits
+ f.write(' long l%d = (tmp[tmpIdx+%d] & MASK%d_%d) << %d;\n' %(i, tmp_idx, next_primitive, remaining_bits, b))
+ tmp_idx += 1
+ while b >= remaining_bits_per_long:
+ b -= remaining_bits_per_long
+ f.write(' l%d |= (tmp[tmpIdx+%d] & MASK%d_%d) << %d;\n' %(i, tmp_idx, next_primitive, remaining_bits_per_long, b))
+ tmp_idx += 1
+ if b > 0:
+ f.write(' l%d |= (tmp[tmpIdx+%d] >>> %d) & MASK%d_%d;\n' %(i, tmp_idx, remaining_bits_per_long-b, next_primitive, b))
+ remaining_bits = remaining_bits_per_long-b
+ f.write(' longs[longsIdx+%d] = l%d;\n' %(i, i))
+ f.write(' }\n')
+
+
+
+def writeDecode(bpv, f):
+ next_primitive = 32
+ if bpv <= 8:
+ next_primitive = 8
+ elif bpv <= 16:
+ next_primitive = 16
+ f.write(' private static void decode%d(DataInput in, long[] tmp, long[] longs) throws IOException {\n' %bpv)
+ num_values_per_long = 64 / next_primitive
+ if bpv == next_primitive:
+ f.write(' in.readLELongs(longs, 0, %d);\n' %(bpv*2))
+ else:
+ f.write(' in.readLELongs(tmp, 0, %d);\n' %(bpv*2))
+ shift = next_primitive - bpv
+ o = 0
+ while shift >= 0:
+ f.write(' shiftLongs(tmp, %d, longs, %d, %d, MASK%d_%d);\n' %(bpv*2, o, shift, next_primitive, bpv))
+ o += bpv*2
+ shift -= bpv
+ if shift + bpv > 0:
+ writeRemainder(bpv, next_primitive, shift + bpv, o, 128/num_values_per_long - o, f)
+ f.write(' }\n')
+ f.write('\n')
+
+if __name__ == '__main__':
+ f = open(OUTPUT_FILE, 'w')
+ f.write(HEADER)
+ for primitive_size in [8, 16, 32]:
+ for bpv in range(1, min(MAX_SPECIALIZED_BITS_PER_VALUE + 1, primitive_size)):
+ if bpv * 2 != primitive_size or primitive_size == 8:
+ f.write(' private static final long MASK%d_%d = mask%d(%d);\n' %(primitive_size, bpv, primitive_size, bpv))
+ f.write('\n')
+ f.write("""
+ /**
+ * Decode 128 integers into {@code longs}.
+ */
+ void decode(int bitsPerValue, DataInput in, long[] longs) throws IOException {
+ switch (bitsPerValue) {
+""")
+ for bpv in range(1, MAX_SPECIALIZED_BITS_PER_VALUE+1):
+ next_primitive = 32
+ if bpv <= 8:
+ next_primitive = 8
+ elif bpv <= 16:
+ next_primitive = 16
+ f.write(' case %d:\n' %bpv)
+ f.write(' decode%d(in, tmp, longs);\n' %bpv)
+ f.write(' expand%d(longs);\n' %next_primitive)
+ f.write(' break;\n')
+ f.write(' default:\n')
+ f.write(' decodeSlow(bitsPerValue, in, tmp, longs);\n')
+ f.write(' expand32(longs);\n')
+ f.write(' break;\n')
+ f.write(' }\n')
+ f.write(' }\n')
+
+ f.write("""
+ /**
+ * Delta-decode 128 integers into {@code longs}.
+ */
+ void decodeAndPrefixSum(int bitsPerValue, DataInput in, long base, long[] longs) throws IOException {
+ switch (bitsPerValue) {
+""")
+ for bpv in range(1, MAX_SPECIALIZED_BITS_PER_VALUE+1):
+ next_primitive = 32
+ if bpv <= 8:
+ next_primitive = 8
+ elif bpv <= 16:
+ next_primitive = 16
+ f.write(' case %d:\n' %bpv)
+ f.write(' decode%d(in, tmp, longs);\n' %bpv)
+ f.write(' prefixSum%d(longs, base);\n' %next_primitive)
+ f.write(' break;\n')
+ f.write(' default:\n')
+ f.write(' decodeSlow(bitsPerValue, in, tmp, longs);\n')
+ f.write(' prefixSum32(longs, base);\n')
+ f.write(' break;\n')
+ f.write(' }\n')
+ f.write(' }\n')
+
+ f.write('\n')
+ for i in range(1, MAX_SPECIALIZED_BITS_PER_VALUE+1):
+ writeDecode(i, f)
+
+ f.write('}\n')
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene84/package-info.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene84/package-info.java
new file mode 100644
index 00000000000..297374dada8
--- /dev/null
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene84/package-info.java
@@ -0,0 +1,413 @@
+/*
+ * 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.
+ */
+
+/**
+ * Lucene 8.4 file format.
+ *
+ * <h1>Apache Lucene - Index File Formats</h1>
+ * <div>
+ * <ul>
+ * <li><a href="#Introduction">Introduction</a></li>
+ * <li><a href="#Definitions">Definitions</a>
+ * <ul>
+ * <li><a href="#Inverted_Indexing">Inverted Indexing</a></li>
+ * <li><a href="#Types_of_Fields">Types of Fields</a></li>
+ * <li><a href="#Segments">Segments</a></li>
+ * <li><a href="#Document_Numbers">Document Numbers</a></li>
+ * </ul>
+ * </li>
+ * <li><a href="#Overview">Index Structure Overview</a></li>
+ * <li><a href="#File_Naming">File Naming</a></li>
+ * <li><a href="#file-names">Summary of File Extensions</a>
+ * <ul>
+ * <li><a href="#Lock_File">Lock File</a></li>
+ * <li><a href="#History">History</a></li>
+ * <li><a href="#Limitations">Limitations</a></li>
+ * </ul>
+ * </li>
+ * </ul>
+ * </div>
+ * <a name="Introduction"></a>
+ * <h2>Introduction</h2>
+ * <div>
+ * <p>This document defines the index file formats used in this version of Lucene.
+ * If you are using a different version of Lucene, please consult the copy of
+ * <code>docs/</code> that was distributed with
+ * the version you are using.</p>
+ * <p>This document attempts to provide a high-level definition of the Apache
+ * Lucene file formats.</p>
+ * </div>
+ * <a name="Definitions"></a>
+ * <h2>Definitions</h2>
+ * <div>
+ * <p>The fundamental concepts in Lucene are index, document, field and term.</p>
+ * <p>An index contains a sequence of documents.</p>
+ * <ul>
+ * <li>A document is a sequence of fields.</li>
+ * <li>A field is a named sequence of terms.</li>
+ * <li>A term is a sequence of bytes.</li>
+ * </ul>
+ * <p>The same sequence of bytes in two different fields is considered a different
+ * term. Thus terms are represented as a pair: the string naming the field, and the
+ * bytes within the field.</p>
+ * <a name="Inverted_Indexing"></a>
+ * <h3>Inverted Indexing</h3>
+ * <p>The index stores statistics about terms in order to make term-based search
+ * more efficient. Lucene's index falls into the family of indexes known as an
+ * <i>inverted index.</i> This is because it can list, for a term, the documents
+ * that contain it. This is the inverse of the natural relationship, in which
+ * documents list terms.</p>
+ * <a name="Types_of_Fields"></a>
+ * <h3>Types of Fields</h3>
+ * <p>In Lucene, fields may be <i>stored</i>, in which case their text is stored
+ * in the index literally, in a non-inverted manner. Fields that are inverted are
+ * called <i>indexed</i>. A field may be both stored and indexed.</p>
+ * <p>The text of a field may be <i>tokenized</i> into terms to be indexed, or the
+ * text of a field may be used literally as a term to be indexed. Most fields are
+ * tokenized, but sometimes it is useful for certain identifier fields to be
+ * indexed literally.</p>
+ * <p>See the {@link org.apache.lucene.document.Field Field}
+ * java docs for more information on Fields.</p>
+ * <a name="Segments"></a>
+ * <h3>Segments</h3>
+ * <p>Lucene indexes may be composed of multiple sub-indexes, or <i>segments</i>.
+ * Each segment is a fully independent index, which could be searched separately.
+ * Indexes evolve by:</p>
+ * <ol>
+ * <li>Creating new segments for newly added documents.</li>
+ * <li>Merging existing segments.</li>
+ * </ol>
+ * <p>Searches may involve multiple segments and/or multiple indexes, each index
+ * potentially composed of a set of segments.</p>
+ * <a name="Document_Numbers"></a>
+ * <h3>Document Numbers</h3>
+ * <p>Internally, Lucene refers to documents by an integer <i>document number</i>.
+ * The first document added to an index is numbered zero, and each subsequent
+ * document added gets a number one greater than the previous.</p>
+ * <p>Note that a document's number may change, so caution should be taken when
+ * storing these numbers outside of Lucene. In particular, numbers may change in
+ * the following situations:</p>
+ * <ul>
+ * <li>
+ * <p>The numbers stored in each segment are unique only within the segment, and
+ * must be converted before they can be used in a larger context. The standard
+ * technique is to allocate each segment a range of values, based on the range of
+ * numbers used in that segment. To convert a document number from a segment to an
+ * external value, the segment's <i>base</i> document number is added. To convert
+ * an external value back to a segment-specific value, the segment is identified
+ * by the range that the external value is in, and the segment's base value is
+ * subtracted. For example two five document segments might be combined, so that
+ * the first segment has a base value of zero, and the second of five. Document
+ * three from the second segment would have an external value of eight.</p>
+ * </li>
+ * <li>
+ * <p>When documents are deleted, gaps are created in the numbering. These are
+ * eventually removed as the index evolves through merging. Deleted documents are
+ * dropped when segments are merged. A freshly-merged segment thus has no gaps in
+ * its numbering.</p>
+ * </li>
+ * </ul>
+ * </div>
+ * <a name="Overview"></a>
+ * <h2>Index Structure Overview</h2>
+ * <div>
+ * <p>Each segment index maintains the following:</p>
+ * <ul>
+ * <li>
+ * {@link org.apache.lucene.codecs.lucene70.Lucene70SegmentInfoFormat Segment info}.
+ * This contains metadata about a segment, such as the number of documents,
+ * what files it uses,
+ * </li>
+ * <li>
+ * {@link org.apache.lucene.codecs.lucene60.Lucene60FieldInfosFormat Field names}.
+ * This contains the set of field names used in the index.
+ * </li>
+ * <li>
+ * {@link org.apache.lucene.codecs.lucene50.Lucene50StoredFieldsFormat Stored Field values}.
+ * This contains, for each document, a list of attribute-value pairs, where the attributes
+ * are field names. These are used to store auxiliary information about the document, such as
+ * its title, url, or an identifier to access a database. The set of stored fields are what is
+ * returned for each hit when searching. This is keyed by document number.
+ * </li>
+ * <li>
+ * {@link org.apache.lucene.codecs.lucene84.Lucene84PostingsFormat Term dictionary}.
+ * A dictionary containing all of the terms used in all of the
+ * indexed fields of all of the documents. The dictionary also contains the number
+ * of documents which contain the term, and pointers to the term's frequency and
+ * proximity data.
+ * </li>
+ * <li>
+ * {@link org.apache.lucene.codecs.lucene84.Lucene84PostingsFormat Term Frequency data}.
+ * For each term in the dictionary, the numbers of all the
+ * documents that contain that term, and the frequency of the term in that
+ * document, unless frequencies are omitted (IndexOptions.DOCS_ONLY)
+ * </li>
+ * <li>
+ * {@link org.apache.lucene.codecs.lucene84.Lucene84PostingsFormat Term Proximity data}.
+ * For each term in the dictionary, the positions that the
+ * term occurs in each document. Note that this will not exist if all fields in
+ * all documents omit position data.
+ * </li>
+ * <li>
+ * {@link org.apache.lucene.codecs.lucene80.Lucene80NormsFormat Normalization factors}.
+ * For each field in each document, a value is stored
+ * that is multiplied into the score for hits on that field.
+ * </li>
+ * <li>
+ * {@link org.apache.lucene.codecs.lucene50.Lucene50TermVectorsFormat Term Vectors}.
+ * For each field in each document, the term vector (sometimes
+ * called document vector) may be stored. A term vector consists of term text and
+ * term frequency. To add Term Vectors to your index see the
+ * {@link org.apache.lucene.document.Field Field} constructors
+ * </li>
+ * <li>
+ * {@link org.apache.lucene.codecs.lucene80.Lucene80DocValuesFormat Per-document values}.
+ * Like stored values, these are also keyed by document
+ * number, but are generally intended to be loaded into main memory for fast
+ * access. Whereas stored values are generally intended for summary results from
+ * searches, per-document values are useful for things like scoring factors.
+ * </li>
+ * <li>
+ * {@link org.apache.lucene.codecs.lucene50.Lucene50LiveDocsFormat Live documents}.
+ * An optional file indicating which documents are live.
+ * </li>
+ * <li>
+ * {@link org.apache.lucene.codecs.lucene60.Lucene60PointsFormat Point values}.
+ * Optional pair of files, recording dimensionally indexed fields, to enable fast
+ * numeric range filtering and large numeric values like BigInteger and BigDecimal (1D)
+ * and geographic shape intersection (2D, 3D).
+ * </li>
+ * </ul>
+ * <p>Details on each of these are provided in their linked pages.</p>
+ * </div>
+ * <a name="File_Naming"></a>
+ * <h2>File Naming</h2>
+ * <div>
+ * <p>All files belonging to a segment have the same name with varying extensions.
+ * The extensions correspond to the different file formats described below. When
+ * using the Compound File format (default for small segments) these files (except
+ * for the Segment info file, the Lock file, and Deleted documents file) are collapsed
+ * into a single .cfs file (see below for details)</p>
+ * <p>Typically, all segments in an index are stored in a single directory,
+ * although this is not required.</p>
+ * <p>File names are never re-used. That is, when any file is saved
+ * to the Directory it is given a never before used filename. This is achieved
+ * using a simple generations approach. For example, the first segments file is
+ * segments_1, then segments_2, etc. The generation is a sequential long integer
+ * represented in alpha-numeric (base 36) form.</p>
+ * </div>
+ * <a name="file-names"></a>
+ * <h2>Summary of File Extensions</h2>
+ * <div>
+ * <p>The following table summarizes the names and extensions of the files in
+ * Lucene:</p>
+ * <table cellspacing="1" cellpadding="4" summary="lucene filenames by extension">
+ * <tr>
+ * <th>Name</th>
+ * <th>Extension</th>
+ * <th>Brief Description</th>
+ * </tr>
+ * <tr>
+ * <td>{@link org.apache.lucene.index.SegmentInfos Segments File}</td>
+ * <td>segments_N</td>
+ * <td>Stores information about a commit point</td>
+ * </tr>
+ * <tr>
+ * <td><a href="#Lock_File">Lock File</a></td>
+ * <td>write.lock</td>
+ * <td>The Write lock prevents multiple IndexWriters from writing to the same
+ * file.</td>
+ * </tr>
+ * <tr>
+ * <td>{@link org.apache.lucene.codecs.lucene70.Lucene70SegmentInfoFormat Segment Info}</td>
+ * <td>.si</td>
+ * <td>Stores metadata about a segment</td>
+ * </tr>
+ * <tr>
+ * <td>{@link org.apache.lucene.codecs.lucene50.Lucene50CompoundFormat Compound File}</td>
+ * <td>.cfs, .cfe</td>
+ * <td>An optional "virtual" file consisting of all the other index files for
+ * systems that frequently run out of file handles.</td>
+ * </tr>
+ * <tr>
+ * <td>{@link org.apache.lucene.codecs.lucene60.Lucene60FieldInfosFormat Fields}</td>
+ * <td>.fnm</td>
+ * <td>Stores information about the fields</td>
+ * </tr>
+ * <tr>
+ * <td>{@link org.apache.lucene.codecs.lucene50.Lucene50StoredFieldsFormat Field Index}</td>
+ * <td>.fdx</td>
+ * <td>Contains pointers to field data</td>
+ * </tr>
+ * <tr>
+ * <td>{@link org.apache.lucene.codecs.lucene50.Lucene50StoredFieldsFormat Field Data}</td>
+ * <td>.fdt</td>
+ * <td>The stored fields for documents</td>
+ * </tr>
+ * <tr>
+ * <td>{@link org.apache.lucene.codecs.lucene84.Lucene84PostingsFormat Term Dictionary}</td>
+ * <td>.tim</td>
+ * <td>The term dictionary, stores term info</td>
+ * </tr>
+ * <tr>
+ * <td>{@link org.apache.lucene.codecs.lucene84.Lucene84PostingsFormat Term Index}</td>
+ * <td>.tip</td>
+ * <td>The index into the Term Dictionary</td>
+ * </tr>
+ * <tr>
+ * <td>{@link org.apache.lucene.codecs.lucene84.Lucene84PostingsFormat Frequencies}</td>
+ * <td>.doc</td>
+ * <td>Contains the list of docs which contain each term along with frequency</td>
+ * </tr>
+ * <tr>
+ * <td>{@link org.apache.lucene.codecs.lucene84.Lucene84PostingsFormat Positions}</td>
+ * <td>.pos</td>
+ * <td>Stores position information about where a term occurs in the index</td>
+ * </tr>
+ * <tr>
+ * <td>{@link org.apache.lucene.codecs.lucene84.Lucene84PostingsFormat Payloads}</td>
+ * <td>.pay</td>
+ * <td>Stores additional per-position metadata information such as character offsets and user payloads</td>
+ * </tr>
+ * <tr>
+ * <td>{@link org.apache.lucene.codecs.lucene80.Lucene80NormsFormat Norms}</td>
+ * <td>.nvd, .nvm</td>
+ * <td>Encodes length and boost factors for docs and fields</td>
+ * </tr>
+ * <tr>
+ * <td>{@link org.apache.lucene.codecs.lucene80.Lucene80DocValuesFormat Per-Document Values}</td>
+ * <td>.dvd, .dvm</td>
+ * <td>Encodes additional scoring factors or other per-document information.</td>
+ * </tr>
+ * <tr>
+ * <td>{@link org.apache.lucene.codecs.lucene50.Lucene50TermVectorsFormat Term Vector Index}</td>
+ * <td>.tvx</td>
+ * <td>Stores offset into the document data file</td>
+ * </tr>
+ * <tr>
+ * <td>{@link org.apache.lucene.codecs.lucene50.Lucene50TermVectorsFormat Term Vector Data}</td>
+ * <td>.tvd</td>
+ * <td>Contains term vector data.</td>
+ * </tr>
+ * <tr>
+ * <td>{@link org.apache.lucene.codecs.lucene50.Lucene50LiveDocsFormat Live Documents}</td>
+ * <td>.liv</td>
+ * <td>Info about what documents are live</td>
+ * </tr>
+ * <tr>
+ * <td>{@link org.apache.lucene.codecs.lucene60.Lucene60PointsFormat Point values}</td>
+ * <td>.dii, .dim</td>
+ * <td>Holds indexed points, if any</td>
+ * </tr>
+ * </table>
+ * </div>
+ * <a name="Lock_File"></a>
+ * <h2>Lock File</h2>
+ * The write lock, which is stored in the index directory by default, is named
+ * "write.lock". If the lock directory is different from the index directory then
+ * the write lock will be named "XXXX-write.lock" where XXXX is a unique prefix
+ * derived from the full path to the index directory. When this file is present, a
+ * writer is currently modifying the index (adding or removing documents). This
+ * lock file ensures that only one writer is modifying the index at a time.
+ * <a name="History"></a>
+ * <h2>History</h2>
+ * <p>Compatibility notes are provided in this document, describing how file
+ * formats have changed from prior versions:</p>
+ * <ul>
+ * <li>In version 2.1, the file format was changed to allow lock-less commits (ie,
+ * no more commit lock). The change is fully backwards compatible: you can open a
+ * pre-2.1 index for searching or adding/deleting of docs. When the new segments
+ * file is saved (committed), it will be written in the new file format (meaning
+ * no specific "upgrade" process is needed). But note that once a commit has
+ * occurred, pre-2.1 Lucene will not be able to read the index.</li>
+ * <li>In version 2.3, the file format was changed to allow segments to share a
+ * single set of doc store (vectors &amp; stored fields) files. This allows for
+ * faster indexing in certain cases. The change is fully backwards compatible (in
+ * the same way as the lock-less commits change in 2.1).</li>
+ * <li>In version 2.4, Strings are now written as true UTF-8 byte sequence, not
+ * Java's modified UTF-8. See <a href="http://issues.apache.org/jira/browse/LUCENE-510">
+ * LUCENE-510</a> for details.</li>
+ * <li>In version 2.9, an optional opaque Map&lt;String,String&gt; CommitUserData
+ * may be passed to IndexWriter's commit methods (and later retrieved), which is
+ * recorded in the segments_N file. See <a href="http://issues.apache.org/jira/browse/LUCENE-1382">
+ * LUCENE-1382</a> for details. Also,
+ * diagnostics were added to each segment written recording details about why it
+ * was written (due to flush, merge; which OS/JRE was used; etc.). See issue
+ * <a href="http://issues.apache.org/jira/browse/LUCENE-1654">LUCENE-1654</a> for details.</li>
+ * <li>In version 3.0, compressed fields are no longer written to the index (they
+ * can still be read, but on merge the new segment will write them, uncompressed).
+ * See issue <a href="http://issues.apache.org/jira/browse/LUCENE-1960">LUCENE-1960</a>
+ * for details.</li>
+ * <li>In version 3.1, segments records the code version that created them. See
+ * <a href="http://issues.apache.org/jira/browse/LUCENE-2720">LUCENE-2720</a> for details.
+ * Additionally segments track explicitly whether or not they have term vectors.
+ * See <a href="http://issues.apache.org/jira/browse/LUCENE-2811">LUCENE-2811</a>
+ * for details.</li>
+ * <li>In version 3.2, numeric fields are written as natively to stored fields
+ * file, previously they were stored in text format only.</li>
+ * <li>In version 3.4, fields can omit position data while still indexing term
+ * frequencies.</li>
+ * <li>In version 4.0, the format of the inverted index became extensible via
+ * the {@link org.apache.lucene.codecs.Codec Codec} api. Fast per-document storage
+ * ({@code DocValues}) was introduced. Normalization factors need no longer be a
+ * single byte, they can be any {@link org.apache.lucene.index.NumericDocValues NumericDocValues}.
+ * Terms need not be unicode strings, they can be any byte sequence. Term offsets
+ * can optionally be indexed into the postings lists. Payloads can be stored in the
+ * term vectors.</li>
+ * <li>In version 4.1, the format of the postings list changed to use either
+ * of FOR compression or variable-byte encoding, depending upon the frequency
+ * of the term. Terms appearing only once were changed to inline directly into
+ * the term dictionary. Stored fields are compressed by default. </li>
+ * <li>In version 4.2, term vectors are compressed by default. DocValues has
+ * a new multi-valued type (SortedSet), that can be used for faceting/grouping/joining
+ * on multi-valued fields.</li>
+ * <li>In version 4.5, DocValues were extended to explicitly represent missing values.</li>
+ * <li>In version 4.6, FieldInfos were extended to support per-field DocValues generation, to
+ * allow updating NumericDocValues fields.</li>
+ * <li>In version 4.8, checksum footers were added to the end of each index file
+ * for improved data integrity. Specifically, the last 8 bytes of every index file
+ * contain the zlib-crc32 checksum of the file.</li>
+ * <li>In version 4.9, DocValues has a new multi-valued numeric type (SortedNumeric)
+ * that is suitable for faceting/sorting/analytics.
+ * <li>In version 5.4, DocValues have been improved to store more information on disk:
+ * addresses for binary fields and ord indexes for multi-valued fields.
+ * <li>In version 6.0, Points were added, for multi-dimensional range/distance search.
+ * <li>In version 6.2, new Segment info format that reads/writes the index sort, to support index sorting.
+ * <li>In version 7.0, DocValues have been improved to better support sparse doc values
+ * thanks to an iterator API.</li>
+ * <li>In version 8.0, postings have been enhanced to record, for each block of
+ * doc ids, the (term freq, normalization factor) pairs that may trigger the
+ * maximum score of the block. This information is recorded alongside skip data
+ * in order to be able to skip blocks of doc ids if they may not produce high
+ * enough scores.
+ * Additionally doc values and norms has been extended with jump-tables to make access O(1)
+ * instead of O(n), where n is the number of elements to skip when advancing in the data.</li>
+ * <li>In version 8.4, postings, positions, offsets and payload lengths have move to a more
+ * performant encoding that is vectorized.</li>
+ * </ul>
+ * <a name="Limitations"></a>
+ * <h2>Limitations</h2>
+ * <div>
+ * <p>Lucene uses a Java <code>int</code> to refer to
+ * document numbers, and the index file format uses an <code>Int32</code>
+ * on-disk to store document numbers. This is a limitation
+ * of both the index file format and the current implementation. Eventually these
+ * should be replaced with either <code>UInt64</code> values, or
+ * better yet, {@link org.apache.lucene.store.DataOutput#writeVInt VInt} values which have no limit.</p>
+ * </div>
+ */
+package org.apache.lucene.codecs.lucene84;
diff --git a/lucene/core/src/java/org/apache/lucene/search/PhraseQuery.java b/lucene/core/src/java/org/apache/lucene/search/PhraseQuery.java
index 3cf9159fa3e..7df01cabb7e 100644
--- a/lucene/core/src/java/org/apache/lucene/search/PhraseQuery.java
+++ b/lucene/core/src/java/org/apache/lucene/search/PhraseQuery.java
@@ -23,8 +23,8 @@ import java.util.Arrays;
import java.util.List;
import java.util.Objects;
-import org.apache.lucene.codecs.lucene50.Lucene50PostingsFormat;
-import org.apache.lucene.codecs.lucene50.Lucene50PostingsReader;
+import org.apache.lucene.codecs.lucene84.Lucene84PostingsFormat;
+import org.apache.lucene.codecs.lucene84.Lucene84PostingsReader;
import org.apache.lucene.index.ImpactsEnum;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexReaderContext;
@@ -374,10 +374,10 @@ public class PhraseQuery extends Query {
/** A guess of
* the average number of simple operations for the initial seek and buffer refill
* per document for the positions of a term.
- * See also {@link Lucene50PostingsReader.BlockImpactsPostingsEnum#nextPosition()}.
+ * See also {@link Lucene84PostingsReader.BlockImpactsPostingsEnum#nextPosition()}.
* <p>
* Aside: Instead of being constant this could depend among others on
- * {@link Lucene50PostingsFormat#BLOCK_SIZE},
+ * {@link Lucene84PostingsFormat#BLOCK_SIZE},
* {@link TermsEnum#docFreq()},
* {@link TermsEnum#totalTermFreq()},
* {@link DocIdSetIterator#cost()} (expected number of matching docs),
@@ -386,7 +386,7 @@ public class PhraseQuery extends Query {
*/
private static final int TERM_POSNS_SEEK_OPS_PER_DOC = 128;
- /** Number of simple operations in {@link Lucene50PostingsReader.BlockImpactsPostingsEnum#nextPosition()}
+ /** Number of simple operations in {@link Lucene84PostingsReader.BlockImpactsPostingsEnum#nextPosition()}
* when no seek or buffer refill is done.
*/
private static final int TERM_OPS_PER_POS = 7;
diff --git a/lucene/core/src/java/org/apache/lucene/store/ByteBufferGuard.java b/lucene/core/src/java/org/apache/lucene/store/ByteBufferGuard.java
index 95fa17d5ea0..ed3b922000e 100644
--- a/lucene/core/src/java/org/apache/lucene/store/ByteBufferGuard.java
+++ b/lucene/core/src/java/org/apache/lucene/store/ByteBufferGuard.java
@@ -18,6 +18,7 @@ package org.apache.lucene.store;
import java.io.IOException;
import java.nio.ByteBuffer;
+import java.nio.LongBuffer;
import java.util.concurrent.atomic.AtomicInteger;
/**
@@ -132,5 +133,10 @@ final class ByteBufferGuard {
ensureValid();
return receiver.getLong(pos);
}
-
+
+ public void getLongs(LongBuffer receiver, long[] dst, int offset, int length) {
+ ensureValid();
+ receiver.get(dst, offset, length);
+ }
+
}
diff --git a/lucene/core/src/java/org/apache/lucene/store/ByteBufferIndexInput.java b/lucene/core/src/java/org/apache/lucene/store/ByteBufferIndexInput.java
index 3df89d79435..e1e2137cab9 100644
--- a/lucene/core/src/java/org/apache/lucene/store/ByteBufferIndexInput.java
+++ b/lucene/core/src/java/org/apache/lucene/store/ByteBufferIndexInput.java
@@ -21,6 +21,8 @@ import java.io.EOFException;
import java.io.IOException;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.nio.LongBuffer;
/**
* Base IndexInput implementation that uses an array
@@ -34,6 +36,8 @@ import java.nio.ByteBuffer;
* are a power-of-two (<code>chunkSizePower</code>).
*/
public abstract class ByteBufferIndexInput extends IndexInput implements RandomAccessInput {
+ private static final LongBuffer EMPTY_LONGBUFFER = LongBuffer.allocate(0);
+
protected final long length;
protected final long chunkSizeMask;
protected final int chunkSizePower;
@@ -42,6 +46,7 @@ public abstract class ByteBufferIndexInput extends IndexInput implements RandomA
protected ByteBuffer[] buffers;
protected int curBufIndex = -1;
protected ByteBuffer curBuf; // redundant for speed: buffers[curBufIndex]
+ private LongBuffer[] curLongBufferViews;
protected boolean isClone = false;
@@ -63,7 +68,12 @@ public abstract class ByteBufferIndexInput extends IndexInput implements RandomA
assert chunkSizePower >= 0 && chunkSizePower <= 30;
assert (length >>> chunkSizePower) < Integer.MAX_VALUE;
}
-
+
+ protected void setCurBuf(ByteBuffer curBuf) {
+ this.curBuf = curBuf;
+ curLongBufferViews = null;
+ }
+
@Override
public final byte readByte() throws IOException {
try {
@@ -74,7 +84,7 @@ public abstract class ByteBufferIndexInput extends IndexInput implements RandomA
if (curBufIndex >= buffers.length) {
throw new EOFException("read past EOF: " + this);
}
- curBuf = buffers[curBufIndex];
+ setCurBuf(buffers[curBufIndex]);
curBuf.position(0);
} while (!curBuf.hasRemaining());
return guard.getByte(curBuf);
@@ -97,7 +107,7 @@ public abstract class ByteBufferIndexInput extends IndexInput implements RandomA
if (curBufIndex >= buffers.length) {
throw new EOFException("read past EOF: " + this);
}
- curBuf = buffers[curBufIndex];
+ setCurBuf(buffers[curBufIndex]);
curBuf.position(0);
curAvail = curBuf.remaining();
}
@@ -107,6 +117,40 @@ public abstract class ByteBufferIndexInput extends IndexInput implements RandomA
}
}
+ @Override
+ public void readLELongs(long[] dst, int offset, int length) throws IOException {
+ // ByteBuffer#getLong could work but it has some per-long overhead and there
+ // is no ByteBuffer#getLongs to read multiple longs at once. So we use the
+ // below trick in order to be able to leverage LongBuffer#get(long[]) to
+ // read multiple longs at once with as little overhead as possible.
+ if (curLongBufferViews == null) {
+ // readLELongs is only used for postings today, so we compute the long
+ // views lazily so that other data-structures don't have to pay for the
+ // associated initialization/memory overhead.
+ curLongBufferViews = new LongBuffer[Long.BYTES];
+ for (int i = 0; i < Long.BYTES; ++i) {
+ // Compute a view for each possible alignment. We cache these views
+ // because #asLongBuffer() has some cost that we don't want to pay on
+ // each invocation of #readLELongs.
+ if (i < curBuf.limit()) {
+ curLongBufferViews[i] = curBuf.duplicate().position(i).order(ByteOrder.LITTLE_ENDIAN).asLongBuffer();
+ } else {
+ curLongBufferViews[i] = EMPTY_LONGBUFFER;
+ }
+ }
+ }
+ try {
+ final int position = curBuf.position();
+ guard.getLongs(curLongBufferViews[position & 0x07].position(position >>> 3), dst, offset, length);
+ // if the above call succeeded, then we know the below sum cannot overflow
+ curBuf.position(position + (length << 3));
+ } catch (BufferUnderflowException e) {
+ super.readLELongs(dst, offset, length);
+ } catch (NullPointerException npe) {
+ throw new AlreadyClosedException("Already closed: " + this);
+ }
+ }
+
@Override
public final short readShort() throws IOException {
try {
@@ -162,7 +206,7 @@ public abstract class ByteBufferIndexInput extends IndexInput implements RandomA
b.position((int) (pos & chunkSizeMask));
// write values, on exception all is unchanged
this.curBufIndex = bi;
- this.curBuf = b;
+ setCurBuf(b);
}
} catch (ArrayIndexOutOfBoundsException | IllegalArgumentException e) {
throw new EOFException("seek past EOF: " + this);
@@ -189,7 +233,7 @@ public abstract class ByteBufferIndexInput extends IndexInput implements RandomA
final ByteBuffer b = buffers[bi];
b.position((int) (pos & chunkSizeMask));
this.curBufIndex = bi;
- this.curBuf = b;
+ setCurBuf(b);
} catch (ArrayIndexOutOfBoundsException | IllegalArgumentException aioobe) {
throw new EOFException("seek past EOF: " + this);
} catch (NullPointerException npe) {
@@ -341,6 +385,7 @@ public abstract class ByteBufferIndexInput extends IndexInput implements RandomA
buffers = null;
curBuf = null;
curBufIndex = 0;
+ curLongBufferViews = null;
}
/** Optimization of ByteBufferIndexInput for when there is only one buffer */
@@ -349,7 +394,7 @@ public abstract class ByteBufferIndexInput extends IndexInput implements RandomA
SingleBufferImpl(String resourceDescription, ByteBuffer buffer, long length, int chunkSizePower, ByteBufferGuard guard) {
super(resourceDescription, new ByteBuffer[] { buffer }, length, chunkSizePower, guard);
this.curBufIndex = 0;
- this.curBuf = buffer;
+ setCurBuf(buffer);
buffer.position(0);
}
@@ -438,6 +483,7 @@ public abstract class ByteBufferIndexInput extends IndexInput implements RandomA
throw new AlreadyClosedException("Already closed: " + this);
}
}
+
}
/** This class adds offset support to ByteBufferIndexInput, which is needed for slices. */
diff --git a/lucene/core/src/java/org/apache/lucene/store/DataInput.java b/lucene/core/src/java/org/apache/lucene/store/DataInput.java
index 2514b841c49..e1f4507d70e 100644
--- a/lucene/core/src/java/org/apache/lucene/store/DataInput.java
+++ b/lucene/core/src/java/org/apache/lucene/store/DataInput.java
@@ -23,6 +23,7 @@ import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
+import java.util.Objects;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
@@ -157,6 +158,26 @@ public abstract class DataInput implements Cloneable {
return (((long)readInt()) << 32) | (readInt() & 0xFFFFFFFFL);
}
+ /**
+ * Read a specified number of longs with the little endian byte order.
+ * <p>This method can be used to read longs whose bytes have been
+ * {@link Long#reverseBytes reversed} at write time:
+ * <pre class="prettyprint">
+ * for (long l : longs) {
+ * output.writeLong(Long.reverseBytes(l));
+ * }
+ * </pre>
+ * @lucene.experimental
+ */
+ // TODO: LUCENE-9047: Make the entire DataInput/DataOutput API little endian
+ // Then this would just be `readLongs`?
+ public void readLELongs(long[] dst, int offset, int length) throws IOException {
+ Objects.checkFromIndexSize(offset, length, dst.length);
+ for (int i = 0; i < length; ++i) {
+ dst[offset + i] = Long.reverseBytes(readLong());
+ }
+ }
+
/** Reads a long stored in variable-length format. Reads between one and
* nine bytes. Smaller values take fewer bytes. Negative numbers are not
* supported.
diff --git a/lucene/core/src/resources/META-INF/services/org.apache.lucene.codecs.Codec b/lucene/core/src/resources/META-INF/services/org.apache.lucene.codecs.Codec
index a818e355d1c..611e237384c 100644
--- a/lucene/core/src/resources/META-INF/services/org.apache.lucene.codecs.Codec
+++ b/lucene/core/src/resources/META-INF/services/org.apache.lucene.codecs.Codec
@@ -13,4 +13,4 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-org.apache.lucene.codecs.lucene80.Lucene80Codec
+org.apache.lucene.codecs.lucene84.Lucene84Codec
diff --git a/lucene/core/src/resources/META-INF/services/org.apache.lucene.codecs.PostingsFormat b/lucene/core/src/resources/META-INF/services/org.apache.lucene.codecs.PostingsFormat
index f7390e28cff..486b1057566 100644
--- a/lucene/core/src/resources/META-INF/services/org.apache.lucene.codecs.PostingsFormat
+++ b/lucene/core/src/resources/META-INF/services/org.apache.lucene.codecs.PostingsFormat
@@ -13,4 +13,4 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-org.apache.lucene.codecs.lucene50.Lucene50PostingsFormat
+org.apache.lucene.codecs.lucene84.Lucene84PostingsFormat
diff --git a/lucene/core/src/test/org/apache/lucene/codecs/lucene50/TestLucene50StoredFieldsFormatHighCompression.java b/lucene/core/src/test/org/apache/lucene/codecs/lucene50/TestLucene50StoredFieldsFormatHighCompression.java
index eef2e117631..6a3ce93a0f0 100644
--- a/lucene/core/src/test/org/apache/lucene/codecs/lucene50/TestLucene50StoredFieldsFormatHighCompression.java
+++ b/lucene/core/src/test/org/apache/lucene/codecs/lucene50/TestLucene50StoredFieldsFormatHighCompression.java
@@ -19,7 +19,7 @@ package org.apache.lucene.codecs.lucene50;
import org.apache.lucene.codecs.Codec;
import org.apache.lucene.codecs.lucene50.Lucene50StoredFieldsFormat.Mode;
-import org.apache.lucene.codecs.lucene80.Lucene80Codec;
+import org.apache.lucene.codecs.lucene84.Lucene84Codec;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.StoredField;
import org.apache.lucene.index.BaseStoredFieldsFormatTestCase;
@@ -33,7 +33,7 @@ import com.carrotsearch.randomizedtesting.generators.RandomPicks;
public class TestLucene50StoredFieldsFormatHighCompression extends BaseStoredFieldsFormatTestCase {
@Override
protected Codec getCodec() {
- return new Lucene80Codec(Mode.BEST_COMPRESSION);
+ return new Lucene84Codec(Mode.BEST_COMPRESSION);
}
/**
@@ -44,7 +44,7 @@ public class TestLucene50StoredFieldsFormatHighCompression extends BaseStoredFie
Directory dir = newDirectory();
for (int i = 0; i < 10; i++) {
IndexWriterConfig iwc = newIndexWriterConfig();
- iwc.setCodec(new Lucene80Codec(RandomPicks.randomFrom(random(), Mode.values())));
+ iwc.setCodec(new Lucene84Codec(RandomPicks.randomFrom(random(), Mode.values())));
IndexWriter iw = new IndexWriter(dir, newIndexWriterConfig());
Document doc = new Document();
doc.add(new StoredField("field1", "value1"));
@@ -71,7 +71,7 @@ public class TestLucene50StoredFieldsFormatHighCompression extends BaseStoredFie
public void testInvalidOptions() {
expectThrows(NullPointerException.class, () -> {
- new Lucene80Codec(null);
+ new Lucene84Codec(null);
});
expectThrows(NullPointerException.class, () -> {
diff --git a/lucene/core/src/test/org/apache/lucene/codecs/lucene80/TestLucene80NormsFormat.java b/lucene/core/src/test/org/apache/lucene/codecs/lucene80/TestLucene80NormsFormat.java
index e6116a937d4..4eadf05ef5a 100644
--- a/lucene/core/src/test/org/apache/lucene/codecs/lucene80/TestLucene80NormsFormat.java
+++ b/lucene/core/src/test/org/apache/lucene/codecs/lucene80/TestLucene80NormsFormat.java
@@ -18,13 +18,14 @@ package org.apache.lucene.codecs.lucene80;
import org.apache.lucene.codecs.Codec;
+import org.apache.lucene.codecs.lucene84.Lucene84Codec;
import org.apache.lucene.index.BaseNormsFormatTestCase;
/**
* Tests Lucene80NormsFormat
*/
public class TestLucene80NormsFormat extends BaseNormsFormatTestCase {
- private final Codec codec = new Lucene80Codec();
+ private final Codec codec = new Lucene84Codec();
@Override
protected Codec getCodec() {
diff --git a/lucene/core/src/test/org/apache/lucene/codecs/lucene84/TestForDeltaUtil.java b/lucene/core/src/test/org/apache/lucene/codecs/lucene84/TestForDeltaUtil.java
new file mode 100644
index 00000000000..d8bab653ea1
--- /dev/null
+++ b/lucene/core/src/test/org/apache/lucene/codecs/lucene84/TestForDeltaUtil.java
@@ -0,0 +1,95 @@
+/*
+ * 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.
+ */
+package org.apache.lucene.codecs.lucene84;
+
+import java.io.IOException;
+import java.util.Arrays;
+
+import org.apache.lucene.store.ByteBuffersDirectory;
+import org.apache.lucene.store.Directory;
+import org.apache.lucene.store.IOContext;
+import org.apache.lucene.store.IndexInput;
+import org.apache.lucene.store.IndexOutput;
+import org.apache.lucene.util.LuceneTestCase;
+import org.apache.lucene.util.TestUtil;
+import org.apache.lucene.util.packed.PackedInts;
+
+import com.carrotsearch.randomizedtesting.generators.RandomNumbers;
+
+public class TestForDeltaUtil extends LuceneTestCase {
+
+ public void testEncodeDecode() throws IOException {
+ final int iterations = RandomNumbers.randomIntBetween(random(), 50, 1000);
+ final int[] values = new int[iterations * ForUtil.BLOCK_SIZE];
+
+ for (int i = 0; i < iterations; ++i) {
+ final int bpv = TestUtil.nextInt(random(), 1, 31-7);
+ for (int j = 0; j < ForUtil.BLOCK_SIZE; ++j) {
+ values[i * ForUtil.BLOCK_SIZE + j] = RandomNumbers.randomIntBetween(random(),
+ 1, (int) PackedInts.maxValue(bpv));
+ }
+ }
+
+ final Directory d = new ByteBuffersDirectory();
+ final long endPointer;
+
+ {
+ // encode
+ IndexOutput out = d.createOutput("test.bin", IOContext.DEFAULT);
+ final ForDeltaUtil forDeltaUtil = new ForDeltaUtil(new ForUtil());
+
+ for (int i = 0; i < iterations; ++i) {
+ long[] source = new long[ForUtil.BLOCK_SIZE];
+ for (int j = 0; j < ForUtil.BLOCK_SIZE; ++j) {
+ source[j] = values[i*ForUtil.BLOCK_SIZE+j];
+ }
+ forDeltaUtil.encodeDeltas(source, out);
+ }
+ endPointer = out.getFilePointer();
+ out.close();
+ }
+
+ {
+ // decode
+ IndexInput in = d.openInput("test.bin", IOContext.READONCE);
+ final ForDeltaUtil forDeltaUtil = new ForDeltaUtil(new ForUtil());
+ for (int i = 0; i < iterations; ++i) {
+ if (random().nextInt(5) == 0) {
+ forDeltaUtil.skip(in);
+ continue;
+ }
+ long base = 0;
+ final long[] restored = new long[ForUtil.BLOCK_SIZE];
+ forDeltaUtil.decodeAndPrefixSum(in, base, restored);
+ final long[] expected = new long[ForUtil.BLOCK_SIZE];
+ for (int j = 0; j < ForUtil.BLOCK_SIZE; ++j) {
+ expected[j] = values[i*ForUtil.BLOCK_SIZE+j];
+ if (j > 0) {
+ expected[j] += expected[j-1];
+ } else {
+ expected[j] += base;
+ }
+ }
+ assertArrayEquals(Arrays.toString(restored), expected, restored);
+ }
+ assertEquals(endPointer, in.getFilePointer());
+ in.close();
+ }
+
+ d.close();
+ }
+}
diff --git a/lucene/core/src/test/org/apache/lucene/codecs/lucene84/TestForUtil.java b/lucene/core/src/test/org/apache/lucene/codecs/lucene84/TestForUtil.java
new file mode 100644
index 00000000000..cd4dc85272c
--- /dev/null
+++ b/lucene/core/src/test/org/apache/lucene/codecs/lucene84/TestForUtil.java
@@ -0,0 +1,95 @@
+/*
+ * 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.
+ */
+package org.apache.lucene.codecs.lucene84;
+
+import java.io.IOException;
+import java.util.Arrays;
+
+import org.apache.lucene.store.ByteBuffersDirectory;
+import org.apache.lucene.store.Directory;
+import org.apache.lucene.store.IOContext;
+import org.apache.lucene.store.IndexInput;
+import org.apache.lucene.store.IndexOutput;
+import org.apache.lucene.util.ArrayUtil;
+import org.apache.lucene.util.LuceneTestCase;
+import org.apache.lucene.util.TestUtil;
+import org.apache.lucene.util.packed.PackedInts;
+
+import com.carrotsearch.randomizedtesting.generators.RandomNumbers;
+
+public class TestForUtil extends LuceneTestCase {
+
+ public void testEncodeDecode() throws IOException {
+ final int iterations = RandomNumbers.randomIntBetween(random(), 50, 1000);
+ final int[] values = new int[iterations * ForUtil.BLOCK_SIZE];
+
+ for (int i = 0; i < iterations; ++i) {
+ final int bpv = TestUtil.nextInt(random(), 1, 31);
+ for (int j = 0; j < ForUtil.BLOCK_SIZE; ++j) {
+ values[i * ForUtil.BLOCK_SIZE + j] = RandomNumbers.randomIntBetween(random(),
+ 0, (int) PackedInts.maxValue(bpv));
+ }
+ }
+
+ final Directory d = new ByteBuffersDirectory();
+ final long endPointer;
+
+ {
+ // encode
+ IndexOutput out = d.createOutput("test.bin", IOContext.DEFAULT);
+ final ForUtil forUtil = new ForUtil();
+
+ for (int i = 0; i < iterations; ++i) {
+ long[] source = new long[ForUtil.BLOCK_SIZE];
+ long or = 0;
+ for (int j = 0; j < ForUtil.BLOCK_SIZE; ++j) {
+ source[j] = values[i*ForUtil.BLOCK_SIZE+j];
+ or |= source[j];
+ }
+ final int bpv = PackedInts.bitsRequired(or);
+ out.writeByte((byte) bpv);
+ forUtil.encode(source, bpv, out);
+ }
+ endPointer = out.getFilePointer();
+ out.close();
+ }
+
+ {
+ // decode
+ IndexInput in = d.openInput("test.bin", IOContext.READONCE);
+ final ForUtil forUtil = new ForUtil();
+ for (int i = 0; i < iterations; ++i) {
+ final int bitsPerValue = in.readByte();
+ final long currentFilePointer = in.getFilePointer();
+ final long[] restored = new long[ForUtil.BLOCK_SIZE];
+ forUtil.decode(bitsPerValue, in, restored);
+ int[] ints = new int[ForUtil.BLOCK_SIZE];
+ for (int j = 0; j < ForUtil.BLOCK_SIZE; ++j) {
+ ints[j] = Math.toIntExact(restored[j]);
+ }
+ assertArrayEquals(Arrays.toString(ints),
+ ArrayUtil.copyOfSubArray(values, i*ForUtil.BLOCK_SIZE, (i+1)*ForUtil.BLOCK_SIZE),
+ ints);
+ assertEquals(forUtil.numBytes(bitsPerValue), in.getFilePointer() - currentFilePointer);
+ }
+ assertEquals(endPointer, in.getFilePointer());
+ in.close();
+ }
+
+ d.close();
+ }
+}
diff --git a/lucene/core/src/test/org/apache/lucene/codecs/lucene84/TestLucene84PostingsFormat.java b/lucene/core/src/test/org/apache/lucene/codecs/lucene84/TestLucene84PostingsFormat.java
new file mode 100644
index 00000000000..0be30e33612
--- /dev/null
+++ b/lucene/core/src/test/org/apache/lucene/codecs/lucene84/TestLucene84PostingsFormat.java
@@ -0,0 +1,350 @@
+/*
+ * 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.
+ */
+package org.apache.lucene.codecs.lucene84;
+
+import java.io.IOException;
+import java.nio.file.Path;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.lucene.analysis.MockAnalyzer;
+import org.apache.lucene.codecs.Codec;
+import org.apache.lucene.codecs.CompetitiveImpactAccumulator;
+import org.apache.lucene.codecs.blocktree.BlockTreeTermsReader;
+import org.apache.lucene.codecs.blocktree.FieldReader;
+import org.apache.lucene.codecs.blocktree.Stats;
+import org.apache.lucene.codecs.lucene84.Lucene84PostingsFormat;
+import org.apache.lucene.codecs.lucene84.Lucene84ScoreSkipReader;
+import org.apache.lucene.codecs.lucene84.Lucene84SkipWriter;
+import org.apache.lucene.codecs.lucene84.Lucene84ScoreSkipReader.MutableImpactList;
+import org.apache.lucene.document.Document;
+import org.apache.lucene.document.Field;
+import org.apache.lucene.index.BasePostingsFormatTestCase;
+import org.apache.lucene.index.DirectoryReader;
+import org.apache.lucene.index.Impact;
+import org.apache.lucene.index.IndexWriter;
+import org.apache.lucene.index.IndexWriterConfig;
+import org.apache.lucene.index.LeafReaderContext;
+import org.apache.lucene.index.Term;
+import org.apache.lucene.store.ByteArrayDataInput;
+import org.apache.lucene.store.Directory;
+import org.apache.lucene.store.FSDirectory;
+import org.apache.lucene.store.IOContext;
+import org.apache.lucene.store.IndexInput;
+import org.apache.lucene.store.IndexOutput;
+import org.apache.lucene.store.MMapDirectory;
+import org.apache.lucene.store.SimpleFSDirectory;
+import org.apache.lucene.util.TestUtil;
+
+public class TestLucene84PostingsFormat extends BasePostingsFormatTestCase {
+ private final Codec codec = TestUtil.alwaysPostingsFormat(new Lucene84PostingsFormat());
+
+ @Override
+ protected Codec getCodec() {
+ return codec;
+ }
+
+ public void testFstOffHeap() throws IOException {
+ Path tempDir = createTempDir();
+ try (Directory d = FSDirectory.open(tempDir)) {
+ assumeTrue("only works with mmap directory", d instanceof MMapDirectory);
+ try (IndexWriter w = new IndexWriter(d, new IndexWriterConfig(new MockAnalyzer(random())))) {
+ DirectoryReader readerFromWriter = DirectoryReader.open(w);
+ for (int i = 0; i < 50; i++) {
+ Document doc = new Document();
+ doc.add(newStringField("id", "" + i, Field.Store.NO));
+ doc.add(newStringField("field", Character.toString((char) (97 + i)), Field.Store.NO));
+ doc.add(newStringField("field", Character.toString((char) (98 + i)), Field.Store.NO));
+ if (rarely()) {
+ w.addDocument(doc);
+ } else {
+ w.updateDocument(new Term("id", "" + i), doc);
+ }
+ if (random().nextBoolean()) {
+ w.commit();
+ }
+
+ if (random().nextBoolean()) {
+ DirectoryReader newReader = DirectoryReader.openIfChanged(readerFromWriter);
+ if (newReader != null) {
+ readerFromWriter.close();
+ readerFromWriter = newReader;
+ }
+ for (LeafReaderContext leaf : readerFromWriter.leaves()) {
+ FieldReader field = (FieldReader) leaf.reader().terms("field");
+ FieldReader id = (FieldReader) leaf.reader().terms("id");
+ assertFalse(id.isFstOffHeap());
+ assertTrue(field.isFstOffHeap());
+ }
+ }
+ }
+ readerFromWriter.close();
+
+ w.forceMerge(1);
+ try (DirectoryReader r = DirectoryReader.open(w)) {
+ assertEquals(1, r.leaves().size());
+ FieldReader field = (FieldReader) r.leaves().get(0).reader().terms("field");
+ FieldReader id = (FieldReader) r.leaves().get(0).reader().terms("id");
+ assertFalse(id.isFstOffHeap());
+ assertTrue(field.isFstOffHeap());
+ }
+ w.commit();
+ try (DirectoryReader r = DirectoryReader.open(d)) {
+ assertEquals(1, r.leaves().size());
+ FieldReader field = (FieldReader) r.leaves().get(0).reader().terms("field");
+ FieldReader id = (FieldReader) r.leaves().get(0).reader().terms("id");
+ assertTrue(id.isFstOffHeap());
+ assertTrue(field.isFstOffHeap());
+ }
+ }
+ }
+
+ try (Directory d = new SimpleFSDirectory(tempDir)) {
+ // test auto
+ try (DirectoryReader r = DirectoryReader.open(d)) {
+ assertEquals(1, r.leaves().size());
+ FieldReader field = (FieldReader) r.leaves().get(0).reader().terms("field");
+ FieldReader id = (FieldReader) r.leaves().get(0).reader().terms("id");
+ assertFalse(id.isFstOffHeap());
+ assertFalse(field.isFstOffHeap());
+ }
+ }
+
+ try (Directory d = new SimpleFSDirectory(tempDir)) {
+ // test per field
+ Map<String, String> readerAttributes = new HashMap<>();
+ readerAttributes.put(BlockTreeTermsReader.FST_MODE_KEY, BlockTreeTermsReader.FSTLoadMode.OFF_HEAP.name());
+ readerAttributes.put(BlockTreeTermsReader.FST_MODE_KEY + ".field", BlockTreeTermsReader.FSTLoadMode.ON_HEAP.name());
+ try (DirectoryReader r = DirectoryReader.open(d, readerAttributes)) {
+ assertEquals(1, r.leaves().size());
+ FieldReader field = (FieldReader) r.leaves().get(0).reader().terms("field");
+ FieldReader id = (FieldReader) r.leaves().get(0).reader().terms("id");
+ assertTrue(id.isFstOffHeap());
+ assertFalse(field.isFstOffHeap());
+ }
+ }
+
+ IllegalArgumentException invalid = expectThrows(IllegalArgumentException.class, () -> {
+ try (Directory d = new SimpleFSDirectory(tempDir)) {
+ Map<String, String> readerAttributes = new HashMap<>();
+ readerAttributes.put(BlockTreeTermsReader.FST_MODE_KEY, "invalid");
+ DirectoryReader.open(d, readerAttributes);
+ }
+ });
+
+ assertEquals("Invalid value for blocktree.terms.fst expected one of: [OFF_HEAP, ON_HEAP, OPTIMIZE_UPDATES_OFF_HEAP, AUTO] but was: invalid", invalid.getMessage());
+ }
+
+ public void testDisableFSTOffHeap() throws IOException {
+ Path tempDir = createTempDir();
+ try (Directory d = MMapDirectory.open(tempDir)) {
+ try (IndexWriter w = new IndexWriter(d, new IndexWriterConfig(new MockAnalyzer(random()))
+ .setReaderAttributes(Collections.singletonMap(BlockTreeTermsReader.FST_MODE_KEY, BlockTreeTermsReader.FSTLoadMode.ON_HEAP.name())))) {
+ assumeTrue("only works with mmap directory", d instanceof MMapDirectory);
+ DirectoryReader readerFromWriter = DirectoryReader.open(w);
+ for (int i = 0; i < 50; i++) {
+ Document doc = new Document();
+ doc.add(newStringField("id", "" + i, Field.Store.NO));
+ doc.add(newStringField("field", Character.toString((char) (97 + i)), Field.Store.NO));
+ doc.add(newStringField("field", Character.toString((char) (98 + i)), Field.Store.NO));
+ if (rarely()) {
+ w.addDocument(doc);
+ } else {
+ w.updateDocument(new Term("id", "" + i), doc);
+ }
+ if (random().nextBoolean()) {
+ w.commit();
+ }
+ if (random().nextBoolean()) {
+ DirectoryReader newReader = DirectoryReader.openIfChanged(readerFromWriter);
+ if (newReader != null) {
+ readerFromWriter.close();
+ readerFromWriter = newReader;
+ }
+ for (LeafReaderContext leaf : readerFromWriter.leaves()) {
+ FieldReader field = (FieldReader) leaf.reader().terms("field");
+ FieldReader id = (FieldReader) leaf.reader().terms("id");
+ assertFalse(id.isFstOffHeap());
+ assertFalse(field.isFstOffHeap());
+ }
+ }
+ }
+ readerFromWriter.close();
+ w.forceMerge(1);
+ w.commit();
+ }
+ try (DirectoryReader r = DirectoryReader.open(d, Collections.singletonMap(BlockTreeTermsReader.FST_MODE_KEY, BlockTreeTermsReader.FSTLoadMode.ON_HEAP.name()))) {
+ assertEquals(1, r.leaves().size());
+ FieldReader field = (FieldReader) r.leaves().get(0).reader().terms("field");
+ FieldReader id = (FieldReader) r.leaves().get(0).reader().terms("id");
+ assertFalse(id.isFstOffHeap());
+ assertFalse(field.isFstOffHeap());
+ }
+ }
+ }
+
+ public void testAlwaysFSTOffHeap() throws IOException {
+ boolean alsoLoadIdOffHeap = random().nextBoolean();
+ BlockTreeTermsReader.FSTLoadMode loadMode;
+ if (alsoLoadIdOffHeap) {
+ loadMode = BlockTreeTermsReader.FSTLoadMode.OFF_HEAP;
+ } else {
+ loadMode = BlockTreeTermsReader.FSTLoadMode.OPTIMIZE_UPDATES_OFF_HEAP;
+ }
+ try (Directory d = newDirectory()) { // any directory should work now
+ try (IndexWriter w = new IndexWriter(d, new IndexWriterConfig(new MockAnalyzer(random()))
+ .setReaderAttributes(Collections.singletonMap(BlockTreeTermsReader.FST_MODE_KEY, loadMode.name())))) {
+ DirectoryReader readerFromWriter = DirectoryReader.open(w);
+ for (int i = 0; i < 50; i++) {
+ Document doc = new Document();
+ doc.add(newStringField("id", "" + i, Field.Store.NO));
+ doc.add(newStringField("field", Character.toString((char) (97 + i)), Field.Store.NO));
+ doc.add(newStringField("field", Character.toString((char) (98 + i)), Field.Store.NO));
+ if (rarely()) {
+ w.addDocument(doc);
+ } else {
+ w.updateDocument(new Term("id", "" + i), doc);
+ }
+ if (random().nextBoolean()) {
+ w.commit();
+ }
+ if (random().nextBoolean()) {
+ DirectoryReader newReader = DirectoryReader.openIfChanged(readerFromWriter);
+ if (newReader != null) {
+ readerFromWriter.close();
+ readerFromWriter = newReader;
+ }
+ for (LeafReaderContext leaf : readerFromWriter.leaves()) {
+ FieldReader field = (FieldReader) leaf.reader().terms("field");
+ FieldReader id = (FieldReader) leaf.reader().terms("id");
+ if (alsoLoadIdOffHeap) {
+ assertTrue(id.isFstOffHeap());
+ } else {
+ assertFalse(id.isFstOffHeap());
+ }
+ assertTrue(field.isFstOffHeap());
+ }
+ }
+ }
+ readerFromWriter.close();
+ w.forceMerge(1);
+ w.commit();
+ }
+ try (DirectoryReader r = DirectoryReader.open(d, Collections.singletonMap(BlockTreeTermsReader.FST_MODE_KEY, loadMode.name()))) {
+ assertEquals(1, r.leaves().size());
+ FieldReader field = (FieldReader) r.leaves().get(0).reader().terms("field");
+ FieldReader id = (FieldReader) r.leaves().get(0).reader().terms("id");
+ assertTrue(id.isFstOffHeap());
+ assertTrue(field.isFstOffHeap());
+ }
+ }
+ }
+
+ /** Make sure the final sub-block(s) are not skipped. */
+ public void testFinalBlock() throws Exception {
+ Directory d = newDirectory();
+ IndexWriter w = new IndexWriter(d, new IndexWriterConfig(new MockAnalyzer(random())));
+ for(int i=0;i<25;i++) {
+ Document doc = new Document();
+ doc.add(newStringField("field", Character.toString((char) (97+i)), Field.Store.NO));
+ doc.add(newStringField("field", "z" + Character.toString((char) (97+i)), Field.Store.NO));
+ w.addDocument(doc);
+ }
+ w.forceMerge(1);
+
+ DirectoryReader r = DirectoryReader.open(w);
+ assertEquals(1, r.leaves().size());
+ FieldReader field = (FieldReader) r.leaves().get(0).reader().terms("field");
+ // We should see exactly two blocks: one root block (prefix empty string) and one block for z* terms (prefix z):
+ Stats stats = field.getStats();
+ assertEquals(0, stats.floorBlockCount);
+ assertEquals(2, stats.nonFloorBlockCount);
+ r.close();
+ w.close();
+ d.close();
+ }
+
+ private void shouldFail(int minItemsInBlock, int maxItemsInBlock) {
+ expectThrows(IllegalArgumentException.class, () -> {
+ new Lucene84PostingsFormat(minItemsInBlock, maxItemsInBlock, BlockTreeTermsReader.FSTLoadMode.AUTO);
+ });
+ }
+
+ public void testInvalidBlockSizes() throws Exception {
+ shouldFail(0, 0);
+ shouldFail(10, 8);
+ shouldFail(-1, 10);
+ shouldFail(10, -1);
+ shouldFail(10, 12);
+ }
+
+ public void testImpactSerialization() throws IOException {
+ // omit norms and omit freqs
+ doTestImpactSerialization(Collections.singletonList(new Impact(1, 1L)));
+
+ // omit freqs
+ doTestImpactSerialization(Collections.singletonList(new Impact(1, 42L)));
+ // omit freqs with very large norms
+ doTestImpactSerialization(Collections.singletonList(new Impact(1, -100L)));
+
+ // omit norms
+ doTestImpactSerialization(Collections.singletonList(new Impact(30, 1L)));
+ // omit norms with large freq
+ doTestImpactSerialization(Collections.singletonList(new Impact(500, 1L)));
+
+ // freqs and norms, basic
+ doTestImpactSerialization(
+ Arrays.asList(
+ new Impact(1, 7L),
+ new Impact(3, 9L),
+ new Impact(7, 10L),
+ new Impact(15, 11L),
+ new Impact(20, 13L),
+ new Impact(28, 14L)));
+
+ // freqs and norms, high values
+ doTestImpactSerialization(
+ Arrays.asList(
+ new Impact(2, 2L),
+ new Impact(10, 10L),
+ new Impact(12, 50L),
+ new Impact(50, -100L),
+ new Impact(1000, -80L),
+ new Impact(1005, -3L)));
+ }
+
+ private void doTestImpactSerialization(List<Impact> impacts) throws IOException {
+ CompetitiveImpactAccumulator acc = new CompetitiveImpactAccumulator();
+ for (Impact impact : impacts) {
+ acc.add(impact.freq, impact.norm);
+ }
+ try(Directory dir = newDirectory()) {
+ try (IndexOutput out = dir.createOutput("foo", IOContext.DEFAULT)) {
+ Lucene84SkipWriter.writeImpacts(acc, out);
+ }
+ try (IndexInput in = dir.openInput("foo", IOContext.DEFAULT)) {
+ byte[] b = new byte[Math.toIntExact(in.length())];
+ in.readBytes(b, 0, b.length);
+ List<Impact> impacts2 = Lucene84ScoreSkipReader.readImpacts(new ByteArrayDataInput(b), new MutableImpactList());
+ assertEquals(impacts, impacts2);
+ }
+ }
+ }
+}
diff --git a/lucene/core/src/test/org/apache/lucene/codecs/lucene84/TestPForUtil.java b/lucene/core/src/test/org/apache/lucene/codecs/lucene84/TestPForUtil.java
new file mode 100644
index 00000000000..f660c09be3c
--- /dev/null
+++ b/lucene/core/src/test/org/apache/lucene/codecs/lucene84/TestPForUtil.java
@@ -0,0 +1,101 @@
+/*
+ * 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.
+ */
+package org.apache.lucene.codecs.lucene84;
+
+import java.io.IOException;
+import java.util.Arrays;
+
+import org.apache.lucene.store.ByteBuffersDirectory;
+import org.apache.lucene.store.Directory;
+import org.apache.lucene.store.IOContext;
+import org.apache.lucene.store.IndexInput;
+import org.apache.lucene.store.IndexOutput;
+import org.apache.lucene.util.ArrayUtil;
+import org.apache.lucene.util.LuceneTestCase;
+import org.apache.lucene.util.TestUtil;
+import org.apache.lucene.util.packed.PackedInts;
+
+import com.carrotsearch.randomizedtesting.generators.RandomNumbers;
+
+public class TestPForUtil extends LuceneTestCase {
+
+ public void testEncodeDecode() throws IOException {
+ final int iterations = RandomNumbers.randomIntBetween(random(), 50, 1000);
+ final int[] values = new int[iterations * ForUtil.BLOCK_SIZE];
+
+ for (int i = 0; i < iterations; ++i) {
+ final int bpv = TestUtil.nextInt(random(), 0, 31);
+ for (int j = 0; j < ForUtil.BLOCK_SIZE; ++j) {
+ values[i * ForUtil.BLOCK_SIZE + j] = RandomNumbers.randomIntBetween(random(),
+ 0, (int) PackedInts.maxValue(bpv));
+ if (random().nextInt(100) == 0) {
+ final int exceptionBpv;
+ if (random().nextInt(10) == 0) {
+ exceptionBpv = Math.min(bpv + TestUtil.nextInt(random(), 9, 16), 31);
+ } else {
+ exceptionBpv = Math.min(bpv + TestUtil.nextInt(random(), 1, 8), 31);
+ }
+ values[i * ForUtil.BLOCK_SIZE + j] |= random().nextInt(1 << (exceptionBpv - bpv)) << bpv;
+ }
+ }
+ }
+
+ final Directory d = new ByteBuffersDirectory();
+ final long endPointer;
+
+ {
+ // encode
+ IndexOutput out = d.createOutput("test.bin", IOContext.DEFAULT);
+ final PForUtil pforUtil = new PForUtil(new ForUtil());
+
+ for (int i = 0; i < iterations; ++i) {
+ long[] source = new long[ForUtil.BLOCK_SIZE];
+ for (int j = 0; j < ForUtil.BLOCK_SIZE; ++j) {
+ source[j] = values[i*ForUtil.BLOCK_SIZE+j];
+ }
+ pforUtil.encode(source, out);
+ }
+ endPointer = out.getFilePointer();
+ out.close();
+ }
+
+ {
+ // decode
+ IndexInput in = d.openInput("test.bin", IOContext.READONCE);
+ final PForUtil pforUtil = new PForUtil(new ForUtil());
+ for (int i = 0; i < iterations; ++i) {
+ if (random().nextInt(5) == 0) {
+ pforUtil.skip(in);
+ continue;
+ }
+ final long[] restored = new long[ForUtil.BLOCK_SIZE];
+ pforUtil.decode(in, restored);
+ int[] ints = new int[ForUtil.BLOCK_SIZE];
+ for (int j = 0; j < ForUtil.BLOCK_SIZE; ++j) {
+ ints[j] = Math.toIntExact(restored[j]);
+ }
+ assertArrayEquals(Arrays.toString(ints),
+ ArrayUtil.copyOfSubArray(values, i*ForUtil.BLOCK_SIZE, (i+1)*ForUtil.BLOCK_SIZE),
+ ints);
+ }
+ assertEquals(endPointer, in.getFilePointer());
+ in.close();
+ }
+
+ d.close();
+ }
+}
diff --git a/lucene/core/src/test/org/apache/lucene/index/Test2BPoints.java b/lucene/core/src/test/org/apache/lucene/index/Test2BPoints.java
index 23e2c9180bf..463573cc995 100644
--- a/lucene/core/src/test/org/apache/lucene/index/Test2BPoints.java
+++ b/lucene/core/src/test/org/apache/lucene/index/Test2BPoints.java
@@ -135,6 +135,6 @@ public class Test2BPoints extends LuceneTestCase {
}
private static Codec getCodec() {
- return Codec.forName("Lucene80");
+ return Codec.forName("Lucene84");
}
}
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestPointValues.java b/lucene/core/src/test/org/apache/lucene/index/TestPointValues.java
index 348a31a53ef..c026ed9b7b3 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestPointValues.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestPointValues.java
@@ -392,11 +392,11 @@ public class TestPointValues extends LuceneTestCase {
dir.close();
}
- // Write point values, one segment with Lucene80, another with SimpleText, then forceMerge with SimpleText
+ // Write point values, one segment with Lucene84, another with SimpleText, then forceMerge with SimpleText
public void testDifferentCodecs1() throws Exception {
Directory dir = newDirectory();
IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random()));
- iwc.setCodec(Codec.forName("Lucene80"));
+ iwc.setCodec(Codec.forName("Lucene84"));
IndexWriter w = new IndexWriter(dir, iwc);
Document doc = new Document();
doc.add(new IntPoint("int", 1));
@@ -415,7 +415,7 @@ public class TestPointValues extends LuceneTestCase {
dir.close();
}
- // Write point values, one segment with Lucene80, another with SimpleText, then forceMerge with Lucene80
+ // Write point values, one segment with Lucene84, another with SimpleText, then forceMerge with Lucene84
public void testDifferentCodecs2() throws Exception {
Directory dir = newDirectory();
IndexWriterConfig iwc = new IndexWriterConfig(new MockAnalyzer(random()));
@@ -427,7 +427,7 @@ public class TestPointValues extends LuceneTestCase {
w.close();
iwc = new IndexWriterConfig(new MockAnalyzer(random()));
- iwc.setCodec(Codec.forName("Lucene80"));
+ iwc.setCodec(Codec.forName("Lucene84"));
w = new IndexWriter(dir, iwc);
doc = new Document();
doc.add(new IntPoint("int", 1));
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestBoolean2.java b/lucene/core/src/test/org/apache/lucene/search/TestBoolean2.java
index 13323a49ad7..414db9b5e8f 100644
--- a/lucene/core/src/test/org/apache/lucene/search/TestBoolean2.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestBoolean2.java
@@ -96,7 +96,7 @@ public class TestBoolean2 extends LuceneTestCase {
IndexWriterConfig iwc = newIndexWriterConfig(new MockAnalyzer(random()));
// randomized codecs are sometimes too costly for this test:
- iwc.setCodec(Codec.forName("Lucene80"));
+ iwc.setCodec(Codec.forName("Lucene84"));
iwc.setMergePolicy(newLogMergePolicy());
RandomIndexWriter writer= new RandomIndexWriter(random(), directory, iwc);
// we'll make a ton of docs, disable store/norms/vectors
@@ -141,7 +141,7 @@ public class TestBoolean2 extends LuceneTestCase {
iwc = newIndexWriterConfig(new MockAnalyzer(random()));
// we need docID order to be preserved:
// randomized codecs are sometimes too costly for this test:
- iwc.setCodec(Codec.forName("Lucene80"));
+ iwc.setCodec(Codec.forName("Lucene84"));
iwc.setMergePolicy(newLogMergePolicy());
try (IndexWriter w = new IndexWriter(singleSegmentDirectory, iwc)) {
w.forceMerge(1, true);
@@ -167,7 +167,7 @@ public class TestBoolean2 extends LuceneTestCase {
iwc = newIndexWriterConfig(new MockAnalyzer(random()));
// randomized codecs are sometimes too costly for this test:
- iwc.setCodec(Codec.forName("Lucene80"));
+ iwc.setCodec(Codec.forName("Lucene84"));
RandomIndexWriter w = new RandomIndexWriter(random(), dir2, iwc);
w.addIndexes(copy);
copy.close();
@@ -179,7 +179,7 @@ public class TestBoolean2 extends LuceneTestCase {
iwc = newIndexWriterConfig(new MockAnalyzer(random()));
iwc.setMaxBufferedDocs(TestUtil.nextInt(random(), 50, 1000));
// randomized codecs are sometimes too costly for this test:
- iwc.setCodec(Codec.forName("Lucene80"));
+ iwc.setCodec(Codec.forName("Lucene84"));
RandomIndexWriter w = new RandomIndexWriter(random(), dir2, iwc);
doc = new Document();
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestPointQueries.java b/lucene/core/src/test/org/apache/lucene/search/TestPointQueries.java
index 49c29077932..9df5c144a58 100644
--- a/lucene/core/src/test/org/apache/lucene/search/TestPointQueries.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestPointQueries.java
@@ -1160,14 +1160,14 @@ public class TestPointQueries extends LuceneTestCase {
}
private static Codec getCodec() {
- if (Codec.getDefault().getName().equals("Lucene80")) {
+ if (Codec.getDefault().getName().equals("Lucene84")) {
int maxPointsInLeafNode = TestUtil.nextInt(random(), 16, 2048);
double maxMBSortInHeap = 5.0 + (3*random().nextDouble());
if (VERBOSE) {
System.out.println("TEST: using Lucene60PointsFormat with maxPointsInLeafNode=" + maxPointsInLeafNode + " and maxMBSortInHeap=" + maxMBSortInHeap);
}
- return new FilterCodec("Lucene80", Codec.getDefault()) {
+ return new FilterCodec("Lucene84", Codec.getDefault()) {
@Override
public PointsFormat pointsFormat() {
return new PointsFormat() {
diff --git a/lucene/core/src/test/org/apache/lucene/store/TestMultiMMap.java b/lucene/core/src/test/org/apache/lucene/store/TestMultiMMap.java
index 3a03ea93ad2..25728d8a440 100644
--- a/lucene/core/src/test/org/apache/lucene/store/TestMultiMMap.java
+++ b/lucene/core/src/test/org/apache/lucene/store/TestMultiMMap.java
@@ -386,4 +386,24 @@ public class TestMultiMMap extends BaseDirectoryTestCase {
mmapDir.close();
}
}
+
+ public void testLittleEndianLongsCrossBoundary() throws Exception {
+ try (Directory dir = new MMapDirectory(createTempDir("testLittleEndianLongsCrossBoundary"), 16)) {
+ try (IndexOutput out = dir.createOutput("littleEndianLongs", newIOContext(random()))) {
+ out.writeByte((byte) 2);
+ out.writeLong(Long.reverseBytes(3L));
+ out.writeLong(Long.reverseBytes(Long.MAX_VALUE));
+ out.writeLong(Long.reverseBytes(-3L));
+ }
+ try (IndexInput input = dir.openInput("littleEndianLongs", newIOContext(random()))) {
+ assertEquals(25, input.length());
+ assertEquals(2, input.readByte());
+ long[] l = new long[4];
+ input.readLELongs(l, 1, 3);
+ assertArrayEquals(new long[] {0L, 3L, Long.MAX_VALUE, -3L}, l);
+ assertEquals(25, input.getFilePointer());
+ }
+ }
+ }
+
}
diff --git a/lucene/queries/src/java/org/apache/lucene/queries/intervals/TermIntervalsSource.java b/lucene/queries/src/java/org/apache/lucene/queries/intervals/TermIntervalsSource.java
index 2859fceb258..efd801f8db5 100644
--- a/lucene/queries/src/java/org/apache/lucene/queries/intervals/TermIntervalsSource.java
+++ b/lucene/queries/src/java/org/apache/lucene/queries/intervals/TermIntervalsSource.java
@@ -22,8 +22,8 @@ import java.util.Collection;
import java.util.Collections;
import java.util.Objects;
-import org.apache.lucene.codecs.lucene50.Lucene50PostingsFormat;
-import org.apache.lucene.codecs.lucene50.Lucene50PostingsReader;
+import org.apache.lucene.codecs.lucene84.Lucene84PostingsFormat;
+import org.apache.lucene.codecs.lucene84.Lucene84PostingsReader;
import org.apache.lucene.index.LeafReader;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.index.PostingsEnum;
@@ -241,10 +241,10 @@ class TermIntervalsSource extends IntervalsSource {
/** A guess of
* the average number of simple operations for the initial seek and buffer refill
* per document for the positions of a term.
- * See also {@link Lucene50PostingsReader.EverythingEnum#nextPosition()}.
+ * See also {@link Lucene84PostingsReader.EverythingEnum#nextPosition()}.
* <p>
* Aside: Instead of being constant this could depend among others on
- * {@link Lucene50PostingsFormat#BLOCK_SIZE},
+ * {@link Lucene84PostingsFormat#BLOCK_SIZE},
* {@link TermsEnum#docFreq()},
* {@link TermsEnum#totalTermFreq()},
* {@link DocIdSetIterator#cost()} (expected number of matching docs),
@@ -253,7 +253,7 @@ class TermIntervalsSource extends IntervalsSource {
*/
private static final int TERM_POSNS_SEEK_OPS_PER_DOC = 128;
- /** Number of simple operations in {@link Lucene50PostingsReader.EverythingEnum#nextPosition()}
+ /** Number of simple operations in {@link Lucene84PostingsReader.EverythingEnum#nextPosition()}
* when no seek or buffer refill is done.
*/
private static final int TERM_OPS_PER_POS = 7;
diff --git a/lucene/sandbox/src/test/org/apache/lucene/document/TestFloatPointNearestNeighbor.java b/lucene/sandbox/src/test/org/apache/lucene/document/TestFloatPointNearestNeighbor.java
index 8379326cfae..93d7993d7a1 100644
--- a/lucene/sandbox/src/test/org/apache/lucene/document/TestFloatPointNearestNeighbor.java
+++ b/lucene/sandbox/src/test/org/apache/lucene/document/TestFloatPointNearestNeighbor.java
@@ -243,7 +243,7 @@ public class TestFloatPointNearestNeighbor extends LuceneTestCase {
private IndexWriterConfig getIndexWriterConfig() {
IndexWriterConfig iwc = newIndexWriterConfig();
- iwc.setCodec(Codec.forName("Lucene80"));
+ iwc.setCodec(Codec.forName("Lucene84"));
return iwc;
}
}
diff --git a/lucene/sandbox/src/test/org/apache/lucene/search/TestNearest.java b/lucene/sandbox/src/test/org/apache/lucene/search/TestNearest.java
index 627b7245881..735b7951f76 100644
--- a/lucene/sandbox/src/test/org/apache/lucene/search/TestNearest.java
+++ b/lucene/sandbox/src/test/org/apache/lucene/search/TestNearest.java
@@ -246,7 +246,7 @@ public class TestNearest extends LuceneTestCase {
private IndexWriterConfig getIndexWriterConfig() {
IndexWriterConfig iwc = newIndexWriterConfig();
- iwc.setCodec(Codec.forName("Lucene80"));
+ iwc.setCodec(Codec.forName("Lucene84"));
return iwc;
}
}
diff --git a/lucene/spatial3d/src/test/org/apache/lucene/spatial3d/TestGeo3DPoint.java b/lucene/spatial3d/src/test/org/apache/lucene/spatial3d/TestGeo3DPoint.java
index 95bfc8a493f..552b1b1d928 100644
--- a/lucene/spatial3d/src/test/org/apache/lucene/spatial3d/TestGeo3DPoint.java
+++ b/lucene/spatial3d/src/test/org/apache/lucene/spatial3d/TestGeo3DPoint.java
@@ -85,14 +85,14 @@ import com.carrotsearch.randomizedtesting.generators.RandomNumbers;
public class TestGeo3DPoint extends LuceneTestCase {
private static Codec getCodec() {
- if (Codec.getDefault().getName().equals("Lucene80")) {
+ if (Codec.getDefault().getName().equals("Lucene84")) {
int maxPointsInLeafNode = TestUtil.nextInt(random(), 16, 2048);
double maxMBSortInHeap = 3.0 + (3*random().nextDouble());
if (VERBOSE) {
System.out.println("TEST: using Lucene60PointsFormat with maxPointsInLeafNode=" + maxPointsInLeafNode + " and maxMBSortInHeap=" + maxMBSortInHeap);
}
- return new FilterCodec("Lucene80", Codec.getDefault()) {
+ return new FilterCodec("Lucene84", Codec.getDefault()) {
@Override
public PointsFormat pointsFormat() {
return new PointsFormat() {
diff --git a/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/Completion50PostingsFormat.java b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/Completion50PostingsFormat.java
index fcc0584b607..b0c6d37930d 100644
--- a/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/Completion50PostingsFormat.java
+++ b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/Completion50PostingsFormat.java
@@ -20,7 +20,10 @@ import org.apache.lucene.codecs.PostingsFormat;
/**
* {@link org.apache.lucene.search.suggest.document.CompletionPostingsFormat}
- * for {@link org.apache.lucene.codecs.lucene50.Lucene50PostingsFormat}
+ * for {@code org.apache.lucene.codecs.lucene50.Lucene50PostingsFormat}.
+ * This format is only used for backward-compatibility of the index format
+ * and cannot be used to write data, use {@link Completion84PostingsFormat}
+ * on new indices.
*
* @lucene.experimental
*/
@@ -39,7 +42,7 @@ public class Completion50PostingsFormat extends CompletionPostingsFormat {
* if the completion FST should be loaded on or off heap.
*/
public Completion50PostingsFormat(FSTLoadMode fstLoadMode) {
- super(fstLoadMode);
+ super("completion", fstLoadMode);
}
@Override
diff --git a/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/Completion84PostingsFormat.java b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/Completion84PostingsFormat.java
new file mode 100644
index 00000000000..4c77437843e
--- /dev/null
+++ b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/Completion84PostingsFormat.java
@@ -0,0 +1,49 @@
+/*
+ * 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.
+ */
+package org.apache.lucene.search.suggest.document;
+
+import org.apache.lucene.codecs.PostingsFormat;
+
+/**
+ * {@link org.apache.lucene.search.suggest.document.CompletionPostingsFormat}
+ * for {@link org.apache.lucene.codecs.lucene84.Lucene84PostingsFormat}
+ *
+ * @lucene.experimental
+ */
+public class Completion84PostingsFormat extends CompletionPostingsFormat {
+ /**
+ * Creates a {@link Completion84PostingsFormat} that will load
+ * the completion FST on-heap.
+ */
+ public Completion84PostingsFormat() {
+ this(FSTLoadMode.ON_HEAP);
+ }
+
+ /**
+ * Creates a {@link Completion84PostingsFormat} that will
+ * use the provided <code>fstLoadMode</code> to determine
+ * if the completion FST should be loaded on or off heap.
+ */
+ public Completion84PostingsFormat(FSTLoadMode fstLoadMode) {
+ super("Completion84", fstLoadMode);
+ }
+
+ @Override
+ protected PostingsFormat delegatePostingsFormat() {
+ return PostingsFormat.forName("Lucene84");
+ }
+}
diff --git a/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionFieldsConsumer.java b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionFieldsConsumer.java
index 5ab16a97f43..b3e1bf961a8 100644
--- a/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionFieldsConsumer.java
+++ b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionFieldsConsumer.java
@@ -38,7 +38,6 @@ import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.IOUtils;
-import static org.apache.lucene.search.suggest.document.CompletionPostingsFormat.CODEC_NAME;
import static org.apache.lucene.search.suggest.document.CompletionPostingsFormat.COMPLETION_VERSION_CURRENT;
import static org.apache.lucene.search.suggest.document.CompletionPostingsFormat.DICT_EXTENSION;
import static org.apache.lucene.search.suggest.document.CompletionPostingsFormat.INDEX_EXTENSION;
@@ -62,8 +61,10 @@ final class CompletionFieldsConsumer extends FieldsConsumer {
private final SegmentWriteState state;
private IndexOutput dictOut;
private FieldsConsumer delegateFieldsConsumer;
+ private final String codecName;
- CompletionFieldsConsumer(PostingsFormat delegatePostingsFormat, SegmentWriteState state) throws IOException {
+ CompletionFieldsConsumer(String codecName, PostingsFormat delegatePostingsFormat, SegmentWriteState state) throws IOException {
+ this.codecName = codecName;
this.delegatePostingsFormatName = delegatePostingsFormat.getName();
this.state = state;
String dictFile = IndexFileNames.segmentFileName(state.segmentInfo.name, state.segmentSuffix, DICT_EXTENSION);
@@ -71,7 +72,7 @@ final class CompletionFieldsConsumer extends FieldsConsumer {
try {
this.delegateFieldsConsumer = delegatePostingsFormat.fieldsConsumer(state);
dictOut = state.directory.createOutput(dictFile, state.context);
- CodecUtil.writeIndexHeader(dictOut, CODEC_NAME, COMPLETION_VERSION_CURRENT, state.segmentInfo.getId(), state.segmentSuffix);
+ CodecUtil.writeIndexHeader(dictOut, codecName, COMPLETION_VERSION_CURRENT, state.segmentInfo.getId(), state.segmentSuffix);
success = true;
} finally {
if (success == false) {
@@ -122,7 +123,7 @@ final class CompletionFieldsConsumer extends FieldsConsumer {
boolean success = false;
try (IndexOutput indexOut = state.directory.createOutput(indexFile, state.context)) {
delegateFieldsConsumer.close();
- CodecUtil.writeIndexHeader(indexOut, CODEC_NAME, COMPLETION_VERSION_CURRENT, state.segmentInfo.getId(), state.segmentSuffix);
+ CodecUtil.writeIndexHeader(indexOut, codecName, COMPLETION_VERSION_CURRENT, state.segmentInfo.getId(), state.segmentSuffix);
/*
* we write the delegate postings format name so we can load it
* without getting an instance in the ctor
diff --git a/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionFieldsProducer.java b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionFieldsProducer.java
index b21b0b56dbc..945041e28cf 100644
--- a/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionFieldsProducer.java
+++ b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionFieldsProducer.java
@@ -39,7 +39,6 @@ import org.apache.lucene.util.Accountable;
import org.apache.lucene.util.Accountables;
import org.apache.lucene.util.IOUtils;
-import static org.apache.lucene.search.suggest.document.CompletionPostingsFormat.CODEC_NAME;
import static org.apache.lucene.search.suggest.document.CompletionPostingsFormat.COMPLETION_CODEC_VERSION;
import static org.apache.lucene.search.suggest.document.CompletionPostingsFormat.COMPLETION_VERSION_CURRENT;
import static org.apache.lucene.search.suggest.document.CompletionPostingsFormat.DICT_EXTENSION;
@@ -72,7 +71,7 @@ final class CompletionFieldsProducer extends FieldsProducer {
this.readers = readers;
}
- CompletionFieldsProducer(SegmentReadState state, FSTLoadMode fstLoadMode) throws IOException {
+ CompletionFieldsProducer(String codecName, SegmentReadState state, FSTLoadMode fstLoadMode) throws IOException {
String indexFile = IndexFileNames.segmentFileName(state.segmentInfo.name, state.segmentSuffix, INDEX_EXTENSION);
delegateFieldsProducer = null;
boolean success = false;
@@ -81,12 +80,12 @@ final class CompletionFieldsProducer extends FieldsProducer {
// open up dict file containing all fsts
String dictFile = IndexFileNames.segmentFileName(state.segmentInfo.name, state.segmentSuffix, DICT_EXTENSION);
dictIn = state.directory.openInput(dictFile, state.context);
- CodecUtil.checkIndexHeader(dictIn, CODEC_NAME, COMPLETION_CODEC_VERSION, COMPLETION_VERSION_CURRENT, state.segmentInfo.getId(), state.segmentSuffix);
+ CodecUtil.checkIndexHeader(dictIn, codecName, COMPLETION_CODEC_VERSION, COMPLETION_VERSION_CURRENT, state.segmentInfo.getId(), state.segmentSuffix);
// just validate the footer for the dictIn
CodecUtil.retrieveChecksum(dictIn);
// open up index file (fieldNumber, offset)
- CodecUtil.checkIndexHeader(index, CODEC_NAME, COMPLETION_CODEC_VERSION, COMPLETION_VERSION_CURRENT, state.segmentInfo.getId(), state.segmentSuffix);
+ CodecUtil.checkIndexHeader(index, codecName, COMPLETION_CODEC_VERSION, COMPLETION_VERSION_CURRENT, state.segmentInfo.getId(), state.segmentSuffix);
// load delegate PF
PostingsFormat delegatePostingsFormat = PostingsFormat.forName(index.readString());
delegateFieldsProducer = delegatePostingsFormat.fieldsProducer(state);
diff --git a/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionPostingsFormat.java b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionPostingsFormat.java
index 2598ecf9a12..486d00509c1 100644
--- a/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionPostingsFormat.java
+++ b/lucene/suggest/src/java/org/apache/lucene/search/suggest/document/CompletionPostingsFormat.java
@@ -90,7 +90,6 @@ import org.apache.lucene.util.fst.FST;
*/
public abstract class CompletionPostingsFormat extends PostingsFormat {
- static final String CODEC_NAME = "completion";
static final int COMPLETION_CODEC_VERSION = 1;
static final int COMPLETION_VERSION_CURRENT = COMPLETION_CODEC_VERSION;
static final String INDEX_EXTENSION = "cmp";
@@ -121,8 +120,8 @@ public abstract class CompletionPostingsFormat extends PostingsFormat {
/**
* Used only by core Lucene at read-time via Service Provider instantiation
*/
- public CompletionPostingsFormat() {
- this(FSTLoadMode.ON_HEAP);
+ public CompletionPostingsFormat(String name) {
+ this(name, FSTLoadMode.ON_HEAP);
}
/**
@@ -130,8 +129,8 @@ public abstract class CompletionPostingsFormat extends PostingsFormat {
* use the provided <code>fstLoadMode</code> to determine
* if the completion FST should be loaded on or off heap.
*/
- public CompletionPostingsFormat(FSTLoadMode fstLoadMode) {
- super(CODEC_NAME);
+ public CompletionPostingsFormat(String name, FSTLoadMode fstLoadMode) {
+ super(name);
this.fstLoadMode = fstLoadMode;
}
@@ -147,11 +146,11 @@ public abstract class CompletionPostingsFormat extends PostingsFormat {
throw new UnsupportedOperationException("Error - " + getClass().getName()
+ " has been constructed without a choice of PostingsFormat");
}
- return new CompletionFieldsConsumer(delegatePostingsFormat, state);
+ return new CompletionFieldsConsumer(getName(), delegatePostingsFormat, state);
}
@Override
public FieldsProducer fieldsProducer(SegmentReadState state) throws IOException {
- return new CompletionFieldsProducer(state, fstLoadMode);
+ return new CompletionFieldsProducer(getName(), state, fstLoadMode);
}
}
diff --git a/lucene/suggest/src/resources/META-INF/services/org.apache.lucene.codecs.PostingsFormat b/lucene/suggest/src/resources/META-INF/services/org.apache.lucene.codecs.PostingsFormat
index 30695391e49..b74211eb8dd 100644
--- a/lucene/suggest/src/resources/META-INF/services/org.apache.lucene.codecs.PostingsFormat
+++ b/lucene/suggest/src/resources/META-INF/services/org.apache.lucene.codecs.PostingsFormat
@@ -31,3 +31,4 @@
# limitations under the License.
org.apache.lucene.search.suggest.document.Completion50PostingsFormat
+org.apache.lucene.search.suggest.document.Completion84PostingsFormat
diff --git a/lucene/suggest/src/test/org/apache/lucene/search/suggest/document/TestSuggestField.java b/lucene/suggest/src/test/org/apache/lucene/search/suggest/document/TestSuggestField.java
index 68dc014e109..24f5426635e 100644
--- a/lucene/suggest/src/test/org/apache/lucene/search/suggest/document/TestSuggestField.java
+++ b/lucene/suggest/src/test/org/apache/lucene/search/suggest/document/TestSuggestField.java
@@ -16,6 +16,9 @@
*/
package org.apache.lucene.search.suggest.document;
+import static org.apache.lucene.analysis.BaseTokenStreamTestCase.assertTokenStreamContents;
+import static org.hamcrest.core.IsEqual.equalTo;
+
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
@@ -29,7 +32,6 @@ import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CyclicBarrier;
-import com.carrotsearch.randomizedtesting.generators.RandomPicks;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.MockAnalyzer;
import org.apache.lucene.analysis.TokenFilter;
@@ -39,7 +41,7 @@ import org.apache.lucene.analysis.tokenattributes.PayloadAttribute;
import org.apache.lucene.analysis.tokenattributes.TypeAttribute;
import org.apache.lucene.codecs.Codec;
import org.apache.lucene.codecs.PostingsFormat;
-import org.apache.lucene.codecs.lucene80.Lucene80Codec;
+import org.apache.lucene.codecs.lucene84.Lucene84Codec;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.IntPoint;
@@ -54,6 +56,7 @@ import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.suggest.BitsProducer;
import org.apache.lucene.search.suggest.Lookup;
+import org.apache.lucene.search.suggest.document.TopSuggestDocs.SuggestScoreDoc;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.OutputStreamDataOutput;
import org.apache.lucene.util.Bits;
@@ -66,9 +69,7 @@ import org.junit.After;
import org.junit.Before;
import org.junit.Test;
-import static org.apache.lucene.analysis.BaseTokenStreamTestCase.assertTokenStreamContents;
-import static org.apache.lucene.search.suggest.document.TopSuggestDocs.SuggestScoreDoc;
-import static org.hamcrest.core.IsEqual.equalTo;
+import com.carrotsearch.randomizedtesting.generators.RandomPicks;
public class TestSuggestField extends LuceneTestCase {
@@ -886,10 +887,10 @@ public class TestSuggestField extends LuceneTestCase {
static IndexWriterConfig iwcWithSuggestField(Analyzer analyzer, final Set<String> suggestFields) {
IndexWriterConfig iwc = newIndexWriterConfig(random(), analyzer);
iwc.setMergePolicy(newLogMergePolicy());
- Codec filterCodec = new Lucene80Codec() {
+ Codec filterCodec = new Lucene84Codec() {
CompletionPostingsFormat.FSTLoadMode fstLoadMode =
RandomPicks.randomFrom(random(), CompletionPostingsFormat.FSTLoadMode.values());
- PostingsFormat postingsFormat = new Completion50PostingsFormat(fstLoadMode);
+ PostingsFormat postingsFormat = new Completion84PostingsFormat(fstLoadMode);
@Override
public PostingsFormat getPostingsFormatForField(String field) {
diff --git a/lucene/test-framework/src/java/org/apache/lucene/codecs/blockterms/LuceneFixedGap.java b/lucene/test-framework/src/java/org/apache/lucene/codecs/blockterms/LuceneFixedGap.java
index e79638a1d45..7caeb187941 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/codecs/blockterms/LuceneFixedGap.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/codecs/blockterms/LuceneFixedGap.java
@@ -23,9 +23,9 @@ import org.apache.lucene.codecs.FieldsProducer;
import org.apache.lucene.codecs.PostingsFormat;
import org.apache.lucene.codecs.PostingsReaderBase;
import org.apache.lucene.codecs.PostingsWriterBase;
-import org.apache.lucene.codecs.lucene50.Lucene50PostingsFormat; // javadocs
-import org.apache.lucene.codecs.lucene50.Lucene50PostingsReader;
-import org.apache.lucene.codecs.lucene50.Lucene50PostingsWriter;
+import org.apache.lucene.codecs.lucene84.Lucene84PostingsFormat; // javadocs
+import org.apache.lucene.codecs.lucene84.Lucene84PostingsReader;
+import org.apache.lucene.codecs.lucene84.Lucene84PostingsWriter;
import org.apache.lucene.index.SegmentReadState;
import org.apache.lucene.index.SegmentWriteState;
@@ -33,7 +33,7 @@ import org.apache.lucene.index.SegmentWriteState;
// any PostingsFormat and make it ord-able...
/**
- * Customized version of {@link Lucene50PostingsFormat} that uses
+ * Customized version of {@link Lucene84PostingsFormat} that uses
* {@link FixedGapTermsIndexWriter}.
*/
public final class LuceneFixedGap extends PostingsFormat {
@@ -50,7 +50,7 @@ public final class LuceneFixedGap extends PostingsFormat {
@Override
public FieldsConsumer fieldsConsumer(SegmentWriteState state) throws IOException {
- PostingsWriterBase docs = new Lucene50PostingsWriter(state);
+ PostingsWriterBase docs = new Lucene84PostingsWriter(state);
// TODO: should we make the terms index more easily
// pluggable? Ie so that this codec would record which
@@ -87,7 +87,7 @@ public final class LuceneFixedGap extends PostingsFormat {
@Override
public FieldsProducer fieldsProducer(SegmentReadState state) throws IOException {
- PostingsReaderBase postings = new Lucene50PostingsReader(state);
+ PostingsReaderBase postings = new Lucene84PostingsReader(state);
TermsIndexReaderBase indexReader;
boolean success = false;
diff --git a/lucene/test-framework/src/java/org/apache/lucene/codecs/blockterms/LuceneVarGapDocFreqInterval.java b/lucene/test-framework/src/java/org/apache/lucene/codecs/blockterms/LuceneVarGapDocFreqInterval.java
index 67110fecfb9..94421c0f1f0 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/codecs/blockterms/LuceneVarGapDocFreqInterval.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/codecs/blockterms/LuceneVarGapDocFreqInterval.java
@@ -23,9 +23,9 @@ import org.apache.lucene.codecs.FieldsProducer;
import org.apache.lucene.codecs.PostingsFormat;
import org.apache.lucene.codecs.PostingsReaderBase;
import org.apache.lucene.codecs.PostingsWriterBase;
-import org.apache.lucene.codecs.lucene50.Lucene50PostingsFormat; // javadocs
-import org.apache.lucene.codecs.lucene50.Lucene50PostingsReader;
-import org.apache.lucene.codecs.lucene50.Lucene50PostingsWriter;
+import org.apache.lucene.codecs.lucene84.Lucene84PostingsFormat; // javadocs
+import org.apache.lucene.codecs.lucene84.Lucene84PostingsReader;
+import org.apache.lucene.codecs.lucene84.Lucene84PostingsWriter;
import org.apache.lucene.index.SegmentReadState;
import org.apache.lucene.index.SegmentWriteState;
@@ -33,7 +33,7 @@ import org.apache.lucene.index.SegmentWriteState;
// any PostingsFormat and make it ord-able...
/**
- * Customized version of {@link Lucene50PostingsFormat} that uses
+ * Customized version of {@link Lucene84PostingsFormat} that uses
* {@link VariableGapTermsIndexWriter} with a fixed interval, but
* forcing high docfreq terms to be indexed terms.
*/
@@ -53,7 +53,7 @@ public final class LuceneVarGapDocFreqInterval extends PostingsFormat {
@Override
public FieldsConsumer fieldsConsumer(SegmentWriteState state) throws IOException {
- PostingsWriterBase docs = new Lucene50PostingsWriter(state);
+ PostingsWriterBase docs = new Lucene84PostingsWriter(state);
// TODO: should we make the terms index more easily
// pluggable? Ie so that this codec would record which
@@ -90,7 +90,7 @@ public final class LuceneVarGapDocFreqInterval extends PostingsFormat {
@Override
public FieldsProducer fieldsProducer(SegmentReadState state) throws IOException {
- PostingsReaderBase postings = new Lucene50PostingsReader(state);
+ PostingsReaderBase postings = new Lucene84PostingsReader(state);
TermsIndexReaderBase indexReader;
boolean success = false;
diff --git a/lucene/test-framework/src/java/org/apache/lucene/codecs/blockterms/LuceneVarGapFixedInterval.java b/lucene/test-framework/src/java/org/apache/lucene/codecs/blockterms/LuceneVarGapFixedInterval.java
index fe9cedf5107..1049fea56df 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/codecs/blockterms/LuceneVarGapFixedInterval.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/codecs/blockterms/LuceneVarGapFixedInterval.java
@@ -23,9 +23,9 @@ import org.apache.lucene.codecs.FieldsProducer;
import org.apache.lucene.codecs.PostingsFormat;
import org.apache.lucene.codecs.PostingsReaderBase;
import org.apache.lucene.codecs.PostingsWriterBase;
-import org.apache.lucene.codecs.lucene50.Lucene50PostingsFormat; // javadocs
-import org.apache.lucene.codecs.lucene50.Lucene50PostingsReader;
-import org.apache.lucene.codecs.lucene50.Lucene50PostingsWriter;
+import org.apache.lucene.codecs.lucene84.Lucene84PostingsFormat; // javadocs
+import org.apache.lucene.codecs.lucene84.Lucene84PostingsReader;
+import org.apache.lucene.codecs.lucene84.Lucene84PostingsWriter;
import org.apache.lucene.index.SegmentReadState;
import org.apache.lucene.index.SegmentWriteState;
@@ -33,7 +33,7 @@ import org.apache.lucene.index.SegmentWriteState;
// any PostingsFormat and make it ord-able...
/**
- * Customized version of {@link Lucene50PostingsFormat} that uses
+ * Customized version of {@link Lucene84PostingsFormat} that uses
* {@link VariableGapTermsIndexWriter} with a fixed interval.
*/
public final class LuceneVarGapFixedInterval extends PostingsFormat {
@@ -50,7 +50,7 @@ public final class LuceneVarGapFixedInterval extends PostingsFormat {
@Override
public FieldsConsumer fieldsConsumer(SegmentWriteState state) throws IOException {
- PostingsWriterBase docs = new Lucene50PostingsWriter(state);
+ PostingsWriterBase docs = new Lucene84PostingsWriter(state);
// TODO: should we make the terms index more easily
// pluggable? Ie so that this codec would record which
@@ -87,7 +87,7 @@ public final class LuceneVarGapFixedInterval extends PostingsFormat {
@Override
public FieldsProducer fieldsProducer(SegmentReadState state) throws IOException {
- PostingsReaderBase postings = new Lucene50PostingsReader(state);
+ PostingsReaderBase postings = new Lucene84PostingsReader(state);
TermsIndexReaderBase indexReader;
boolean success = false;
diff --git a/lucene/test-framework/src/java/org/apache/lucene/codecs/mockrandom/MockRandomPostingsFormat.java b/lucene/test-framework/src/java/org/apache/lucene/codecs/mockrandom/MockRandomPostingsFormat.java
index 143ba9cefb1..e55eb8747ae 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/codecs/mockrandom/MockRandomPostingsFormat.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/codecs/mockrandom/MockRandomPostingsFormat.java
@@ -39,8 +39,8 @@ import org.apache.lucene.codecs.blocktree.BlockTreeTermsReader;
import org.apache.lucene.codecs.blocktree.BlockTreeTermsWriter;
import org.apache.lucene.codecs.blocktreeords.OrdsBlockTreeTermsReader;
import org.apache.lucene.codecs.blocktreeords.OrdsBlockTreeTermsWriter;
-import org.apache.lucene.codecs.lucene50.Lucene50PostingsReader;
-import org.apache.lucene.codecs.lucene50.Lucene50PostingsWriter;
+import org.apache.lucene.codecs.lucene84.Lucene84PostingsReader;
+import org.apache.lucene.codecs.lucene84.Lucene84PostingsWriter;
import org.apache.lucene.codecs.memory.FSTOrdTermsReader;
import org.apache.lucene.codecs.memory.FSTOrdTermsWriter;
import org.apache.lucene.codecs.memory.FSTTermsReader;
@@ -119,7 +119,7 @@ public final class MockRandomPostingsFormat extends PostingsFormat {
random.nextInt(); // consume a random for buffersize
- PostingsWriterBase postingsWriter = new Lucene50PostingsWriter(state);
+ PostingsWriterBase postingsWriter = new Lucene84PostingsWriter(state);
final FieldsConsumer fields;
final int t1 = random.nextInt(5);
@@ -284,7 +284,7 @@ public final class MockRandomPostingsFormat extends PostingsFormat {
System.out.println("MockRandomCodec: readBufferSize=" + readBufferSize);
}
- PostingsReaderBase postingsReader = new Lucene50PostingsReader(state);
+ PostingsReaderBase postingsReader = new Lucene84PostingsReader(state);
final FieldsProducer fields;
final int t1 = random.nextInt(5);
diff --git a/lucene/test-framework/src/java/org/apache/lucene/codecs/uniformsplit/UniformSplitRot13PostingsFormat.java b/lucene/test-framework/src/java/org/apache/lucene/codecs/uniformsplit/UniformSplitRot13PostingsFormat.java
index 9b7aa40696e..76b6e9cacee 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/codecs/uniformsplit/UniformSplitRot13PostingsFormat.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/codecs/uniformsplit/UniformSplitRot13PostingsFormat.java
@@ -24,8 +24,8 @@ import org.apache.lucene.codecs.FieldsProducer;
import org.apache.lucene.codecs.PostingsFormat;
import org.apache.lucene.codecs.PostingsReaderBase;
import org.apache.lucene.codecs.PostingsWriterBase;
-import org.apache.lucene.codecs.lucene50.Lucene50PostingsReader;
-import org.apache.lucene.codecs.lucene50.Lucene50PostingsWriter;
+import org.apache.lucene.codecs.lucene84.Lucene84PostingsReader;
+import org.apache.lucene.codecs.lucene84.Lucene84PostingsWriter;
import org.apache.lucene.index.SegmentReadState;
import org.apache.lucene.index.SegmentWriteState;
import org.apache.lucene.store.DataOutput;
@@ -59,7 +59,7 @@ public class UniformSplitRot13PostingsFormat extends PostingsFormat {
@Override
public FieldsConsumer fieldsConsumer(SegmentWriteState segmentWriteState) throws IOException {
- PostingsWriterBase postingsWriter = new Lucene50PostingsWriter(segmentWriteState);
+ PostingsWriterBase postingsWriter = new Lucene84PostingsWriter(segmentWriteState);
boolean success = false;
try {
FieldsConsumer fieldsConsumer = createFieldsConsumer(segmentWriteState, postingsWriter);
@@ -121,7 +121,7 @@ public class UniformSplitRot13PostingsFormat extends PostingsFormat {
@Override
public FieldsProducer fieldsProducer(SegmentReadState segmentReadState) throws IOException {
- PostingsReaderBase postingsReader = new Lucene50PostingsReader(segmentReadState);
+ PostingsReaderBase postingsReader = new Lucene84PostingsReader(segmentReadState);
boolean success = false;
try {
FieldsProducer fieldsProducer = createFieldsProducer(segmentReadState, postingsReader);
diff --git a/lucene/test-framework/src/java/org/apache/lucene/geo/BaseGeoPointTestCase.java b/lucene/test-framework/src/java/org/apache/lucene/geo/BaseGeoPointTestCase.java
index 134e0be0c00..3561f253aa3 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/geo/BaseGeoPointTestCase.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/geo/BaseGeoPointTestCase.java
@@ -1275,7 +1275,7 @@ public abstract class BaseGeoPointTestCase extends LuceneTestCase {
// Else seeds may not reproduce:
iwc.setMergeScheduler(new SerialMergeScheduler());
int pointsInLeaf = 2 + random().nextInt(4);
- iwc.setCodec(new FilterCodec("Lucene80", TestUtil.getDefaultCodec()) {
+ iwc.setCodec(new FilterCodec("Lucene84", TestUtil.getDefaultCodec()) {
@Override
public PointsFormat pointsFormat() {
return new PointsFormat() {
diff --git a/lucene/test-framework/src/java/org/apache/lucene/store/BaseDirectoryTestCase.java b/lucene/test-framework/src/java/org/apache/lucene/store/BaseDirectoryTestCase.java
index 4d12f0a60cf..26dfd7dccc5 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/store/BaseDirectoryTestCase.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/store/BaseDirectoryTestCase.java
@@ -183,6 +183,59 @@ public abstract class BaseDirectoryTestCase extends LuceneTestCase {
}
}
+ public void testAlignedLittleEndianLongs() throws Exception {
+ try (Directory dir = getDirectory(createTempDir("testAlignedLittleEndianLongs"))) {
+ try (IndexOutput out = dir.createOutput("littleEndianLongs", newIOContext(random()))) {
+ out.writeLong(Long.reverseBytes(3L));
+ out.writeLong(Long.reverseBytes(Long.MAX_VALUE));
+ out.writeLong(Long.reverseBytes(-3L));
+ }
+ try (IndexInput input = dir.openInput("littleEndianLongs", newIOContext(random()))) {
+ assertEquals(24, input.length());
+ long[] l = new long[4];
+ input.readLELongs(l, 1, 3);
+ assertArrayEquals(new long[] {0L, 3L, Long.MAX_VALUE, -3L}, l);
+ assertEquals(24, input.getFilePointer());
+ }
+ }
+ }
+
+ public void testUnalignedLittleEndianLongs() throws Exception {
+ try (Directory dir = getDirectory(createTempDir("testUnalignedLittleEndianLongs"))) {
+ try (IndexOutput out = dir.createOutput("littleEndianLongs", newIOContext(random()))) {
+ out.writeByte((byte) 2);
+ out.writeLong(Long.reverseBytes(3L));
+ out.writeLong(Long.reverseBytes(Long.MAX_VALUE));
+ out.writeLong(Long.reverseBytes(-3L));
+ }
+ try (IndexInput input = dir.openInput("littleEndianLongs", newIOContext(random()))) {
+ assertEquals(25, input.length());
+ assertEquals(2, input.readByte());
+ long[] l = new long[4];
+ input.readLELongs(l, 1, 3);
+ assertArrayEquals(new long[] {0L, 3L, Long.MAX_VALUE, -3L}, l);
+ assertEquals(25, input.getFilePointer());
+ }
+ }
+ }
+
+ public void testLittleEndianLongsUnderflow() throws Exception {
+ try (Directory dir = getDirectory(createTempDir("testLittleEndianLongsUnderflow"))) {
+ final int offset = random().nextInt(8);
+ final int length = TestUtil.nextInt(random(), 1, 16);
+ try (IndexOutput out = dir.createOutput("littleEndianLongs", newIOContext(random()))) {
+ byte[] b = new byte[offset + length * Long.BYTES - TestUtil.nextInt(random(), 1, Long.BYTES)];
+ random().nextBytes(b);
+ out.writeBytes(b, b.length);
+ }
+ try (IndexInput input = dir.openInput("littleEndianLongs", newIOContext(random()))) {
+ input.seek(offset);
+ expectThrows(EOFException.class,
+ () -> input.readLELongs(new long[length], 0, length));
+ }
+ }
+ }
+
public void testString() throws Exception {
try (Directory dir = getDirectory(createTempDir("testString"))) {
IndexOutput output = dir.createOutput("string", newIOContext(random()));
diff --git a/lucene/test-framework/src/java/org/apache/lucene/util/RamUsageTester.java b/lucene/test-framework/src/java/org/apache/lucene/util/RamUsageTester.java
index fdd7e2e68b5..5ff5c992b6d 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/util/RamUsageTester.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/util/RamUsageTester.java
@@ -22,6 +22,7 @@ import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
import java.nio.file.Path;
import java.security.AccessController;
import java.security.PrivilegedAction;
@@ -239,6 +240,7 @@ public final class RamUsageTester {
// For File and Path, we just take the length of String representation as approximation:
a(File.class, v -> charArraySize(v.toString().length()));
a(Path.class, v -> charArraySize(v.toString().length()));
+ a(ByteOrder.class, v -> 0); // Instances of ByteOrder are constants
}
@SuppressWarnings("unchecked")
diff --git a/lucene/test-framework/src/java/org/apache/lucene/util/TestRuleSetupAndRestoreClassEnv.java b/lucene/test-framework/src/java/org/apache/lucene/util/TestRuleSetupAndRestoreClassEnv.java
index 371237441b1..bd59e8cf40b 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/util/TestRuleSetupAndRestoreClassEnv.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/util/TestRuleSetupAndRestoreClassEnv.java
@@ -43,7 +43,7 @@ import org.apache.lucene.codecs.asserting.AssertingPostingsFormat;
import org.apache.lucene.codecs.cheapbastard.CheapBastardCodec;
import org.apache.lucene.codecs.compressing.CompressingCodec;
import org.apache.lucene.codecs.lucene50.Lucene50StoredFieldsFormat;
-import org.apache.lucene.codecs.lucene80.Lucene80Codec;
+import org.apache.lucene.codecs.lucene84.Lucene84Codec;
import org.apache.lucene.codecs.mockrandom.MockRandomPostingsFormat;
import org.apache.lucene.codecs.simpletext.SimpleTextCodec;
import org.apache.lucene.index.RandomCodec;
@@ -188,8 +188,8 @@ final class TestRuleSetupAndRestoreClassEnv extends AbstractBeforeAfterRule {
codec = new AssertingCodec();
} else if ("Compressing".equals(TEST_CODEC) || ("random".equals(TEST_CODEC) && randomVal == 6 && !shouldAvoidCodec("Compressing"))) {
codec = CompressingCodec.randomInstance(random);
- } else if ("Lucene80".equals(TEST_CODEC) || ("random".equals(TEST_CODEC) && randomVal == 5 && !shouldAvoidCodec("Lucene80"))) {
- codec = new Lucene80Codec(RandomPicks.randomFrom(random, Lucene50StoredFieldsFormat.Mode.values())
+ } else if ("Lucene84".equals(TEST_CODEC) || ("random".equals(TEST_CODEC) && randomVal == 5 && !shouldAvoidCodec("Lucene84"))) {
+ codec = new Lucene84Codec(RandomPicks.randomFrom(random, Lucene50StoredFieldsFormat.Mode.values())
);
} else if (!"random".equals(TEST_CODEC)) {
codec = Codec.forName(TEST_CODEC);
diff --git a/lucene/test-framework/src/java/org/apache/lucene/util/TestUtil.java b/lucene/test-framework/src/java/org/apache/lucene/util/TestUtil.java
index acfc06fdae8..73febcf6434 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/util/TestUtil.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/util/TestUtil.java
@@ -53,9 +53,9 @@ import org.apache.lucene.codecs.asserting.AssertingCodec;
import org.apache.lucene.codecs.blockterms.LuceneFixedGap;
import org.apache.lucene.codecs.blocktree.BlockTreeTermsReader;
import org.apache.lucene.codecs.blocktreeords.BlockTreeOrdsPostingsFormat;
-import org.apache.lucene.codecs.lucene50.Lucene50PostingsFormat;
import org.apache.lucene.codecs.lucene80.Lucene80DocValuesFormat;
-import org.apache.lucene.codecs.lucene80.Lucene80Codec;
+import org.apache.lucene.codecs.lucene84.Lucene84Codec;
+import org.apache.lucene.codecs.lucene84.Lucene84PostingsFormat;
import org.apache.lucene.codecs.perfield.PerFieldDocValuesFormat;
import org.apache.lucene.codecs.perfield.PerFieldPostingsFormat;
import org.apache.lucene.document.BinaryDocValuesField;
@@ -64,7 +64,29 @@ import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.NumericDocValuesField;
import org.apache.lucene.document.SortedDocValuesField;
-import org.apache.lucene.index.*;
+import org.apache.lucene.index.CheckIndex;
+import org.apache.lucene.index.CodecReader;
+import org.apache.lucene.index.ConcurrentMergeScheduler;
+import org.apache.lucene.index.DirectoryReader;
+import org.apache.lucene.index.DocValuesType;
+import org.apache.lucene.index.FieldInfo;
+import org.apache.lucene.index.FilterLeafReader;
+import org.apache.lucene.index.IndexFileNames;
+import org.apache.lucene.index.IndexReader;
+import org.apache.lucene.index.IndexWriter;
+import org.apache.lucene.index.IndexableField;
+import org.apache.lucene.index.LeafReader;
+import org.apache.lucene.index.LeafReaderContext;
+import org.apache.lucene.index.LogMergePolicy;
+import org.apache.lucene.index.MergePolicy;
+import org.apache.lucene.index.MergeScheduler;
+import org.apache.lucene.index.MultiTerms;
+import org.apache.lucene.index.PostingsEnum;
+import org.apache.lucene.index.SegmentReader;
+import org.apache.lucene.index.SlowCodecReaderWrapper;
+import org.apache.lucene.index.Terms;
+import org.apache.lucene.index.TermsEnum;
+import org.apache.lucene.index.TieredMergePolicy;
import org.apache.lucene.mockfile.FilterFileSystem;
import org.apache.lucene.mockfile.VirusCheckingFS;
import org.apache.lucene.mockfile.WindowsFS;
@@ -898,14 +920,14 @@ public final class TestUtil {
* This may be different than {@link Codec#getDefault()} because that is randomized.
*/
public static Codec getDefaultCodec() {
- return new Lucene80Codec();
+ return new Lucene84Codec();
}
/**
* Returns the actual default postings format (e.g. LuceneMNPostingsFormat for this version of Lucene.
*/
public static PostingsFormat getDefaultPostingsFormat() {
- return new Lucene50PostingsFormat();
+ return new Lucene84PostingsFormat();
}
/**
@@ -913,7 +935,7 @@ public final class TestUtil {
* @lucene.internal this may disappear at any time
*/
public static PostingsFormat getDefaultPostingsFormat(int minItemsPerBlock, int maxItemsPerBlock, BlockTreeTermsReader.FSTLoadMode fstLoadMode) {
- return new Lucene50PostingsFormat(minItemsPerBlock, maxItemsPerBlock, fstLoadMode);
+ return new Lucene84PostingsFormat(minItemsPerBlock, maxItemsPerBlock, fstLoadMode);
}
/** Returns a random postings format that supports term ordinals */
diff --git a/solr/core/src/java/org/apache/solr/core/SchemaCodecFactory.java b/solr/core/src/java/org/apache/solr/core/SchemaCodecFactory.java
index 5adc161b5a0..761c7501877 100644
--- a/solr/core/src/java/org/apache/solr/core/SchemaCodecFactory.java
+++ b/solr/core/src/java/org/apache/solr/core/SchemaCodecFactory.java
@@ -24,9 +24,9 @@ import org.apache.lucene.codecs.Codec;
import org.apache.lucene.codecs.DocValuesFormat;
import org.apache.lucene.codecs.PostingsFormat;
import org.apache.lucene.codecs.lucene50.Lucene50StoredFieldsFormat.Mode;
-import org.apache.lucene.codecs.lucene80.Lucene80Codec;
-import org.apache.solr.common.SolrException.ErrorCode;
+import org.apache.lucene.codecs.lucene84.Lucene84Codec;
import org.apache.solr.common.SolrException;
+import org.apache.solr.common.SolrException.ErrorCode;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.schema.SchemaField;
import org.apache.solr.util.plugin.SolrCoreAware;
@@ -91,7 +91,7 @@ public class SchemaCodecFactory extends CodecFactory implements SolrCoreAware {
compressionMode = SOLR_DEFAULT_COMPRESSION_MODE;
log.debug("Using default compressionMode: " + compressionMode);
}
- codec = new Lucene80Codec(compressionMode) {
+ codec = new Lucene84Codec(compressionMode) {
@Override
public PostingsFormat getPostingsFormatForField(String field) {
final SchemaField schemaField = core.getLatestSchema().getFieldOrNull(field);
diff --git a/solr/core/src/test-files/solr/collection1/conf/schema_codec.xml b/solr/core/src/test-files/solr/collection1/conf/schema_codec.xml
index 3cb2f721cca..e2add4eb2a8 100644
--- a/solr/core/src/test-files/solr/collection1/conf/schema_codec.xml
+++ b/solr/core/src/test-files/solr/collection1/conf/schema_codec.xml
@@ -20,7 +20,7 @@
as a way to vet that the configuration actually matters.
-->
<fieldType name="string_direct" class="solr.StrField" postingsFormat="Direct" docValuesFormat="Asserting" />
- <fieldType name="string_standard" class="solr.StrField" postingsFormat="Lucene50"/>
+ <fieldType name="string_standard" class="solr.StrField" postingsFormat="Lucene84"/>
<fieldType name="string_disk" class="solr.StrField" docValuesFormat="Lucene80"/>