Apache Lucene open-source search software
Allow FST builder to use different writer (#12543) (#12624)
Dzung Buib6999818474c
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene90/blocktree/Lucene90BlockTreeTermsWriter.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene90/blocktree/Lucene90BlockTreeTermsWriter.javaindex acd75092022..463532218cd 100644--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene90/blocktree/Lucene90BlockTreeTermsWriter.java+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene90/blocktree/Lucene90BlockTreeTermsWriter.java@@ -16,6 +16,8 @@*/package org.apache.lucene.codecs.lucene90.blocktree;+import static org.apache.lucene.util.fst.FSTCompiler.getOnHeapReaderWriter;+import java.io.IOException;import java.util.ArrayList;import java.util.Arrays;@@ -525,7 +527,7 @@ public final class Lucene90BlockTreeTermsWriter extends FieldsConsumer {// Disable suffixes sharing for block tree index because suffixes are mostly dropped// from the FST index and left in the term blocks..suffixRAMLimitMB(0d)- .bytesPageBits(pageBits)+ .dataOutput(getOnHeapReaderWriter(pageBits)).build();// if (DEBUG) {// System.out.println(" compile index for prefix=" + prefix);diff --git a/lucene/core/src/java/org/apache/lucene/util/fst/BytesStore.java b/lucene/core/src/java/org/apache/lucene/util/fst/BytesStore.javadeleted file mode 100644index 87b29fe8b7b..00000000000--- a/lucene/core/src/java/org/apache/lucene/util/fst/BytesStore.java+++ /dev/null@@ -1,478 +0,0 @@-/*- * 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.util.fst;--import java.io.IOException;-import java.util.ArrayList;-import java.util.List;-import org.apache.lucene.store.DataInput;-import org.apache.lucene.store.DataOutput;-import org.apache.lucene.util.RamUsageEstimator;--// TODO: merge with PagedBytes, except PagedBytes doesn't-// let you read while writing which FST needs--class BytesStore extends DataOutput implements FSTReader {-- private static final long BASE_RAM_BYTES_USED =- RamUsageEstimator.shallowSizeOfInstance(BytesStore.class)- + RamUsageEstimator.shallowSizeOfInstance(ArrayList.class);-- private final List<byte[]> blocks = new ArrayList<>();-- private final int blockSize;- private final int blockBits;- private final int blockMask;-- private byte[] current;- private int nextWrite;-- public BytesStore(int blockBits) {- this.blockBits = blockBits;- blockSize = 1 << blockBits;- blockMask = blockSize - 1;- nextWrite = blockSize;- }-- @Override- public void writeByte(byte b) {- if (nextWrite == blockSize) {- current = new byte[blockSize];- blocks.add(current);- nextWrite = 0;- }- current[nextWrite++] = b;- }-- @Override- public void writeBytes(byte[] b, int offset, int len) {- while (len > 0) {- int chunk = blockSize - nextWrite;- if (len <= chunk) {- assert b != null;- assert current != null;- System.arraycopy(b, offset, current, nextWrite, len);- nextWrite += len;- break;- } else {- if (chunk > 0) {- System.arraycopy(b, offset, current, nextWrite, chunk);- offset += chunk;- len -= chunk;- }- current = new byte[blockSize];- blocks.add(current);- nextWrite = 0;- }- }- }-- int getBlockBits() {- return blockBits;- }-- /**- * Absolute writeBytes without changing the current position. Note: this cannot "grow" the bytes,- * so you must only call it on already written parts.- */- void writeBytes(long dest, byte[] b, int offset, int len) {- // System.out.println(" BS.writeBytes dest=" + dest + " offset=" + offset + " len=" + len);- assert dest + len <= getPosition() : "dest=" + dest + " pos=" + getPosition() + " len=" + len;-- // Note: weird: must go "backwards" because copyBytes- // calls us with overlapping src/dest. If we- // go forwards then we overwrite bytes before we can- // copy them:-- /*- int blockIndex = dest >> blockBits;- int upto = dest & blockMask;- byte[] block = blocks.get(blockIndex);- while (len > 0) {- int chunk = blockSize - upto;- System.out.println(" cycle chunk=" + chunk + " len=" + len);- if (len <= chunk) {- System.arraycopy(b, offset, block, upto, len);- break;- } else {- System.arraycopy(b, offset, block, upto, chunk);- offset += chunk;- len -= chunk;- blockIndex++;- block = blocks.get(blockIndex);- upto = 0;- }- }- */-- final long end = dest + len;- int blockIndex = (int) (end >> blockBits);- int downTo = (int) (end & blockMask);- if (downTo == 0) {- blockIndex--;- downTo = blockSize;- }- byte[] block = blocks.get(blockIndex);-- while (len > 0) {- // System.out.println(" cycle downTo=" + downTo + " len=" + len);- if (len <= downTo) {- // System.out.println(" final: offset=" + offset + " len=" + len + " dest=" +- // (downTo-len));- System.arraycopy(b, offset, block, downTo - len, len);- break;- } else {- len -= downTo;- // System.out.println(" partial: offset=" + (offset + len) + " len=" + downTo + "- // dest=0");- System.arraycopy(b, offset + len, block, 0, downTo);- blockIndex--;- block = blocks.get(blockIndex);- downTo = blockSize;- }- }- }-- @Override- public void copyBytes(DataInput input, long numBytes) throws IOException {- assert numBytes >= 0 : "numBytes=" + numBytes;- assert input != null;- long len = numBytes;- while (len > 0) {- int chunk = blockSize - nextWrite;- int l = (int) Math.min(chunk, len);- if (l > 0) {- assert current != null;- input.readBytes(current, nextWrite, l);- nextWrite += l;- len -= l;- } else {- current = new byte[blockSize];- blocks.add(current);- nextWrite = 0;- }- }- }-- /**- * Absolute copy bytes self to self, without changing the position. Note: this cannot "grow" the- * bytes, so must only call it on already written parts.- */- public void copyBytes(long src, long dest, int len) {- // System.out.println("BS.copyBytes src=" + src + " dest=" + dest + " len=" + len);- assert src < dest;-- // Note: weird: must go "backwards" because copyBytes- // calls us with overlapping src/dest. If we- // go forwards then we overwrite bytes before we can- // copy them:-- /*- int blockIndex = src >> blockBits;- int upto = src & blockMask;- byte[] block = blocks.get(blockIndex);- while (len > 0) {- int chunk = blockSize - upto;- System.out.println(" cycle: chunk=" + chunk + " len=" + len);- if (len <= chunk) {- writeBytes(dest, block, upto, len);- break;- } else {- writeBytes(dest, block, upto, chunk);- blockIndex++;- block = blocks.get(blockIndex);- upto = 0;- len -= chunk;- dest += chunk;- }- }- */-- long end = src + len;-- int blockIndex = (int) (end >> blockBits);- int downTo = (int) (end & blockMask);- if (downTo == 0) {- blockIndex--;- downTo = blockSize;- }- byte[] block = blocks.get(blockIndex);-- while (len > 0) {- // System.out.println(" cycle downTo=" + downTo);- if (len <= downTo) {- // System.out.println(" finish");- writeBytes(dest, block, downTo - len, len);- break;- } else {- // System.out.println(" partial");- len -= downTo;- writeBytes(dest + len, block, 0, downTo);- blockIndex--;- block = blocks.get(blockIndex);- downTo = blockSize;- }- }- }-- /** Copies bytes from this store to a target byte array. */- public void writeTo(long src, byte[] dest, int offset, int len) {- int blockIndex = (int) (src >> blockBits);- int upto = (int) (src & blockMask);- byte[] block = blocks.get(blockIndex);- while (len > 0) {- int chunk = blockSize - upto;- if (len <= chunk) {- System.arraycopy(block, upto, dest, offset, len);- break;- } else {- System.arraycopy(block, upto, dest, offset, chunk);- blockIndex++;- block = blocks.get(blockIndex);- upto = 0;- len -= chunk;- offset += chunk;- }- }- }-- /** Reverse from srcPos, inclusive, to destPos, inclusive. */- public void reverse(long srcPos, long destPos) {- assert srcPos < destPos;- assert destPos < getPosition();- // System.out.println("reverse src=" + srcPos + " dest=" + destPos);-- int srcBlockIndex = (int) (srcPos >> blockBits);- int src = (int) (srcPos & blockMask);- byte[] srcBlock = blocks.get(srcBlockIndex);-- int destBlockIndex = (int) (destPos >> blockBits);- int dest = (int) (destPos & blockMask);- byte[] destBlock = blocks.get(destBlockIndex);- // System.out.println(" srcBlock=" + srcBlockIndex + " destBlock=" + destBlockIndex);-- int limit = (int) (destPos - srcPos + 1) / 2;- for (int i = 0; i < limit; i++) {- // System.out.println(" cycle src=" + src + " dest=" + dest);- byte b = srcBlock[src];- srcBlock[src] = destBlock[dest];- destBlock[dest] = b;- src++;- if (src == blockSize) {- srcBlockIndex++;- srcBlock = blocks.get(srcBlockIndex);- // System.out.println(" set destBlock=" + destBlock + " srcBlock=" + srcBlock);- src = 0;- }-- dest--;- if (dest == -1) {- destBlockIndex--;- destBlock = blocks.get(destBlockIndex);- // System.out.println(" set destBlock=" + destBlock + " srcBlock=" + srcBlock);- dest = blockSize - 1;- }- }- }-- private void skipBytes(int len) {- while (len > 0) {- int chunk = blockSize - nextWrite;- if (len <= chunk) {- nextWrite += len;- break;- } else {- len -= chunk;- current = new byte[blockSize];- blocks.add(current);- nextWrite = 0;- }- }- }-- public long getPosition() {- return ((long) blocks.size() - 1) * blockSize + nextWrite;- }-- /** Set the position of this BytesStore, truncating or expanding if needed */- public void setPosition(long newLen) {- assert newLen >= 0;- long oldPosition = getPosition();- if (newLen > oldPosition) {- skipBytes((int) (newLen - oldPosition));- return;- }- int blockIndex = (int) (newLen >> blockBits);- nextWrite = (int) (newLen & blockMask);- if (nextWrite == 0) {- blockIndex--;- nextWrite = blockSize;- }- blocks.subList(blockIndex + 1, blocks.size()).clear();- if (newLen == 0) {- current = null;- } else {- current = blocks.get(blockIndex);- }- assert newLen == getPosition();- }-- public void finish() {- if (current != null) {- byte[] lastBuffer = new byte[nextWrite];- System.arraycopy(current, 0, lastBuffer, 0, nextWrite);- blocks.set(blocks.size() - 1, lastBuffer);- current = null;- }- }-- /** Writes all of our bytes to the target {@link DataOutput}. */- @Override- public void writeTo(DataOutput out) throws IOException {- for (byte[] block : blocks) {- out.writeBytes(block, 0, block.length);- }- }-- public FST.BytesReader getForwardReader() {- if (blocks.size() == 1) {- return new ForwardBytesReader(blocks.get(0));- }- return new FST.BytesReader() {- private byte[] current;- private int nextBuffer;- private int nextRead = blockSize;-- @Override- public byte readByte() {- if (nextRead == blockSize) {- current = blocks.get(nextBuffer++);- nextRead = 0;- }- return current[nextRead++];- }-- @Override- public void skipBytes(long count) {- setPosition(getPosition() + count);- }-- @Override- public void readBytes(byte[] b, int offset, int len) {- while (len > 0) {- int chunkLeft = blockSize - nextRead;- if (len <= chunkLeft) {- System.arraycopy(current, nextRead, b, offset, len);- nextRead += len;- break;- } else {- if (chunkLeft > 0) {- System.arraycopy(current, nextRead, b, offset, chunkLeft);- offset += chunkLeft;- len -= chunkLeft;- }- current = blocks.get(nextBuffer++);- nextRead = 0;- }- }- }-- @Override- public long getPosition() {- return ((long) nextBuffer - 1) * blockSize + nextRead;- }-- @Override- public void setPosition(long pos) {- int bufferIndex = (int) (pos >> blockBits);- if (nextBuffer != bufferIndex + 1) {- nextBuffer = bufferIndex + 1;- current = blocks.get(bufferIndex);- }- nextRead = (int) (pos & blockMask);- assert getPosition() == pos;- }- };- }-- @Override- public FST.BytesReader getReverseBytesReader() {- if (blocks.size() == 1) {- return new ReverseBytesReader(blocks.get(0));- }- return new FST.BytesReader() {- private byte[] current = blocks.size() == 0 ? null : blocks.get(0);- private int nextBuffer = -1;- private int nextRead = 0;-- @Override- public byte readByte() {- if (nextRead == -1) {- current = blocks.get(nextBuffer--);- nextRead = blockSize - 1;- }- return current[nextRead--];- }-- @Override- public void skipBytes(long count) {- setPosition(getPosition() - count);- }-- @Override- public void readBytes(byte[] b, int offset, int len) {- for (int i = 0; i < len; i++) {- b[offset + i] = readByte();- }- }-- @Override- public long getPosition() {- return ((long) nextBuffer + 1) * blockSize + nextRead;- }-- @Override- public void setPosition(long pos) {- // NOTE: a little weird because if you- // setPosition(0), the next byte you read is- // bytes[0] ... but I would expect bytes[-1] (ie,- // EOF)...?- int bufferIndex = (int) (pos >> blockBits);- if (nextBuffer != bufferIndex - 1) {- nextBuffer = bufferIndex - 1;- current = blocks.get(bufferIndex);- }- nextRead = (int) (pos & blockMask);- assert getPosition() == pos : "pos=" + pos + " getPos()=" + getPosition();- }- };- }-- @Override- public long ramBytesUsed() {- long size = BASE_RAM_BYTES_USED;- for (byte[] block : blocks) {- size += RamUsageEstimator.sizeOf(block);- }- return size;- }-- @Override- public String toString() {- return getClass().getSimpleName() + "(numBlocks=" + blocks.size() + ")";- }-}diff --git a/lucene/core/src/java/org/apache/lucene/util/fst/FST.java b/lucene/core/src/java/org/apache/lucene/util/fst/FST.javaindex 0dd35618e8e..f49f61767e4 100644--- a/lucene/core/src/java/org/apache/lucene/util/fst/FST.java+++ b/lucene/core/src/java/org/apache/lucene/util/fst/FST.java@@ -17,6 +17,7 @@package org.apache.lucene.util.fst;import static org.apache.lucene.util.fst.FST.Arc.BitTable;+import static org.apache.lucene.util.fst.FSTCompiler.getOnHeapReaderWriter;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;@@ -25,6 +26,7 @@ import java.io.InputStream;import java.io.OutputStream;import java.nio.file.Files;import java.nio.file.Path;+import java.util.Objects;import org.apache.lucene.codecs.CodecUtil;import org.apache.lucene.index.CorruptIndexException;import org.apache.lucene.store.ByteBuffersDataOutput;@@ -123,10 +125,7 @@ public final class FST<T> implements Accountable {/** If arc has this label then that arc is final/accepted */public static final int END_LABEL = -1;- /**- * A {@link BytesStore}, used during building, or during reading when the FST is very large (more- * than 1 GB). If the FST is less than 1 GB then bytesArray is set instead.- */+ /** The reader of the FST, used to read bytes from the underlying FST storage */private final FSTReader fstReader;public final Outputs<T> outputs;@@ -419,7 +418,8 @@ public final class FST<T> implements Accountable {/** Create the FST with a metadata object and a FSTReader. */FST(FSTMetadata<T> metadata, FSTReader fstReader) {- this.metadata = metadata;+ assert fstReader != null;+ this.metadata = Objects.requireNonNull(metadata, "FSTMetadata cannot be null");this.outputs = metadata.outputs;this.fstReader = fstReader;}@@ -442,10 +442,12 @@ public final class FST<T> implements Accountable {if (metaIn.readByte() == 1) {// accepts empty string// 1 KB blocks:- BytesStore emptyBytes = new BytesStore(10);+ ReadWriteDataOutput emptyBytes = (ReadWriteDataOutput) getOnHeapReaderWriter(10);int numBytes = metaIn.readVInt();emptyBytes.copyBytes(metaIn, numBytes);+ emptyBytes.freeze();+// De-serialize empty-string output:BytesReader reader = emptyBytes.getReverseBytesReader();// NoOutputs uses 0 bytes when writing its output,@@ -500,6 +502,14 @@ public final class FST<T> implements Accountable {return metadata;}+ /**+ * Save the FST to DataOutput. If you use an {@link org.apache.lucene.store.IndexOutput} to build+ * the FST, then you should not and do not need to call this method, as the FST is already saved.+ * Doing so will throw an {@link UnsupportedOperationException}.+ *+ * @param metaOut the DataOutput to write the metadata to+ * @param out the DataOutput to write the FST bytes to+ */public void save(DataOutput metaOut, DataOutput out) throws IOException {saveMetadata(metaOut);fstReader.writeTo(out);@@ -508,7 +518,7 @@ public final class FST<T> implements Accountable {/*** Save the metadata to a DataOutput*- * @param metaOut the DataOutput to save+ * @param metaOut the DataOutput to write the metadata to*/public void saveMetadata(DataOutput metaOut) throws IOException {CodecUtil.writeHeader(metaOut, FILE_FORMAT_NAME, VERSION_CURRENT);diff --git a/lucene/core/src/java/org/apache/lucene/util/fst/FSTCompiler.java b/lucene/core/src/java/org/apache/lucene/util/fst/FSTCompiler.javaindex be6bb663ca9..da1fff8ec15 100644--- a/lucene/core/src/java/org/apache/lucene/util/fst/FSTCompiler.java+++ b/lucene/core/src/java/org/apache/lucene/util/fst/FSTCompiler.java@@ -16,6 +16,8 @@*/package org.apache.lucene.util.fst;+import static org.apache.lucene.store.ByteBuffersDataOutput.ALLOCATE_BB_ON_HEAP;+import static org.apache.lucene.store.ByteBuffersDataOutput.NO_REUSE;import static org.apache.lucene.util.fst.FST.ARCS_FOR_BINARY_SEARCH;import static org.apache.lucene.util.fst.FST.ARCS_FOR_CONTINUOUS;import static org.apache.lucene.util.fst.FST.ARCS_FOR_DIRECT_ADDRESSING;@@ -31,16 +33,16 @@ import static org.apache.lucene.util.fst.FST.VERSION_CURRENT;import static org.apache.lucene.util.fst.FST.getNumPresenceBytes;import java.io.IOException;+import java.util.Objects;import org.apache.lucene.store.ByteArrayDataOutput;+import org.apache.lucene.store.ByteBuffersDataOutput;import org.apache.lucene.store.DataOutput;+import org.apache.lucene.util.Accountable;import org.apache.lucene.util.ArrayUtil;import org.apache.lucene.util.IntsRef;import org.apache.lucene.util.IntsRefBuilder;import org.apache.lucene.util.fst.FST.INPUT_TYPE; // javadoc-// TODO: could we somehow stream an FST to disk while we-// build it?-/*** Builds a minimal FST (maps an IntsRef term to an arbitrary output) from pre-sorted terms with* outputs. The FST becomes an FSA if you use NoOutputs. The FST is written on-the-fly into a@@ -55,6 +57,17 @@ import org.apache.lucene.util.fst.FST.INPUT_TYPE; // javadoc* <p>FSTs larger than 2.1GB are now possible (as of Lucene 4.2). FSTs containing more than 2.1B* nodes are also now possible, however they cannot be packed.*+ * <p>It now supports 3 different workflows:+ *+ * <p>- Build FST and use it immediately entirely in RAM and then discard it+ *+ * <p>- Build FST and use it immediately entirely in RAM and also save it to other DataOutput, and+ * load it later and use it+ *+ * <p>- Build FST but stream it immediately to disk (except the FSTMetaData, to be saved at the+ * end). In order to use it, you need to construct the corresponding DataInput and use the FST+ * constructor to read it.+ ** @lucene.experimental*/public class FSTCompiler<T> {@@ -85,6 +98,10 @@ public class FSTCompiler<T> {*/private static final float DIRECT_ADDRESSING_MAX_OVERSIZE_WITH_CREDIT_FACTOR = 1.66f;+ // a FSTReader used when a non-FSTReader DataOutput is configured.+ // it will throw exceptions if attempt to call getReverseBytesReader() or writeTo(DataOutput)+ private static final FSTReader NULL_FST_READER = new NullFSTReader();+private final NodeHash<T> dedupHash;final FST<T> fst;private final T NO_OUTPUT;@@ -120,22 +137,45 @@ public class FSTCompiler<T> {final float directAddressingMaxOversizingFactor;long directAddressingExpansionCredit;- final BytesStore bytes;+ // the DataOutput to stream the FST bytes to+ final DataOutput dataOutput;++ // buffer to store bytes for the one node we are currently writing+ final GrowableByteArrayDataOutput scratchBytes = new GrowableByteArrayDataOutput();++ private long numBytesWritten;++ /**+ * Get an on-heap DataOutput that allows the FST to be read immediately after writing, and also+ * optionally saved to an external DataOutput.+ *+ * @param blockBits how many bits wide to make each block of the DataOutput+ * @return the DataOutput+ */+ public static DataOutput getOnHeapReaderWriter(int blockBits) {+ return new ReadWriteDataOutput(+ new ByteBuffersDataOutput(blockBits, blockBits, ALLOCATE_BB_ON_HEAP, NO_REUSE));+ }private FSTCompiler(FST.INPUT_TYPE inputType,double suffixRAMLimitMB,Outputs<T> outputs,boolean allowFixedLengthArcs,- int bytesPageBits,- float directAddressingMaxOversizingFactor) {+ DataOutput dataOutput,+ float directAddressingMaxOversizingFactor)+ throws IOException {this.allowFixedLengthArcs = allowFixedLengthArcs;this.directAddressingMaxOversizingFactor = directAddressingMaxOversizingFactor;- bytes = new BytesStore(bytesPageBits);// pad: ensure no node gets address 0 which is reserved to mean// the stop state w/ no arcs- bytes.writeByte((byte) 0);- fst = new FST<>(new FST.FSTMetadata<>(inputType, outputs, null, -1, VERSION_CURRENT, 0), bytes);+ dataOutput.writeByte((byte) 0);+ numBytesWritten++;+ this.dataOutput = dataOutput;+ fst =+ new FST<>(+ new FST.FSTMetadata<>(inputType, outputs, null, -1, VERSION_CURRENT, 0),+ toFSTReader(dataOutput));if (suffixRAMLimitMB < 0) {throw new IllegalArgumentException("ramLimitMB must be >= 0; got: " + suffixRAMLimitMB);} else if (suffixRAMLimitMB > 0) {@@ -153,6 +193,40 @@ public class FSTCompiler<T> {}}+ // Get the respective FSTReader of the DataOutput. If the DataOutput is also a FSTReader then we+ // will use it, otherwise we will return a NullFSTReader. Attempting to read from a FST with+ // NullFSTReader will throw UnsupportedOperationException+ private FSTReader toFSTReader(DataOutput dataOutput) {+ if (dataOutput instanceof FSTReader) {+ return (FSTReader) dataOutput;+ }+ return NULL_FST_READER;+ }++ /**+ * This class is used for FST backed by non-FSTReader DataOutput. It does not allow getting the+ * reverse BytesReader nor writing to a DataOutput.+ */+ private static final class NullFSTReader implements FSTReader {++ @Override+ public long ramBytesUsed() {+ return 0;+ }++ @Override+ public FST.BytesReader getReverseBytesReader() {+ throw new UnsupportedOperationException(+ "FST was not constructed with getOnHeapReaderWriter()");+ }++ @Override+ public void writeTo(DataOutput out) {+ throw new UnsupportedOperationException(+ "FST was not constructed with getOnHeapReaderWriter()");+ }+ }+/*** Fluent-style constructor for FST {@link FSTCompiler}.*@@ -165,7 +239,7 @@ public class FSTCompiler<T> {private final Outputs<T> outputs;private double suffixRAMLimitMB = 32.0;private boolean allowFixedLengthArcs = true;- private int bytesPageBits = 15;+ private DataOutput dataOutput;private float directAddressingMaxOversizingFactor = DIRECT_ADDRESSING_MAX_OVERSIZING_FACTOR;/**@@ -218,13 +292,18 @@ public class FSTCompiler<T> {}/**- * How many bits wide to make each byte[] block in the BytesStore; if you know the FST will be- * large then make this larger. For example 15 bits = 32768 byte pages.+ * Set the {@link DataOutput} which is used for low-level writing of FST. If you want the FST to+ * be immediately readable, you need to use {@link FSTCompiler#getOnHeapReaderWriter(int)}.+ *+ * <p>Otherwise you need to construct the corresponding {@link+ * org.apache.lucene.store.DataInput} and use the FST constructor to read it.*- * <p>Default = 15.+ * @param dataOutput the DataOutput+ * @return this builder+ * @see FSTCompiler#getOnHeapReaderWriter(int)*/- public Builder<T> bytesPageBits(int bytesPageBits) {- this.bytesPageBits = bytesPageBits;+ public Builder<T> dataOutput(DataOutput dataOutput) {+ this.dataOutput = Objects.requireNonNull(dataOutput, "DataOutput cannot be null");return this;}@@ -248,12 +327,16 @@ public class FSTCompiler<T> {/** Creates a new {@link FSTCompiler}. */public FSTCompiler<T> build() throws IOException {+ // create a default DataOutput if not specified+ if (dataOutput == null) {+ dataOutput = getOnHeapReaderWriter(15);+ }return new FSTCompiler<>(inputType,suffixRAMLimitMB,outputs,allowFixedLengthArcs,- bytesPageBits,+ dataOutput,directAddressingMaxOversizingFactor);}}@@ -271,13 +354,9 @@ public class FSTCompiler<T> {return arcCount;}- public long getMappedStateCount() {- return dedupHash == null ? 0 : nodeCount;- }-- private CompiledNode compileNode(UnCompiledNode<T> nodeIn, int tailLength) throws IOException {+ private CompiledNode compileNode(UnCompiledNode<T> nodeIn) throws IOException {final long node;- long bytesPosStart = bytes.getPosition();+ long bytesPosStart = numBytesWritten;if (dedupHash != null) {if (nodeIn.numArcs == 0) {node = addNode(nodeIn);@@ -288,9 +367,10 @@ public class FSTCompiler<T> {} else {node = addNode(nodeIn);}+assert node != -2;- long bytesPosEnd = bytes.getPosition();+ long bytesPosEnd = numBytesWritten;if (bytesPosEnd != bytesPosStart) {// The FST added a new node:assert bytesPosEnd > bytesPosStart;@@ -315,8 +395,8 @@ public class FSTCompiler<T> {return NON_FINAL_END_NODE;}}- final long startAddress = bytes.getPosition();- // System.out.println(" startAddr=" + startAddress);+ // reset the scratch writer to prepare for new write+ scratchBytes.setPosition(0);final boolean doFixedLengthArcs = shouldExpandNodeWithFixedLengthArcs(nodeIn);if (doFixedLengthArcs) {@@ -331,7 +411,7 @@ public class FSTCompiler<T> {final int lastArc = nodeIn.numArcs - 1;- long lastArcStart = bytes.getPosition();+ long lastArcStart = 0;int maxBytesPerArc = 0;int maxBytesPerArcWithoutLabel = 0;for (int arcIdx = 0; arcIdx < nodeIn.numArcs; arcIdx++) {@@ -371,38 +451,38 @@ public class FSTCompiler<T> {flags += BIT_ARC_HAS_OUTPUT;}- bytes.writeByte((byte) flags);- long labelStart = bytes.getPosition();- writeLabel(bytes, arc.label);- int numLabelBytes = (int) (bytes.getPosition() - labelStart);+ scratchBytes.writeByte((byte) flags);+ long labelStart = scratchBytes.getPosition();+ writeLabel(scratchBytes, arc.label);+ int numLabelBytes = (int) (scratchBytes.getPosition() - labelStart);// System.out.println(" write arc: label=" + (char) arc.label + " flags=" + flags + "// target=" + target.node + " pos=" + bytes.getPosition() + " output=" +// outputs.outputToString(arc.output));if (arc.output != NO_OUTPUT) {- fst.outputs.write(arc.output, bytes);+ fst.outputs.write(arc.output, scratchBytes);// System.out.println(" write output");}if (arc.nextFinalOutput != NO_OUTPUT) {// System.out.println(" write final output");- fst.outputs.writeFinalOutput(arc.nextFinalOutput, bytes);+ fst.outputs.writeFinalOutput(arc.nextFinalOutput, scratchBytes);}if (targetHasArcs && (flags & BIT_TARGET_NEXT) == 0) {assert target.node > 0;// System.out.println(" write target");- bytes.writeVLong(target.node);+ scratchBytes.writeVLong(target.node);}// just write the arcs "like normal" on first pass, but record how many bytes each one took// and max byte size:if (doFixedLengthArcs) {- int numArcBytes = (int) (bytes.getPosition() - lastArcStart);+ int numArcBytes = (int) (scratchBytes.getPosition() - lastArcStart);numBytesPerArc[arcIdx] = numArcBytes;numLabelBytesPerArc[arcIdx] = numLabelBytes;- lastArcStart = bytes.getPosition();+ lastArcStart = scratchBytes.getPosition();maxBytesPerArc = Math.max(maxBytesPerArc, numArcBytes);maxBytesPerArcWithoutLabel =Math.max(maxBytesPerArcWithoutLabel, numArcBytes - numLabelBytes);@@ -439,23 +519,25 @@ public class FSTCompiler<T> {boolean continuousLabel = labelRange == nodeIn.numArcs;if (continuousLabel) {writeNodeForDirectAddressingOrContinuous(- nodeIn, startAddress, maxBytesPerArcWithoutLabel, labelRange, true);+ nodeIn, maxBytesPerArcWithoutLabel, labelRange, true);continuousNodeCount++;} else if (shouldExpandNodeWithDirectAddressing(nodeIn, maxBytesPerArc, maxBytesPerArcWithoutLabel, labelRange)) {writeNodeForDirectAddressingOrContinuous(- nodeIn, startAddress, maxBytesPerArcWithoutLabel, labelRange, false);+ nodeIn, maxBytesPerArcWithoutLabel, labelRange, false);directAddressingNodeCount++;} else {- writeNodeForBinarySearch(nodeIn, startAddress, maxBytesPerArc);+ writeNodeForBinarySearch(nodeIn, maxBytesPerArc);binarySearchNodeCount++;}}- final long thisNodeAddress = bytes.getPosition() - 1;- bytes.reverse(startAddress, thisNodeAddress);+ reverseScratchBytes();+ scratchBytes.writeTo(dataOutput);+ numBytesWritten += scratchBytes.getPosition();+nodeCount++;- return thisNodeAddress;+ return numBytesWritten - 1;}private void writeLabel(DataOutput out, int v) throws IOException {@@ -530,8 +612,7 @@ public class FSTCompiler<T> {return false;}- private void writeNodeForBinarySearch(- FSTCompiler.UnCompiledNode<T> nodeIn, long startAddress, int maxBytesPerArc) {+ private void writeNodeForBinarySearch(FSTCompiler.UnCompiledNode<T> nodeIn, int maxBytesPerArc) {// Build the header in a buffer.// It is a false/special arc which is in fact a node header with node flags followed by node// metadata.@@ -543,11 +624,11 @@ public class FSTCompiler<T> {int headerLen = fixedLengthArcsBuffer.getPosition();// Expand the arcs in place, backwards.- long srcPos = bytes.getPosition();- long destPos = startAddress + headerLen + nodeIn.numArcs * (long) maxBytesPerArc;+ int srcPos = scratchBytes.getPosition();+ int destPos = headerLen + nodeIn.numArcs * maxBytesPerArc;assert destPos >= srcPos;if (destPos > srcPos) {- bytes.setPosition(destPos);+ scratchBytes.setPosition(destPos);for (int arcIdx = nodeIn.numArcs - 1; arcIdx >= 0; arcIdx--) {destPos -= maxBytesPerArc;int arcLen = numBytesPerArc[arcIdx];@@ -566,18 +647,49 @@ public class FSTCompiler<T> {+ arcLen+ " nodeIn.numArcs="+ nodeIn.numArcs;- bytes.copyBytes(srcPos, destPos, arcLen);+ // copy the bytes from srcPos to destPos, essentially expanding the arc from variable+ // length to fixed length+ writeScratchBytes(destPos, scratchBytes.getBytes(), srcPos, arcLen);}}}- // Write the header.- bytes.writeBytes(startAddress, fixedLengthArcsBuffer.getBytes(), 0, headerLen);+ // Finally write the header+ writeScratchBytes(0, fixedLengthArcsBuffer.getBytes(), 0, headerLen);+ }++ /**+ * Reverse the scratch bytes in place. This operation does not affect scratchBytes.getPosition().+ */+ private void reverseScratchBytes() {+ int pos = scratchBytes.getPosition();+ byte[] bytes = scratchBytes.getBytes();+ int limit = pos / 2;+ for (int i = 0; i < limit; i++) {+ byte b = bytes[i];+ bytes[i] = bytes[pos - 1 - i];+ bytes[pos - 1 - i] = b;+ }+ }++ /**+ * Write bytes from a source byte[] to the scratch bytes. The written bytes must fit within what+ * was already written in the scratch bytes.+ *+ * <p>This operation does not affect scratchBytes.getPosition().+ *+ * @param destPos the position in the scratch bytes+ * @param bytes the source byte[]+ * @param offset the offset inside the source byte[]+ * @param length the number of bytes to write+ */+ private void writeScratchBytes(int destPos, byte[] bytes, int offset, int length) {+ assert destPos + length <= scratchBytes.getPosition();+ System.arraycopy(bytes, offset, scratchBytes.getBytes(), destPos, length);}private void writeNodeForDirectAddressingOrContinuous(FSTCompiler.UnCompiledNode<T> nodeIn,- long startAddress,int maxBytesPerArcWithoutLabel,int labelRange,boolean continuous) {@@ -588,7 +700,7 @@ public class FSTCompiler<T> {// the presence bits, and the first label. Keep the first label.int headerMaxLen = 11;int numPresenceBytes = continuous ? 0 : getNumPresenceBytes(labelRange);- long srcPos = bytes.getPosition();+ int srcPos = scratchBytes.getPosition();int totalArcBytes = numLabelBytesPerArc[0] + nodeIn.numArcs * maxBytesPerArcWithoutLabel;int bufferOffset = headerMaxLen + numPresenceBytes + totalArcBytes;byte[] buffer = fixedLengthArcsBuffer.ensureCapacity(bufferOffset).getBytes();@@ -599,16 +711,16 @@ public class FSTCompiler<T> {srcPos -= srcArcLen;int labelLen = numLabelBytesPerArc[arcIdx];// Copy the flags.- bytes.writeTo(srcPos, buffer, bufferOffset, 1);+ scratchBytes.writeTo(srcPos, buffer, bufferOffset, 1);// Skip the label, copy the remaining.int remainingArcLen = srcArcLen - 1 - labelLen;if (remainingArcLen != 0) {- bytes.writeTo(srcPos + 1 + labelLen, buffer, bufferOffset + 1, remainingArcLen);+ scratchBytes.writeTo(srcPos + 1 + labelLen, buffer, bufferOffset + 1, remainingArcLen);}if (arcIdx == 0) {// Copy the label of the first arc only.bufferOffset -= labelLen;- bytes.writeTo(srcPos + 1, buffer, bufferOffset, labelLen);+ scratchBytes.writeTo(srcPos + 1, buffer, bufferOffset, labelLen);}}assert bufferOffset == headerMaxLen + numPresenceBytes;@@ -625,18 +737,18 @@ public class FSTCompiler<T> {int headerLen = fixedLengthArcsBuffer.getPosition();// Write the header.- bytes.setPosition(startAddress);- bytes.writeBytes(fixedLengthArcsBuffer.getBytes(), 0, headerLen);+ scratchBytes.setPosition(0);+ scratchBytes.writeBytes(fixedLengthArcsBuffer.getBytes(), 0, headerLen);// Write the presence bitsif (continuous == false) {writePresenceBits(nodeIn);- assert bytes.getPosition() == startAddress + headerLen + numPresenceBytes;+ assert scratchBytes.getPosition() == headerLen + numPresenceBytes;}// Write the first label and the arcs.- bytes.writeBytes(fixedLengthArcsBuffer.getBytes(), bufferOffset, totalArcBytes);- assert bytes.getPosition() == startAddress + headerLen + numPresenceBytes + totalArcBytes;+ scratchBytes.writeBytes(fixedLengthArcsBuffer.getBytes(), bufferOffset, totalArcBytes);+ assert scratchBytes.getPosition() == headerLen + numPresenceBytes + totalArcBytes;}private void writePresenceBits(FSTCompiler.UnCompiledNode<T> nodeIn) {@@ -648,7 +760,7 @@ public class FSTCompiler<T> {assert label > previousLabel;presenceIndex += label - previousLabel;while (presenceIndex >= Byte.SIZE) {- bytes.writeByte(presenceBits);+ scratchBytes.writeByte(presenceBits);presenceBits = 0;presenceIndex -= Byte.SIZE;}@@ -659,7 +771,7 @@ public class FSTCompiler<T> {assert presenceIndex == (nodeIn.arcs[nodeIn.numArcs - 1].label - nodeIn.arcs[0].label) % 8;assert presenceBits != 0; // The last byte is not 0.assert (presenceBits & (1 << presenceIndex)) != 0; // The last arc is always present.- bytes.writeByte(presenceBits);+ scratchBytes.writeByte(presenceBits);}private void freezeTail(int prefixLenPlus1) throws IOException {@@ -685,11 +797,7 @@ public class FSTCompiler<T> {// this node makes it and we now compile it. first,// compile any targets that were previously// undecided:- parent.replaceLast(- lastInput.intAt(idx - 1),- compileNode(node, 1 + lastInput.length() - idx),- nextFinalOutput,- isFinal);+ parent.replaceLast(lastInput.intAt(idx - 1), compileNode(node), nextFinalOutput, isFinal);}}@@ -810,7 +918,7 @@ public class FSTCompiler<T> {}void finish(long newStartNode) {- assert newStartNode <= bytes.getPosition();+ assert newStartNode <= numBytesWritten;if (fst.metadata.startNode != -1) {throw new IllegalStateException("already finished");}@@ -818,7 +926,11 @@ public class FSTCompiler<T> {newStartNode = 0;}fst.metadata.startNode = newStartNode;- fst.metadata.numBytes = bytes.getPosition();+ fst.metadata.numBytes = numBytesWritten;+ // freeze the dataOutput if applicable+ if (dataOutput instanceof ReadWriteDataOutput) {+ ((ReadWriteDataOutput) dataOutput).freeze();+ }}private boolean validOutput(T output) {@@ -826,6 +938,8 @@ public class FSTCompiler<T> {}/** Returns final FST. NOTE: this will return null if nothing is accepted by the FST. */+ // TODO: make this method to only return the FSTMetadata and user needs to construct the FST+ // themselvespublic FST<T> compile() throws IOException {final UnCompiledNode<T> root = frontier[0];@@ -840,8 +954,7 @@ public class FSTCompiler<T> {// if (DEBUG) System.out.println(" builder.finish root.isFinal=" + root.isFinal + "// root.output=" + root.output);- finish(compileNode(root, lastInput.length()).node);- bytes.finish();+ finish(compileNode(root).node);return fst;}@@ -864,11 +977,15 @@ public class FSTCompiler<T> {}public long fstRamBytesUsed() {- return fst.ramBytesUsed();+ long ramBytesUsed = scratchBytes.ramBytesUsed();+ if (dataOutput instanceof Accountable) {+ ramBytesUsed += ((Accountable) dataOutput).ramBytesUsed();+ }+ return ramBytesUsed;}public long fstSizeInBytes() {- return bytes.getPosition();+ return numBytesWritten;}static final class CompiledNode implements Node {diff --git a/lucene/core/src/java/org/apache/lucene/util/fst/GrowableByteArrayDataOutput.java b/lucene/core/src/java/org/apache/lucene/util/fst/GrowableByteArrayDataOutput.javanew file mode 100644index 00000000000..e6ea871aa06--- /dev/null+++ b/lucene/core/src/java/org/apache/lucene/util/fst/GrowableByteArrayDataOutput.java@@ -0,0 +1,99 @@+/*+ * 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.util.fst;++import java.io.IOException;+import org.apache.lucene.store.DataOutput;+import org.apache.lucene.util.Accountable;+import org.apache.lucene.util.ArrayUtil;+import org.apache.lucene.util.RamUsageEstimator;++// Storing a single contiguous byte[] for the current node of the FST we are writing. The byte[]+// will only grow, never shrink.+// Note: This is only safe for usage that is bounded in the number of bytes written. Do not make+// this public! Public users should instead use ByteBuffersDataOutput+final class GrowableByteArrayDataOutput extends DataOutput implements Accountable {++ private static final long BASE_RAM_BYTES_USED =+ RamUsageEstimator.shallowSizeOfInstance(GrowableByteArrayDataOutput.class);++ private static final int INITIAL_SIZE = 1 << 8;++ // holds an initial size of 256 bytes. this byte array will only grow, but not shrink+ private byte[] bytes = new byte[INITIAL_SIZE];++ private int nextWrite;++ @Override+ public void writeByte(byte b) {+ ensureCapacity(1);+ bytes[nextWrite++] = b;+ }++ @Override+ public void writeBytes(byte[] b, int offset, int len) {+ if (len == 0) {+ return;+ }+ ensureCapacity(len);+ System.arraycopy(b, offset, bytes, nextWrite, len);+ nextWrite += len;+ }++ public int getPosition() {+ return nextWrite;+ }++ public byte[] getBytes() {+ return bytes;+ }++ /** Set the position of the byte[], increasing the capacity if needed */+ public void setPosition(int newLen) {+ assert newLen >= 0;+ if (newLen > nextWrite) {+ ensureCapacity(newLen - nextWrite);+ }+ nextWrite = newLen;+ }++ /**+ * Ensure we can write additional capacityToWrite bytes.+ *+ * @param capacityToWrite the additional bytes to write+ */+ private void ensureCapacity(int capacityToWrite) {+ assert capacityToWrite > 0;+ bytes = ArrayUtil.grow(bytes, nextWrite + capacityToWrite);+ }++ /** Writes all of our bytes to the target {@link DataOutput}. */+ public void writeTo(DataOutput out) throws IOException {+ out.writeBytes(bytes, 0, nextWrite);+ }++ /** Copies bytes from this store to a target byte array. */+ public void writeTo(int srcOffset, byte[] dest, int destOffset, int len) {+ assert srcOffset + len <= nextWrite;+ System.arraycopy(bytes, srcOffset, dest, destOffset, len);+ }++ @Override+ public long ramBytesUsed() {+ return BASE_RAM_BYTES_USED + RamUsageEstimator.sizeOf(bytes);+ }+}diff --git a/lucene/core/src/java/org/apache/lucene/util/fst/NodeHash.java b/lucene/core/src/java/org/apache/lucene/util/fst/NodeHash.javaindex 53640f59ffd..7326fd77f73 100644--- a/lucene/core/src/java/org/apache/lucene/util/fst/NodeHash.java+++ b/lucene/core/src/java/org/apache/lucene/util/fst/NodeHash.java@@ -129,19 +129,18 @@ final class NodeHash<T> {} else {// not in fallback either -- freeze & add the incoming node- long startAddress = fstCompiler.bytes.getPosition();// freeze & addnodeAddress = fstCompiler.addNode(nodeIn);- // TODO: Write the bytes directly from BytesStore// we use 0 as empty marker in hash table, so it better be impossible to get a frozen node// at 0:assert nodeAddress != FST.FINAL_END_NODE && nodeAddress != FST.NON_FINAL_END_NODE;- byte[] buf = new byte[Math.toIntExact(nodeAddress - startAddress + 1)];- fstCompiler.bytes.writeTo(startAddress, buf, 0, buf.length);primaryTable.setNodeAddress(hashSlot, nodeAddress);- primaryTable.copyNodeBytes(hashSlot, buf);+ primaryTable.copyNodeBytes(+ hashSlot,+ fstCompiler.scratchBytes.getBytes(),+ fstCompiler.scratchBytes.getPosition());// confirm frozen hash and unfrozen hash are the sameassert primaryTable.hash(nodeAddress, hashSlot) == hash@@ -300,9 +299,9 @@ final class NodeHash<T> {}/** copy the node bytes from the FST */- void copyNodeBytes(long hashSlot, byte[] bytes) {+ void copyNodeBytes(long hashSlot, byte[] bytes, int length) {assert copiedNodeAddress.get(hashSlot) == 0;- copiedNodes.append(bytes);+ copiedNodes.append(bytes, 0, length);// write the offset, which points to the last byte of the node we copied since we later read// this node in reversecopiedNodeAddress.set(hashSlot, copiedNodes.getPosition() - 1);diff --git a/lucene/core/src/java/org/apache/lucene/util/fst/OnHeapFSTStore.java b/lucene/core/src/java/org/apache/lucene/util/fst/OnHeapFSTStore.javaindex 2113c93f4c3..949babdaa88 100644--- a/lucene/core/src/java/org/apache/lucene/util/fst/OnHeapFSTStore.java+++ b/lucene/core/src/java/org/apache/lucene/util/fst/OnHeapFSTStore.java@@ -16,6 +16,8 @@*/package org.apache.lucene.util.fst;+import static org.apache.lucene.util.fst.FSTCompiler.getOnHeapReaderWriter;+import java.io.IOException;import org.apache.lucene.store.DataInput;import org.apache.lucene.store.DataOutput;@@ -32,10 +34,10 @@ public final class OnHeapFSTStore implements FSTStore {RamUsageEstimator.shallowSizeOfInstance(OnHeapFSTStore.class);/**- * A {@link BytesStore}, used during building, or during reading when the FST is very large (more- * than 1 GB). If the FST is less than 1 GB then bytesArray is set instead.+ * A {@link ReadWriteDataOutput}, used during reading when the FST is very large (more than 1 GB).+ * If the FST is less than 1 GB then bytesArray is set instead.*/- private BytesStore bytes;+ private ReadWriteDataOutput dataOutput;/** Used at read time when the FST fits into a single byte[]. */private byte[] bytesArray;@@ -54,8 +56,9 @@ public final class OnHeapFSTStore implements FSTStore {public FSTStore init(DataInput in, long numBytes) throws IOException {if (numBytes > 1 << this.maxBlockBits) {// FST is big: we need multiple pages- bytes = new BytesStore(this.maxBlockBits);- bytes.copyBytes(in, numBytes);+ dataOutput = (ReadWriteDataOutput) getOnHeapReaderWriter(maxBlockBits);+ dataOutput.copyBytes(in, numBytes);+ dataOutput.freeze();} else {// FST fits into a single block: use ByteArrayBytesStoreReader for less overheadbytesArray = new byte[(int) numBytes];@@ -70,7 +73,7 @@ public final class OnHeapFSTStore implements FSTStore {if (bytesArray != null) {size += bytesArray.length;} else {- size += bytes.ramBytesUsed();+ size += dataOutput.ramBytesUsed();}return size;}@@ -80,14 +83,14 @@ public final class OnHeapFSTStore implements FSTStore {if (bytesArray != null) {return new ReverseBytesReader(bytesArray);} else {- return bytes.getReverseBytesReader();+ return dataOutput.getReverseBytesReader();}}@Overridepublic void writeTo(DataOutput out) throws IOException {- if (bytes != null) {- bytes.writeTo(out);+ if (dataOutput != null) {+ dataOutput.writeTo(out);} else {assert bytesArray != null;out.writeBytes(bytesArray, 0, bytesArray.length);diff --git a/lucene/core/src/java/org/apache/lucene/util/fst/ReadWriteDataOutput.java b/lucene/core/src/java/org/apache/lucene/util/fst/ReadWriteDataOutput.javanew file mode 100644index 00000000000..f5792779d00--- /dev/null+++ b/lucene/core/src/java/org/apache/lucene/util/fst/ReadWriteDataOutput.java@@ -0,0 +1,73 @@+/*+ * 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.util.fst;++import java.io.IOException;+import org.apache.lucene.store.ByteBuffersDataInput;+import org.apache.lucene.store.ByteBuffersDataOutput;+import org.apache.lucene.store.DataOutput;++/**+ * An adapter class to use {@link ByteBuffersDataOutput} as a {@link FSTReader}. It allows the FST+ * to be readable immediately after writing+ */+final class ReadWriteDataOutput extends DataOutput implements FSTReader {++ private final ByteBuffersDataOutput dataOutput;+ // the DataInput to read from once we finish writing+ private ByteBuffersDataInput dataInput;+ // whether this DataOutput is already frozen+ private boolean frozen;++ public ReadWriteDataOutput(ByteBuffersDataOutput dataOutput) {+ this.dataOutput = dataOutput;+ }++ @Override+ public void writeByte(byte b) {+ assert frozen == false;+ dataOutput.writeByte(b);+ }++ @Override+ public void writeBytes(byte[] b, int offset, int length) {+ assert frozen == false;+ dataOutput.writeBytes(b, offset, length);+ }++ @Override+ public long ramBytesUsed() {+ return dataOutput.ramBytesUsed();+ }++ public void freeze() {+ frozen = true;+ // this operation are costly, so we want to compute it once and cache+ dataInput = dataOutput.toDataInput();+ }++ @Override+ public FST.BytesReader getReverseBytesReader() {+ assert dataInput != null; // freeze() must be called first+ return new ReverseRandomAccessReader(dataInput);+ }++ @Override+ public void writeTo(DataOutput out) throws IOException {+ dataOutput.copyTo(out);+ }+}diff --git a/lucene/core/src/test/org/apache/lucene/util/fst/Test2BFST.java b/lucene/core/src/test/org/apache/lucene/util/fst/Test2BFST.javaindex 2e0aefbc06d..b2758ca526e 100644--- a/lucene/core/src/test/org/apache/lucene/util/fst/Test2BFST.java+++ b/lucene/core/src/test/org/apache/lucene/util/fst/Test2BFST.java@@ -31,9 +31,6 @@ import org.apache.lucene.util.BytesRef;import org.apache.lucene.util.IntsRef;import org.junit.Ignore;-// TODO: soon we will be able to run this test with small heaps! Once #12633 and #12543-// are done-//// Run something like this:// ./gradlew test --tests Test2BFST -Dtests.heapsize=32g -Dtests.verbose=true --max-workers=1diff --git a/lucene/core/src/test/org/apache/lucene/util/fst/Test2BFSTOffHeap.java b/lucene/core/src/test/org/apache/lucene/util/fst/Test2BFSTOffHeap.javanew file mode 100644index 00000000000..090c99716f6--- /dev/null+++ b/lucene/core/src/test/org/apache/lucene/util/fst/Test2BFSTOffHeap.java@@ -0,0 +1,342 @@+/*+ * 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.util.fst;++import com.carrotsearch.randomizedtesting.annotations.TimeoutSuite;+import java.util.Arrays;+import java.util.Random;+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.store.MMapDirectory;+import org.apache.lucene.tests.util.LuceneTestCase;+import org.apache.lucene.tests.util.LuceneTestCase.SuppressSysoutChecks;+import org.apache.lucene.tests.util.TimeUnits;+import org.apache.lucene.util.BytesRef;+import org.apache.lucene.util.IntsRef;+import org.junit.Ignore;++// Similar to Test2BFST but will build and read the FST off-heap and can be run with small heap++// Run something like this:+// ./gradlew test --tests Test2BFSTOffHeap -Dtests.verbose=true --max-workers=1++@Ignore("Will take long time to run (~4.5 hours)")+@SuppressSysoutChecks(bugUrl = "test prints helpful progress reports with time")+@TimeoutSuite(millis = 100 * TimeUnits.HOUR)+public class Test2BFSTOffHeap extends LuceneTestCase {++ private static long LIMIT = 3L * 1024 * 1024 * 1024;++ public void test() throws Exception {+ assumeWorkingMMapOnWindows();++ int[] ints = new int[7];+ IntsRef input = new IntsRef(ints, 0, ints.length);+ long seed = random().nextLong();++ Directory dir = new MMapDirectory(createTempDir("2BFSTOffHeap"));++ // Build FST w/ NoOutputs and stop when nodeCount > 2.2B+ {+ System.out.println("\nTEST: ~2.2B nodes; output=NO_OUTPUTS");+ Outputs<Object> outputs = NoOutputs.getSingleton();+ Object NO_OUTPUT = outputs.getNoOutput();+ IndexOutput indexOutput = dir.createOutput("fst", IOContext.DEFAULT);+ final FSTCompiler<Object> fstCompiler =+ new FSTCompiler.Builder<>(FST.INPUT_TYPE.BYTE1, outputs).dataOutput(indexOutput).build();++ int count = 0;+ Random r = new Random(seed);+ int[] ints2 = new int[200];+ IntsRef input2 = new IntsRef(ints2, 0, ints2.length);+ long startTime = System.nanoTime();+ while (true) {+ // System.out.println("add: " + input + " -> " + output);+ for (int i = 10; i < ints2.length; i++) {+ ints2[i] = r.nextInt(256);+ }+ fstCompiler.add(input2, NO_OUTPUT);+ count++;+ if (count % 100000 == 0) {+ System.out.println(+ count+ + ": "+ + fstCompiler.fstRamBytesUsed()+ + " RAM bytes used; "+ + fstCompiler.fstSizeInBytes()+ + " FST bytes; "+ + fstCompiler.getNodeCount()+ + " nodes; took "+ + (long) ((System.nanoTime() - startTime) / 1e9)+ + " seconds");+ }+ if (fstCompiler.getNodeCount() > Integer.MAX_VALUE + 100L * 1024 * 1024) {+ break;+ }+ nextInput(r, ints2);+ }++ FST<Object> fst = fstCompiler.compile();+ indexOutput.close();+ try (IndexInput indexInput = dir.openInput("fst", IOContext.DEFAULT)) {+ fst = new FST<>(fst.getMetadata(), indexInput, new OffHeapFSTStore());++ for (int verify = 0; verify < 2; verify++) {+ System.out.println(+ "\nTEST: now verify [fst size="+ + fst.numBytes()+ + "; nodeCount="+ + fstCompiler.getNodeCount()+ + "; arcCount="+ + fstCompiler.getArcCount()+ + "]");++ Arrays.fill(ints2, 0);+ r = new Random(seed);++ startTime = System.nanoTime();+ for (int i = 0; i < count; i++) {+ if (i % 1000000 == 0) {+ System.out.println(+ i + "...: took " + (long) ((System.nanoTime() - startTime) / 1e9) + " seconds");+ }+ for (int j = 10; j < ints2.length; j++) {+ ints2[j] = r.nextInt(256);+ }+ assertEquals(NO_OUTPUT, Util.get(fst, input2));+ nextInput(r, ints2);+ }++ System.out.println("\nTEST: enum all input/outputs");+ IntsRefFSTEnum<Object> fstEnum = new IntsRefFSTEnum<>(fst);++ Arrays.fill(ints2, 0);+ r = new Random(seed);+ int upto = 0;+ while (true) {+ IntsRefFSTEnum.InputOutput<Object> pair = fstEnum.next();+ if (pair == null) {+ break;+ }+ for (int j = 10; j < ints2.length; j++) {+ ints2[j] = r.nextInt(256);+ }+ assertEquals(input2, pair.input);+ assertEquals(NO_OUTPUT, pair.output);+ upto++;+ nextInput(r, ints2);+ }+ assertEquals(count, upto);+ }+ } finally {+ dir.deleteFile("fst");+ }+ }++ // Build FST w/ ByteSequenceOutputs and stop when FST+ // size = 3GB+ {+ System.out.println("\nTEST: 3 GB size; outputs=bytes");+ IndexOutput indexOutput = dir.createOutput("fst", IOContext.DEFAULT);+ Outputs<BytesRef> outputs = ByteSequenceOutputs.getSingleton();+ final FSTCompiler<BytesRef> fstCompiler =+ new FSTCompiler.Builder<>(FST.INPUT_TYPE.BYTE1, outputs).dataOutput(indexOutput).build();++ byte[] outputBytes = new byte[20];+ BytesRef output = new BytesRef(outputBytes);+ Arrays.fill(ints, 0);+ int count = 0;+ Random r = new Random(seed);+ while (true) {+ r.nextBytes(outputBytes);+ // System.out.println("add: " + input + " -> " + output);+ fstCompiler.add(input, BytesRef.deepCopyOf(output));+ count++;+ if (count % 10000 == 0) {+ long size = fstCompiler.fstSizeInBytes();+ if (count % 1000000 == 0) {+ System.out.println(count + "...: " + size + " bytes");+ }+ if (size > LIMIT) {+ break;+ }+ }+ nextInput(r, ints);+ }++ FST<BytesRef> fst = fstCompiler.compile();+ indexOutput.close();+ try (IndexInput indexInput = dir.openInput("fst", IOContext.DEFAULT)) {+ fst = new FST<>(fst.getMetadata(), indexInput, new OffHeapFSTStore());+ for (int verify = 0; verify < 2; verify++) {++ System.out.println(+ "\nTEST: now verify [fst size="+ + fst.numBytes()+ + "; nodeCount="+ + fstCompiler.getNodeCount()+ + "; arcCount="+ + fstCompiler.getArcCount()+ + "]");++ r = new Random(seed);+ Arrays.fill(ints, 0);++ long startTime = System.nanoTime();++ for (int i = 0; i < count; i++) {+ if (i % 1000000 == 0) {+ System.out.println(+ i + "...: took " + (long) ((System.nanoTime() - startTime) / 1e9) + " seconds");+ }+ r.nextBytes(outputBytes);+ assertEquals(output, Util.get(fst, input));+ nextInput(r, ints);+ }++ System.out.println("\nTEST: enum all input/outputs");+ IntsRefFSTEnum<BytesRef> fstEnum = new IntsRefFSTEnum<>(fst);++ Arrays.fill(ints, 0);+ r = new Random(seed);+ int upto = 0;+ while (true) {+ IntsRefFSTEnum.InputOutput<BytesRef> pair = fstEnum.next();+ if (pair == null) {+ break;+ }+ assertEquals(input, pair.input);+ r.nextBytes(outputBytes);+ assertEquals(output, pair.output);+ upto++;+ nextInput(r, ints);+ }+ assertEquals(count, upto);+ }+ } finally {+ dir.deleteFile("fst");+ }+ }++ // Build FST w/ PositiveIntOutputs and stop when FST+ // size = 3GB+ {+ IndexOutput indexOutput = dir.createOutput("fst", IOContext.DEFAULT);+ System.out.println("\nTEST: 3 GB size; outputs=long");+ Outputs<Long> outputs = PositiveIntOutputs.getSingleton();+ final FSTCompiler<Long> fstCompiler =+ new FSTCompiler.Builder<>(FST.INPUT_TYPE.BYTE1, outputs).dataOutput(indexOutput).build();++ long output = 1;++ Arrays.fill(ints, 0);+ int count = 0;+ Random r = new Random(seed);+ while (true) {+ // System.out.println("add: " + input + " -> " + output);+ fstCompiler.add(input, output);+ output += 1 + r.nextInt(10);+ count++;+ if (count % 10000 == 0) {+ long size = fstCompiler.fstSizeInBytes();+ if (count % 1000000 == 0) {+ System.out.println(count + "...: " + size + " bytes");+ }+ if (size > LIMIT) {+ break;+ }+ }+ nextInput(r, ints);+ }++ FST<Long> fst = fstCompiler.compile();+ indexOutput.close();+ try (IndexInput indexInput = dir.openInput("fst", IOContext.DEFAULT)) {+ fst = new FST<>(fst.getMetadata(), indexInput, new OffHeapFSTStore());++ for (int verify = 0; verify < 2; verify++) {++ System.out.println(+ "\nTEST: now verify [fst size="+ + fst.numBytes()+ + "; nodeCount="+ + fstCompiler.getNodeCount()+ + "; arcCount="+ + fstCompiler.getArcCount()+ + "]");++ Arrays.fill(ints, 0);++ output = 1;+ r = new Random(seed);+ long startTime = System.nanoTime();+ for (int i = 0; i < count; i++) {+ if (i % 1000000 == 0) {+ System.out.println(+ i + "...: took " + (long) ((System.nanoTime() - startTime) / 1e9) + " seconds");+ }++ assertEquals(output, Util.get(fst, input).longValue());++ output += 1 + r.nextInt(10);+ nextInput(r, ints);+ }++ System.out.println("\nTEST: enum all input/outputs");+ IntsRefFSTEnum<Long> fstEnum = new IntsRefFSTEnum<>(fst);++ Arrays.fill(ints, 0);+ r = new Random(seed);+ int upto = 0;+ output = 1;+ while (true) {+ IntsRefFSTEnum.InputOutput<Long> pair = fstEnum.next();+ if (pair == null) {+ break;+ }+ assertEquals(input, pair.input);+ assertEquals(output, pair.output.longValue());+ output += 1 + r.nextInt(10);+ upto++;+ nextInput(r, ints);+ }+ assertEquals(count, upto);+ }+ } finally {+ dir.deleteFile("fst");+ }+ }+ dir.close();+ }++ private void nextInput(Random r, int[] ints) {+ int downTo = 6;+ while (downTo >= 0) {+ // Must add random amounts (and not just 1) because+ // otherwise FST outsmarts us and remains tiny:+ ints[downTo] += 1 + r.nextInt(10);+ if (ints[downTo] < 256) {+ break;+ } else {+ ints[downTo] = 0;+ downTo--;+ }+ }+ }+}diff --git a/lucene/core/src/test/org/apache/lucene/util/fst/TestBytesStore.java b/lucene/core/src/test/org/apache/lucene/util/fst/TestBytesStore.javadeleted file mode 100644index b550fe81fa9..00000000000--- a/lucene/core/src/test/org/apache/lucene/util/fst/TestBytesStore.java+++ /dev/null@@ -1,362 +0,0 @@-/*- * 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.util.fst;--import java.io.IOException;-import java.util.Arrays;-import org.apache.lucene.store.ByteArrayDataInput;-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.tests.util.LuceneTestCase;-import org.apache.lucene.tests.util.TestUtil;-import org.apache.lucene.util.ArrayUtil;--public class TestBytesStore extends LuceneTestCase {-- public void testRandom() throws Exception {-- final int iters = atLeast(10);- final int maxBytes = TEST_NIGHTLY ? 200000 : 20000;- for (int iter = 0; iter < iters; iter++) {- final int numBytes = TestUtil.nextInt(random(), 1, maxBytes);- final byte[] expected = new byte[numBytes];- final int blockBits = TestUtil.nextInt(random(), 8, 15);- final BytesStore bytes = new BytesStore(blockBits);- if (VERBOSE) {- System.out.println(- "TEST: iter=" + iter + " numBytes=" + numBytes + " blockBits=" + blockBits);- }-- int pos = 0;- while (pos < numBytes) {- int op = random().nextInt(6);- if (VERBOSE) {- System.out.println(" cycle pos=" + pos);- }- switch (op) {- case 0:- {- // write random byte- byte b = (byte) random().nextInt(256);- if (VERBOSE) {- System.out.println(" writeByte b=" + b);- }-- expected[pos++] = b;- bytes.writeByte(b);- }- break;-- case 1:- {- // write random byte[]- int len = random().nextInt(Math.min(numBytes - pos, 100));- byte[] temp = new byte[len];- random().nextBytes(temp);- if (VERBOSE) {- System.out.println(" writeBytes len=" + len + " bytes=" + Arrays.toString(temp));- }- System.arraycopy(temp, 0, expected, pos, temp.length);- bytes.writeBytes(temp, 0, temp.length);- pos += len;- }- break;-- case 2:- {- // reverse bytes- if (pos > 1) {- int len = TestUtil.nextInt(random(), 2, Math.min(100, pos));- int start;- if (len == pos) {- start = 0;- } else {- start = random().nextInt(pos - len);- }- int end = start + len - 1;- if (VERBOSE) {- System.out.println(- " reverse start=" + start + " end=" + end + " len=" + len + " pos=" + pos);- }- bytes.reverse(start, end);-- while (start <= end) {- byte b = expected[end];- expected[end] = expected[start];- expected[start] = b;- start++;- end--;- }- }- }- break;-- case 3:- {- // abs write random byte[]- if (pos > 2) {- int randomPos = random().nextInt(pos - 1);- int len = TestUtil.nextInt(random(), 1, Math.min(pos - randomPos - 1, 100));- byte[] temp = new byte[len];- random().nextBytes(temp);- if (VERBOSE) {- System.out.println(- " abs writeBytes pos="- + randomPos- + " len="- + len- + " bytes="- + Arrays.toString(temp));- }- System.arraycopy(temp, 0, expected, randomPos, temp.length);- bytes.writeBytes(randomPos, temp, 0, temp.length);- }- }- break;-- case 4:- {- // copyBytes- if (pos > 1) {- int src = random().nextInt(pos - 1);- int dest = TestUtil.nextInt(random(), src + 1, pos - 1);- int len = TestUtil.nextInt(random(), 1, Math.min(300, pos - dest));- if (VERBOSE) {- System.out.println(" copyBytes src=" + src + " dest=" + dest + " len=" + len);- }- System.arraycopy(expected, src, expected, dest, len);- bytes.copyBytes(src, dest, len);- }- }- break;-- case 5:- {- // skip- int len = random().nextInt(Math.min(100, numBytes - pos));-- if (VERBOSE) {- System.out.println(" skip len=" + len);- }-- pos += len;- bytes.setPosition(pos);-- // NOTE: must fill in zeros in case truncate was- // used, else we get false fails:- if (len > 0) {- byte[] zeros = new byte[len];- bytes.writeBytes(pos - len, zeros, 0, len);- }- }- break;- }-- assertEquals(pos, bytes.getPosition());-- if (pos > 0 && random().nextInt(50) == 17) {- // truncate- int len = TestUtil.nextInt(random(), 1, Math.min(pos, 100));- bytes.setPosition(pos - len);- pos -= len;- Arrays.fill(expected, pos, pos + len, (byte) 0);- if (VERBOSE) {- System.out.println(" truncate len=" + len + " newPos=" + pos);- }- }-- if ((pos > 0 && random().nextInt(200) == 17)) {- verify(bytes, expected, pos);- }- }-- BytesStore bytesToVerify;-- if (random().nextBoolean()) {- if (VERBOSE) {- System.out.println("TEST: save/load final bytes");- }- Directory dir = newDirectory();- IndexOutput out = dir.createOutput("bytes", IOContext.DEFAULT);- bytes.writeTo(out);- out.close();- IndexInput in = dir.openInput("bytes", IOContext.DEFAULT);- bytesToVerify = new BytesStore(TestUtil.nextInt(random(), 8, 20));- bytesToVerify.copyBytes(in, numBytes);- in.close();- dir.close();- } else {- bytesToVerify = bytes;- }-- verify(bytesToVerify, expected, numBytes);- }- }-- public void testCopyBytesOnByteStore() throws IOException {- byte[] bytes = new byte[1024 * 8 + 10];- byte[] bytesout = new byte[bytes.length];- random().nextBytes(bytes);- int offset = TestUtil.nextInt(random(), 0, 100);- int len = bytes.length - offset;- ByteArrayDataInput in = new ByteArrayDataInput(bytes, offset, len);- final int blockBits = TestUtil.nextInt(random(), 8, 15);- final BytesStore o = new BytesStore(blockBits);- o.copyBytes(in, len);- o.writeTo(0, bytesout, 0, len);- assertArrayEquals(- ArrayUtil.copyOfSubArray(bytesout, 0, len),- ArrayUtil.copyOfSubArray(bytes, offset, offset + len));- }-- private void verify(BytesStore bytes, byte[] expected, int totalLength) throws Exception {- assertEquals(totalLength, bytes.getPosition());- if (totalLength == 0) {- return;- }- if (VERBOSE) {- System.out.println(" verify...");- }-- // First verify whole thing in one blast:- byte[] actual = new byte[totalLength];- if (random().nextBoolean()) {- if (VERBOSE) {- System.out.println(" bulk: reversed");- }- // reversed- FST.BytesReader r = bytes.getReverseBytesReader();- r.setPosition(totalLength - 1);- r.readBytes(actual, 0, actual.length);- int start = 0;- int end = totalLength - 1;- while (start < end) {- byte b = actual[start];- actual[start] = actual[end];- actual[end] = b;- start++;- end--;- }- } else {- // forward- if (VERBOSE) {- System.out.println(" bulk: forward");- }- FST.BytesReader r = bytes.getForwardReader();- r.readBytes(actual, 0, actual.length);- }-- for (int i = 0; i < totalLength; i++) {- assertEquals("byte @ index=" + i, expected[i], actual[i]);- }-- FST.BytesReader r;-- // Then verify ops:- boolean reversed = random().nextBoolean();- if (reversed) {- if (VERBOSE) {- System.out.println(" ops: reversed");- }- r = bytes.getReverseBytesReader();- } else {- if (VERBOSE) {- System.out.println(" ops: forward");- }- r = bytes.getForwardReader();- }-- if (totalLength > 1) {- int numOps = TestUtil.nextInt(random(), 100, 200);- for (int op = 0; op < numOps; op++) {-- int numBytes = random().nextInt(Math.min(1000, totalLength - 1));- int pos;- if (reversed) {- pos = TestUtil.nextInt(random(), numBytes, totalLength - 1);- } else {- pos = random().nextInt(totalLength - numBytes);- }- if (VERBOSE) {- System.out.println(- " op iter="- + op- + " reversed="- + reversed- + " numBytes="- + numBytes- + " pos="- + pos);- }- byte[] temp = new byte[numBytes];- r.setPosition(pos);- assertEquals(pos, r.getPosition());- r.readBytes(temp, 0, temp.length);- for (int i = 0; i < numBytes; i++) {- byte expectedByte;- if (reversed) {- expectedByte = expected[pos - i];- } else {- expectedByte = expected[pos + i];- }- assertEquals("byte @ index=" + i, expectedByte, temp[i]);- }-- int left;- int expectedPos;-- if (reversed) {- expectedPos = pos - numBytes;- left = (int) r.getPosition();- } else {- expectedPos = pos + numBytes;- left = (int) (totalLength - r.getPosition());- }- assertEquals(expectedPos, r.getPosition());-- if (left > 4) {- int skipBytes = random().nextInt(left - 4);-- int expectedInt = 0;- if (reversed) {- expectedPos -= skipBytes;- expectedInt |= (expected[expectedPos--] & 0xFF);- expectedInt |= (expected[expectedPos--] & 0xFF) << 8;- expectedInt |= (expected[expectedPos--] & 0xFF) << 16;- expectedInt |= (expected[expectedPos--] & 0xFF) << 24;- } else {- expectedPos += skipBytes;- expectedInt |= (expected[expectedPos++] & 0xFF);- expectedInt |= (expected[expectedPos++] & 0xFF) << 8;- expectedInt |= (expected[expectedPos++] & 0xFF) << 16;- expectedInt |= (expected[expectedPos++] & 0xFF) << 24;- }-- if (VERBOSE) {- System.out.println(" skip numBytes=" + skipBytes);- System.out.println(" readInt");- }-- r.skipBytes(skipBytes);- assertEquals(expectedInt, r.readInt());- }- }- }- }-}diff --git a/lucene/core/src/test/org/apache/lucene/util/fst/TestFSTDirectAddressing.java b/lucene/core/src/test/org/apache/lucene/util/fst/TestFSTDirectAddressing.javaindex d988506eca1..0f064d1ea44 100644--- a/lucene/core/src/test/org/apache/lucene/util/fst/TestFSTDirectAddressing.java+++ b/lucene/core/src/test/org/apache/lucene/util/fst/TestFSTDirectAddressing.java@@ -67,7 +67,7 @@ public class TestFSTDirectAddressing extends LuceneTestCase {}entries.add(new BytesRef(b));}- long size = buildFST(entries).ramBytesUsed();+ long size = buildFST(entries).numBytes();// Size is 1648 when we use only list-encoding. We were previously failing to ever de-dup// direct addressing, which led this case to blow up.// This test will fail if there is more than 1% size increase with direct addressing.diff --git a/lucene/core/src/test/org/apache/lucene/util/fst/TestGrowableByteArrayDataOutput.java b/lucene/core/src/test/org/apache/lucene/util/fst/TestGrowableByteArrayDataOutput.javanew file mode 100644index 00000000000..0d271cc49e9--- /dev/null+++ b/lucene/core/src/test/org/apache/lucene/util/fst/TestGrowableByteArrayDataOutput.java@@ -0,0 +1,159 @@+/*+ * 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.util.fst;++import java.io.ByteArrayOutputStream;+import java.io.IOException;+import java.util.Arrays;+import org.apache.lucene.store.ByteArrayDataInput;+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.store.OutputStreamDataOutput;+import org.apache.lucene.tests.util.LuceneTestCase;+import org.apache.lucene.tests.util.TestUtil;+import org.apache.lucene.util.ArrayUtil;++public class TestGrowableByteArrayDataOutput extends LuceneTestCase {++ public void testRandom() throws Exception {++ final int iters = atLeast(10);+ final int maxBytes = TEST_NIGHTLY ? 200000 : 20000;+ for (int iter = 0; iter < iters; iter++) {+ final int numBytes = TestUtil.nextInt(random(), 1, maxBytes);+ final byte[] expected = new byte[numBytes];+ final GrowableByteArrayDataOutput bytes = new GrowableByteArrayDataOutput();+ if (VERBOSE) {+ System.out.println("TEST: iter=" + iter + " numBytes=" + numBytes);+ }++ int pos = 0;+ while (pos < numBytes) {+ int op = random().nextInt(2);+ if (VERBOSE) {+ System.out.println(" cycle pos=" + pos);+ }+ switch (op) {+ case 0:+ {+ // write random byte+ byte b = (byte) random().nextInt(256);+ if (VERBOSE) {+ System.out.println(" writeByte b=" + b);+ }++ expected[pos++] = b;+ bytes.writeByte(b);+ }+ break;++ case 1:+ {+ // write random byte[]+ int len = random().nextInt(Math.min(numBytes - pos, 100));+ byte[] temp = new byte[len];+ random().nextBytes(temp);+ if (VERBOSE) {+ System.out.println(" writeBytes len=" + len + " bytes=" + Arrays.toString(temp));+ }+ System.arraycopy(temp, 0, expected, pos, temp.length);+ bytes.writeBytes(temp, 0, temp.length);+ pos += len;+ }+ break;+ }++ assertEquals(pos, bytes.getPosition());++ if (pos > 0 && random().nextInt(50) == 17) {+ // truncate+ int len = TestUtil.nextInt(random(), 1, Math.min(pos, 100));+ bytes.setPosition(pos - len);+ pos -= len;+ Arrays.fill(expected, pos, pos + len, (byte) 0);+ if (VERBOSE) {+ System.out.println(" truncate len=" + len + " newPos=" + pos);+ }+ }++ if ((pos > 0 && random().nextInt(200) == 17)) {+ verify(bytes, expected, pos);+ }+ }++ GrowableByteArrayDataOutput bytesToVerify;++ if (random().nextBoolean()) {+ if (VERBOSE) {+ System.out.println("TEST: save/load final bytes");+ }+ Directory dir = newDirectory();+ IndexOutput out = dir.createOutput("bytes", IOContext.DEFAULT);+ bytes.writeTo(out);+ out.close();+ IndexInput in = dir.openInput("bytes", IOContext.DEFAULT);+ bytesToVerify = new GrowableByteArrayDataOutput();+ bytesToVerify.copyBytes(in, numBytes);+ in.close();+ dir.close();+ } else {+ bytesToVerify = bytes;+ }++ verify(bytesToVerify, expected, numBytes);+ }+ }++ public void testCopyBytesOnByteStore() throws IOException {+ byte[] bytes = new byte[1024 * 8 + 10];+ byte[] bytesout = new byte[bytes.length];+ random().nextBytes(bytes);+ int offset = TestUtil.nextInt(random(), 0, 100);+ int len = bytes.length - offset;+ ByteArrayDataInput in = new ByteArrayDataInput(bytes, offset, len);+ final GrowableByteArrayDataOutput o = new GrowableByteArrayDataOutput();+ o.copyBytes(in, len);+ o.writeTo(0, bytesout, 0, len);+ assertArrayEquals(+ ArrayUtil.copyOfSubArray(bytesout, 0, len),+ ArrayUtil.copyOfSubArray(bytes, offset, offset + len));+ }++ private void verify(GrowableByteArrayDataOutput bytes, byte[] expected, int totalLength)+ throws Exception {+ assertEquals(totalLength, bytes.getPosition());+ if (totalLength == 0) {+ return;+ }+ if (VERBOSE) {+ System.out.println(" verify...");+ }++ // First verify whole thing in one blast:+ ByteArrayOutputStream baos = new ByteArrayOutputStream();+ bytes.writeTo(new OutputStreamDataOutput(baos));+ byte[] actual = baos.toByteArray();++ assertEquals(totalLength, actual.length);++ for (int i = 0; i < totalLength; i++) {+ assertEquals("byte @ index=" + i, expected[i], actual[i]);+ }+ }+}diff --git a/lucene/core/src/test/org/apache/lucene/util/fst/TestNodeHash.java b/lucene/core/src/test/org/apache/lucene/util/fst/TestNodeHash.javaindex 4c9b531279a..8319f20efea 100644--- a/lucene/core/src/test/org/apache/lucene/util/fst/TestNodeHash.java+++ b/lucene/core/src/test/org/apache/lucene/util/fst/TestNodeHash.java@@ -30,7 +30,7 @@ public class TestNodeHash extends LuceneTestCase {int nodeLength = atLeast(500);long fallbackHashSlot = 1;byte[] fallbackBytes = RandomBytes.randomBytesOfLength(random(), nodeLength);- fallbackHashTable.copyNodeBytes(fallbackHashSlot, fallbackBytes);+ fallbackHashTable.copyNodeBytes(fallbackHashSlot, fallbackBytes, nodeLength);// check if the bytes we wrote are the same as the original bytesbyte[] storedBytes = fallbackHashTable.getBytes(fallbackHashSlot, nodeLength);diff --git a/lucene/test-framework/src/java/org/apache/lucene/tests/util/fst/FSTTester.java b/lucene/test-framework/src/java/org/apache/lucene/tests/util/fst/FSTTester.javaindex 82a80055be3..d80cbf58dc4 100644--- a/lucene/test-framework/src/java/org/apache/lucene/tests/util/fst/FSTTester.java+++ b/lucene/test-framework/src/java/org/apache/lucene/tests/util/fst/FSTTester.java@@ -255,10 +255,19 @@ public class FSTTester<T> {public FST<T> doTest() throws IOException {- final FSTCompiler<T> fstCompiler =+ final FSTCompiler.Builder<T> fstCompilerBuilder =new FSTCompiler.Builder<>(- inputMode == 0 ? FST.INPUT_TYPE.BYTE1 : FST.INPUT_TYPE.BYTE4, outputs)- .build();+ inputMode == 0 ? FST.INPUT_TYPE.BYTE1 : FST.INPUT_TYPE.BYTE4, outputs);++ IndexOutput indexOutput = null;+ boolean useOffHeap = random.nextBoolean();++ if (useOffHeap) {+ indexOutput = dir.createOutput("fstOffHeap.bin", IOContext.DEFAULT);+ fstCompilerBuilder.dataOutput(indexOutput);+ }++ final FSTCompiler<T> fstCompiler = fstCompilerBuilder.build();for (InputOutput<T> pair : pairs) {if (pair.output instanceof List) {@@ -274,8 +283,16 @@ public class FSTTester<T> {}}FST<T> fst = fstCompiler.compile();+ ;- if (random.nextBoolean() && fst != null) {+ if (useOffHeap) {+ indexOutput.close();+ try (IndexInput in = dir.openInput("fstOffHeap.bin", IOContext.DEFAULT)) {+ fst = new FST<>(fst.getMetadata(), in);+ } finally {+ dir.deleteFile("fstOffHeap.bin");+ }+ } else if (random.nextBoolean() && fst != null) {IOContext context = LuceneTestCase.newIOContext(random);try (IndexOutput out = dir.createOutput("fst.bin", context)) {fst.save(out, out);