Skip to content

armgit / solr

Public Imported from GitHub
0

Apache Solr open-source search software

LUCENE-5864: Split BytesRef into BytesRef and BytesRefBuilder.

Adrien Grand94d1b7f5a648
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txt
index 84e8be930c1..27ce552a954 100644
--- a/lucene/CHANGES.txt
+++ b/lucene/CHANGES.txt
@@ -164,6 +164,10 @@ API Changes
* LUCENE-5850: CheckIndex now prints the Lucene version used to write
each segment. (Robert Muir, Mike McCandless)
+* LUCENE-5836: BytesRef has been splitted into BytesRef, whose intended usage is
+ to be just a reference to a section of a larger byte[] and BytesRefBuilder
+ which is a StringBuilder-like class for BytesRef instances. (Adrien Grand)
+
Optimizations
* LUCENE-5780: Make OrdinalMap more memory-efficient, especially in case the
diff --git a/lucene/analysis/common/src/java/org/apache/lucene/analysis/charfilter/NormalizeCharMap.java b/lucene/analysis/common/src/java/org/apache/lucene/analysis/charfilter/NormalizeCharMap.java
index 499fdf0808a..ca2c7780e88 100644
--- a/lucene/analysis/common/src/java/org/apache/lucene/analysis/charfilter/NormalizeCharMap.java
+++ b/lucene/analysis/common/src/java/org/apache/lucene/analysis/charfilter/NormalizeCharMap.java
@@ -24,6 +24,7 @@ import java.util.TreeMap;
import org.apache.lucene.util.CharsRef;
import org.apache.lucene.util.IntsRef;
+import org.apache.lucene.util.IntsRefBuilder;
import org.apache.lucene.util.fst.Builder;
import org.apache.lucene.util.fst.CharSequenceOutputs;
import org.apache.lucene.util.fst.FST;
@@ -109,7 +110,7 @@ public class NormalizeCharMap {
try {
final Outputs<CharsRef> outputs = CharSequenceOutputs.getSingleton();
final org.apache.lucene.util.fst.Builder<CharsRef> builder = new org.apache.lucene.util.fst.Builder<>(FST.INPUT_TYPE.BYTE2, outputs);
- final IntsRef scratch = new IntsRef();
+ final IntsRefBuilder scratch = new IntsRefBuilder();
for(Map.Entry<String,String> ent : pendingPairs.entrySet()) {
builder.add(Util.toUTF16(ent.getKey(), scratch),
new CharsRef(ent.getValue()));
diff --git a/lucene/analysis/common/src/java/org/apache/lucene/analysis/hunspell/Dictionary.java b/lucene/analysis/common/src/java/org/apache/lucene/analysis/hunspell/Dictionary.java
index 1adcb2ac5f4..06086baf20a 100644
--- a/lucene/analysis/common/src/java/org/apache/lucene/analysis/hunspell/Dictionary.java
+++ b/lucene/analysis/common/src/java/org/apache/lucene/analysis/hunspell/Dictionary.java
@@ -20,10 +20,12 @@ package org.apache.lucene.analysis.hunspell;
import org.apache.lucene.store.ByteArrayDataOutput;
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.BytesRefHash;
import org.apache.lucene.util.CharsRef;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.IntsRef;
+import org.apache.lucene.util.IntsRefBuilder;
import org.apache.lucene.util.OfflineSorter;
import org.apache.lucene.util.OfflineSorter.ByteSequencesReader;
import org.apache.lucene.util.OfflineSorter.ByteSequencesWriter;
@@ -400,7 +402,7 @@ public class Dictionary {
private FST<IntsRef> affixFST(TreeMap<String,List<Integer>> affixes) throws IOException {
IntSequenceOutputs outputs = IntSequenceOutputs.getSingleton();
Builder<IntsRef> builder = new Builder<>(FST.INPUT_TYPE.BYTE4, outputs);
- IntsRef scratch = new IntsRef();
+ IntsRefBuilder scratch = new IntsRefBuilder();
for (Map.Entry<String,List<Integer>> entry : affixes.entrySet()) {
Util.toUTF32(entry.getKey(), scratch);
List<Integer> entries = entry.getValue();
@@ -408,7 +410,7 @@ public class Dictionary {
for (Integer c : entries) {
output.ints[output.length++] = c;
}
- builder.add(scratch, output);
+ builder.add(scratch.get(), output);
}
return builder.finish();
}
@@ -450,7 +452,7 @@ public class Dictionary {
Map<String,Integer> seenPatterns,
Map<String,Integer> seenStrips) throws IOException, ParseException {
- BytesRef scratch = new BytesRef();
+ BytesRefBuilder scratch = new BytesRefBuilder();
StringBuilder sb = new StringBuilder();
String args[] = header.split("\\s+");
@@ -543,7 +545,7 @@ public class Dictionary {
}
encodeFlags(scratch, appendFlags);
- int appendFlagsOrd = flagLookup.add(scratch);
+ int appendFlagsOrd = flagLookup.add(scratch.get());
if (appendFlagsOrd < 0) {
// already exists in our hash
appendFlagsOrd = (-appendFlagsOrd)-1;
@@ -594,10 +596,10 @@ public class Dictionary {
Outputs<CharsRef> outputs = CharSequenceOutputs.getSingleton();
Builder<CharsRef> builder = new Builder<>(FST.INPUT_TYPE.BYTE2, outputs);
- IntsRef scratchInts = new IntsRef();
+ IntsRefBuilder scratchInts = new IntsRefBuilder();
for (Map.Entry<String,String> entry : mappings.entrySet()) {
Util.toUTF16(entry.getKey(), scratchInts);
- builder.add(scratchInts, new CharsRef(entry.getValue()));
+ builder.add(scratchInts.get(), new CharsRef(entry.getValue()));
}
return builder.finish();
@@ -768,8 +770,8 @@ public class Dictionary {
* @throws IOException Can be thrown while reading from the file
*/
private void readDictionaryFiles(List<InputStream> dictionaries, CharsetDecoder decoder, Builder<IntsRef> words) throws IOException {
- BytesRef flagsScratch = new BytesRef();
- IntsRef scratchInts = new IntsRef();
+ BytesRefBuilder flagsScratch = new BytesRefBuilder();
+ IntsRefBuilder scratchInts = new IntsRefBuilder();
StringBuilder sb = new StringBuilder();
@@ -859,17 +861,17 @@ public class Dictionary {
unsorted.delete();
ByteSequencesReader reader = new ByteSequencesReader(sorted);
- BytesRef scratchLine = new BytesRef();
+ BytesRefBuilder scratchLine = new BytesRefBuilder();
// TODO: the flags themselves can be double-chars (long) or also numeric
// either way the trick is to encode them as char... but they must be parsed differently
String currentEntry = null;
- IntsRef currentOrds = new IntsRef();
+ IntsRefBuilder currentOrds = new IntsRefBuilder();
String line;
while (reader.read(scratchLine)) {
- line = scratchLine.utf8ToString();
+ line = scratchLine.get().utf8ToString();
String entry;
char wordForm[];
int end;
@@ -909,7 +911,7 @@ public class Dictionary {
throw new IllegalArgumentException("out of order: " + entry + " < " + currentEntry);
} else {
encodeFlags(flagsScratch, wordForm);
- int ord = flagLookup.add(flagsScratch);
+ int ord = flagLookup.add(flagsScratch.get());
if (ord < 0) {
// already exists in our hash
ord = (-ord)-1;
@@ -917,27 +919,25 @@ public class Dictionary {
// finalize current entry, and switch "current" if necessary
if (cmp > 0 && currentEntry != null) {
Util.toUTF32(currentEntry, scratchInts);
- words.add(scratchInts, currentOrds);
+ words.add(scratchInts.get(), currentOrds.get());
}
// swap current
if (cmp > 0 || currentEntry == null) {
currentEntry = entry;
- currentOrds = new IntsRef(); // must be this way
+ currentOrds = new IntsRefBuilder(); // must be this way
}
if (hasStemExceptions) {
- currentOrds.grow(currentOrds.length+2);
- currentOrds.ints[currentOrds.length++] = ord;
- currentOrds.ints[currentOrds.length++] = stemExceptionID;
+ currentOrds.append(ord);
+ currentOrds.append(stemExceptionID);
} else {
- currentOrds.grow(currentOrds.length+1);
- currentOrds.ints[currentOrds.length++] = ord;
+ currentOrds.append(ord);
}
}
}
// finalize last entry
Util.toUTF32(currentEntry, scratchInts);
- words.add(scratchInts, currentOrds);
+ words.add(scratchInts.get(), currentOrds.get());
reader.close();
sorted.delete();
@@ -957,15 +957,14 @@ public class Dictionary {
return flags;
}
- static void encodeFlags(BytesRef b, char flags[]) {
+ static void encodeFlags(BytesRefBuilder b, char flags[]) {
int len = flags.length << 1;
b.grow(len);
- b.length = len;
- int upto = b.offset;
+ b.clear();
for (int i = 0; i < flags.length; i++) {
int flag = flags[i];
- b.bytes[upto++] = (byte) ((flag >> 8) & 0xff);
- b.bytes[upto++] = (byte) (flag & 0xff);
+ b.append((byte) ((flag >> 8) & 0xff));
+ b.append((byte) (flag & 0xff));
}
}
diff --git a/lucene/analysis/common/src/java/org/apache/lucene/analysis/miscellaneous/StemmerOverrideFilter.java b/lucene/analysis/common/src/java/org/apache/lucene/analysis/miscellaneous/StemmerOverrideFilter.java
index 53b4ecdf057..a35dae128f6 100644
--- a/lucene/analysis/common/src/java/org/apache/lucene/analysis/miscellaneous/StemmerOverrideFilter.java
+++ b/lucene/analysis/common/src/java/org/apache/lucene/analysis/miscellaneous/StemmerOverrideFilter.java
@@ -17,23 +17,25 @@ package org.apache.lucene.analysis.miscellaneous;
* limitations under the License.
*/
+import java.io.IOException;
+import java.util.ArrayList;
+
import org.apache.lucene.analysis.TokenFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.analysis.tokenattributes.KeywordAttribute;
+import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.BytesRefHash;
-import org.apache.lucene.util.CharsRef;
-import org.apache.lucene.util.IntsRef;
+import org.apache.lucene.util.CharsRefBuilder;
+import org.apache.lucene.util.IntsRefBuilder;
import org.apache.lucene.util.UnicodeUtil;
import org.apache.lucene.util.fst.ByteSequenceOutputs;
import org.apache.lucene.util.fst.FST;
import org.apache.lucene.util.fst.FST.Arc;
import org.apache.lucene.util.fst.FST.BytesReader;
-import java.io.IOException;
-import java.util.ArrayList;
-
/**
* Provides the ability to override any {@link KeywordAttribute} aware stemmer
* with custom dictionary-based stemming.
@@ -45,7 +47,7 @@ public final class StemmerOverrideFilter extends TokenFilter {
private final KeywordAttribute keywordAtt = addAttribute(KeywordAttribute.class);
private final BytesReader fstReader;
private final Arc<BytesRef> scratchArc = new FST.Arc<>();
- private final CharsRef spare = new CharsRef();
+ private char[] spare = new char[0];
/**
* Create a new StemmerOverrideFilter, performing dictionary-based stemming
@@ -71,12 +73,13 @@ public final class StemmerOverrideFilter extends TokenFilter {
if (!keywordAtt.isKeyword()) { // don't muck with already-keyworded terms
final BytesRef stem = stemmerOverrideMap.get(termAtt.buffer(), termAtt.length(), scratchArc, fstReader);
if (stem != null) {
- final char[] buffer = spare.chars = termAtt.buffer();
- UnicodeUtil.UTF8toUTF16(stem.bytes, stem.offset, stem.length, spare);
- if (spare.chars != buffer) {
- termAtt.copyBuffer(spare.chars, spare.offset, spare.length);
+ spare = ArrayUtil.grow(termAtt.buffer(), stem.length);
+ final int length = UnicodeUtil.UTF8toUTF16(stem, spare);
+ if (spare != termAtt.buffer()) {
+ termAtt.copyBuffer(spare, 0, length);
+ } else {
+ termAtt.setLength(length);
}
- termAtt.setLength(spare.length);
keywordAtt.setKeyword(true);
}
}
@@ -144,10 +147,10 @@ public final class StemmerOverrideFilter extends TokenFilter {
*/
public static class Builder {
private final BytesRefHash hash = new BytesRefHash();
- private final BytesRef spare = new BytesRef();
+ private final BytesRefBuilder spare = new BytesRefBuilder();
private final ArrayList<CharSequence> outputValues = new ArrayList<>();
private final boolean ignoreCase;
- private final CharsRef charsSpare = new CharsRef();
+ private final CharsRefBuilder charsSpare = new CharsRefBuilder();
/**
* Creates a new {@link Builder} with ignoreCase set to <code>false</code>
@@ -176,17 +179,17 @@ public final class StemmerOverrideFilter extends TokenFilter {
if (ignoreCase) {
// convert on the fly to lowercase
charsSpare.grow(length);
- final char[] buffer = charsSpare.chars;
+ final char[] buffer = charsSpare.chars();
for (int i = 0; i < length; ) {
i += Character.toChars(
Character.toLowerCase(
Character.codePointAt(input, i)), buffer, i);
}
- UnicodeUtil.UTF16toUTF8(buffer, 0, length, spare);
+ spare.copyChars(buffer, 0, length);
} else {
- UnicodeUtil.UTF16toUTF8(input, 0, length, spare);
+ spare.copyChars(input, 0, length);
}
- if (hash.add(spare) >= 0) {
+ if (hash.add(spare.get()) >= 0) {
outputValues.add(output);
return true;
}
@@ -203,13 +206,14 @@ public final class StemmerOverrideFilter extends TokenFilter {
org.apache.lucene.util.fst.Builder<BytesRef> builder = new org.apache.lucene.util.fst.Builder<>(
FST.INPUT_TYPE.BYTE4, outputs);
final int[] sort = hash.sort(BytesRef.getUTF8SortedAsUnicodeComparator());
- IntsRef intsSpare = new IntsRef();
+ IntsRefBuilder intsSpare = new IntsRefBuilder();
final int size = hash.size();
+ BytesRef spare = new BytesRef();
for (int i = 0; i < size; i++) {
int id = sort[i];
BytesRef bytesRef = hash.get(id, spare);
- UnicodeUtil.UTF8toUTF32(bytesRef, intsSpare);
- builder.add(intsSpare, new BytesRef(outputValues.get(id)));
+ intsSpare.copyUTF8Bytes(bytesRef);
+ builder.add(intsSpare.get(), new BytesRef(outputValues.get(id)));
}
return new StemmerOverrideMap(builder.finish(), ignoreCase);
}
diff --git a/lucene/analysis/common/src/java/org/apache/lucene/analysis/nl/DutchAnalyzer.java b/lucene/analysis/common/src/java/org/apache/lucene/analysis/nl/DutchAnalyzer.java
index e3b2389f542..a9b54098747 100644
--- a/lucene/analysis/common/src/java/org/apache/lucene/analysis/nl/DutchAnalyzer.java
+++ b/lucene/analysis/common/src/java/org/apache/lucene/analysis/nl/DutchAnalyzer.java
@@ -32,6 +32,7 @@ import org.apache.lucene.analysis.util.CharArrayMap;
import org.apache.lucene.analysis.util.CharArraySet;
import org.apache.lucene.analysis.util.WordlistLoader;
import org.apache.lucene.util.CharsRef;
+import org.apache.lucene.util.CharsRefBuilder;
import org.apache.lucene.util.IOUtils;
import java.io.IOException;
@@ -123,11 +124,11 @@ public final class DutchAnalyzer extends Analyzer {
// we don't need to ignore case here since we lowercase in this analyzer anyway
StemmerOverrideFilter.Builder builder = new StemmerOverrideFilter.Builder(false);
CharArrayMap<String>.EntryIterator iter = stemOverrideDict.entrySet().iterator();
- CharsRef spare = new CharsRef();
+ CharsRefBuilder spare = new CharsRefBuilder();
while (iter.hasNext()) {
char[] nextKey = iter.nextKey();
spare.copyChars(nextKey, 0, nextKey.length);
- builder.add(spare, iter.currentValue());
+ builder.add(spare.get(), iter.currentValue());
}
try {
this.stemdict = builder.build();
diff --git a/lucene/analysis/common/src/java/org/apache/lucene/analysis/pattern/PatternCaptureGroupTokenFilter.java b/lucene/analysis/common/src/java/org/apache/lucene/analysis/pattern/PatternCaptureGroupTokenFilter.java
index 7ed59cfa052..34100277345 100644
--- a/lucene/analysis/common/src/java/org/apache/lucene/analysis/pattern/PatternCaptureGroupTokenFilter.java
+++ b/lucene/analysis/common/src/java/org/apache/lucene/analysis/pattern/PatternCaptureGroupTokenFilter.java
@@ -25,6 +25,7 @@ import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute;
import org.apache.lucene.util.CharsRef;
+import org.apache.lucene.util.CharsRefBuilder;
/**
* CaptureGroup uses Java regexes to emit multiple tokens - one for each capture
@@ -74,7 +75,7 @@ public final class PatternCaptureGroupTokenFilter extends TokenFilter {
private final PositionIncrementAttribute posAttr = addAttribute(PositionIncrementAttribute.class);
private State state;
private final Matcher[] matchers;
- private final CharsRef spare = new CharsRef();
+ private final CharsRefBuilder spare = new CharsRefBuilder();
private final int[] groupCounts;
private final boolean preserveOriginal;
private int[] currentGroup;
@@ -119,7 +120,7 @@ public final class PatternCaptureGroupTokenFilter extends TokenFilter {
final int start = matcher.start(currentGroup[i]);
final int end = matcher.end(currentGroup[i]);
if (start == end || preserveOriginal && start == 0
- && spare.length == end) {
+ && spare.length() == end) {
currentGroup[i]++;
continue;
}
@@ -151,7 +152,7 @@ public final class PatternCaptureGroupTokenFilter extends TokenFilter {
.end(currentGroup[currentMatcher]);
posAttr.setPositionIncrement(0);
- charTermAttr.copyBuffer(spare.chars, start, end - start);
+ charTermAttr.copyBuffer(spare.chars(), start, end - start);
currentGroup[currentMatcher]++;
return true;
}
@@ -166,7 +167,7 @@ public final class PatternCaptureGroupTokenFilter extends TokenFilter {
state = captureState();
for (int i = 0; i < matchers.length; i++) {
- matchers[i].reset(spare);
+ matchers[i].reset(spare.get());
currentGroup[i] = -1;
}
@@ -182,7 +183,7 @@ public final class PatternCaptureGroupTokenFilter extends TokenFilter {
if (start == 0) {
charTermAttr.setLength(end);
} else {
- charTermAttr.copyBuffer(spare.chars, start, end - start);
+ charTermAttr.copyBuffer(spare.chars(), start, end - start);
}
currentGroup[currentMatcher]++;
}
diff --git a/lucene/analysis/common/src/java/org/apache/lucene/analysis/query/QueryAutoStopWordAnalyzer.java b/lucene/analysis/common/src/java/org/apache/lucene/analysis/query/QueryAutoStopWordAnalyzer.java
index 995ae2db893..dc925b855f5 100644
--- a/lucene/analysis/common/src/java/org/apache/lucene/analysis/query/QueryAutoStopWordAnalyzer.java
+++ b/lucene/analysis/common/src/java/org/apache/lucene/analysis/query/QueryAutoStopWordAnalyzer.java
@@ -29,7 +29,7 @@ import org.apache.lucene.index.Term;
import org.apache.lucene.index.Terms;
import org.apache.lucene.index.TermsEnum;
import org.apache.lucene.util.BytesRef;
-import org.apache.lucene.util.CharsRef;
+import org.apache.lucene.util.CharsRefBuilder;
import org.apache.lucene.util.UnicodeUtil;
/**
@@ -142,13 +142,13 @@ public final class QueryAutoStopWordAnalyzer extends AnalyzerWrapper {
for (String field : fields) {
Set<String> stopWords = new HashSet<>();
Terms terms = MultiFields.getTerms(indexReader, field);
- CharsRef spare = new CharsRef();
+ CharsRefBuilder spare = new CharsRefBuilder();
if (terms != null) {
TermsEnum te = terms.iterator(null);
BytesRef text;
while ((text = te.next()) != null) {
if (te.docFreq() > maxDocFreq) {
- UnicodeUtil.UTF8toUTF16(text, spare);
+ spare.copyUTF8Bytes(text);
stopWords.add(spare.toString());
}
}
diff --git a/lucene/analysis/common/src/java/org/apache/lucene/analysis/synonym/SolrSynonymParser.java b/lucene/analysis/common/src/java/org/apache/lucene/analysis/synonym/SolrSynonymParser.java
index 1817055af4d..860ef98a23a 100644
--- a/lucene/analysis/common/src/java/org/apache/lucene/analysis/synonym/SolrSynonymParser.java
+++ b/lucene/analysis/common/src/java/org/apache/lucene/analysis/synonym/SolrSynonymParser.java
@@ -26,6 +26,7 @@ import java.util.ArrayList;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.util.CharsRef;
+import org.apache.lucene.util.CharsRefBuilder;
/**
* Parser for the Solr synonyms format.
@@ -95,19 +96,19 @@ public class SolrSynonymParser extends SynonymMap.Parser {
String inputStrings[] = split(sides[0], ",");
inputs = new CharsRef[inputStrings.length];
for (int i = 0; i < inputs.length; i++) {
- inputs[i] = analyze(unescape(inputStrings[i]).trim(), new CharsRef());
+ inputs[i] = analyze(unescape(inputStrings[i]).trim(), new CharsRefBuilder());
}
String outputStrings[] = split(sides[1], ",");
outputs = new CharsRef[outputStrings.length];
for (int i = 0; i < outputs.length; i++) {
- outputs[i] = analyze(unescape(outputStrings[i]).trim(), new CharsRef());
+ outputs[i] = analyze(unescape(outputStrings[i]).trim(), new CharsRefBuilder());
}
} else {
String inputStrings[] = split(line, ",");
inputs = new CharsRef[inputStrings.length];
for (int i = 0; i < inputs.length; i++) {
- inputs[i] = analyze(unescape(inputStrings[i]).trim(), new CharsRef());
+ inputs[i] = analyze(unescape(inputStrings[i]).trim(), new CharsRefBuilder());
}
if (expand) {
outputs = inputs;
diff --git a/lucene/analysis/common/src/java/org/apache/lucene/analysis/synonym/SynonymFilter.java b/lucene/analysis/common/src/java/org/apache/lucene/analysis/synonym/SynonymFilter.java
index df87946b2d8..0e5337f3e12 100644
--- a/lucene/analysis/common/src/java/org/apache/lucene/analysis/synonym/SynonymFilter.java
+++ b/lucene/analysis/common/src/java/org/apache/lucene/analysis/synonym/SynonymFilter.java
@@ -18,6 +18,7 @@ package org.apache.lucene.analysis.synonym;
*/
import java.io.IOException;
+import java.util.Arrays;
import org.apache.lucene.analysis.TokenFilter;
import org.apache.lucene.analysis.TokenStream;
@@ -30,7 +31,9 @@ import org.apache.lucene.store.ByteArrayDataInput;
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.AttributeSource;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.CharsRef;
+import org.apache.lucene.util.CharsRefBuilder;
import org.apache.lucene.util.RamUsageEstimator;
import org.apache.lucene.util.UnicodeUtil;
import org.apache.lucene.util.fst.FST;
@@ -134,7 +137,7 @@ public final class SynonymFilter extends TokenFilter {
// state for (and enumerate) all other tokens at this
// position:
private static class PendingInput {
- final CharsRef term = new CharsRef();
+ final CharsRefBuilder term = new CharsRefBuilder();
AttributeSource.State state;
boolean keepOrig;
boolean matched;
@@ -157,7 +160,7 @@ public final class SynonymFilter extends TokenFilter {
// Holds pending output synonyms for one future position:
private static class PendingOutputs {
- CharsRef[] outputs;
+ CharsRefBuilder[] outputs;
int[] endOffsets;
int[] posLengths;
int upto;
@@ -167,7 +170,7 @@ public final class SynonymFilter extends TokenFilter {
int lastPosLength;
public PendingOutputs() {
- outputs = new CharsRef[1];
+ outputs = new CharsRefBuilder[1];
endOffsets = new int[1];
posLengths = new int[1];
}
@@ -181,12 +184,12 @@ public final class SynonymFilter extends TokenFilter {
assert upto < count;
lastEndOffset = endOffsets[upto];
lastPosLength = posLengths[upto];
- final CharsRef result = outputs[upto++];
+ final CharsRefBuilder result = outputs[upto++];
posIncr = 0;
if (upto == count) {
reset();
}
- return result;
+ return result.get();
}
public int getLastEndOffset() {
@@ -199,9 +202,7 @@ public final class SynonymFilter extends TokenFilter {
public void add(char[] output, int offset, int len, int endOffset, int posLength) {
if (count == outputs.length) {
- final CharsRef[] next = new CharsRef[ArrayUtil.oversize(1+count, RamUsageEstimator.NUM_BYTES_OBJECT_REF)];
- System.arraycopy(outputs, 0, next, 0, count);
- outputs = next;
+ outputs = Arrays.copyOf(outputs, ArrayUtil.oversize(1+count, RamUsageEstimator.NUM_BYTES_OBJECT_REF));
}
if (count == endOffsets.length) {
final int[] next = new int[ArrayUtil.oversize(1+count, RamUsageEstimator.NUM_BYTES_INT)];
@@ -214,7 +215,7 @@ public final class SynonymFilter extends TokenFilter {
posLengths = next;
}
if (outputs[count] == null) {
- outputs[count] = new CharsRef();
+ outputs[count] = new CharsRefBuilder();
}
outputs[count].copyChars(output, offset, len);
// endOffset can be -1, in which case we should simply
@@ -249,7 +250,7 @@ public final class SynonymFilter extends TokenFilter {
private final BytesRef scratchBytes = new BytesRef();
- private final CharsRef scratchChars = new CharsRef();
+ private final CharsRefBuilder scratchChars = new CharsRefBuilder();
/**
* @param input input tokenstream
@@ -378,8 +379,8 @@ public final class SynonymFilter extends TokenFilter {
}
} else {
// Still in our lookahead
- buffer = futureInputs[curNextRead].term.chars;
- bufferLen = futureInputs[curNextRead].term.length;
+ buffer = futureInputs[curNextRead].term.chars();
+ bufferLen = futureInputs[curNextRead].term.length();
inputEndOffset = futureInputs[curNextRead].endOffset;
//System.out.println(" old token=" + new String(buffer, 0, bufferLen));
}
@@ -462,19 +463,19 @@ public final class SynonymFilter extends TokenFilter {
synonyms.words.get(bytesReader.readVInt(),
scratchBytes);
//System.out.println(" outIDX=" + outputIDX + " bytes=" + scratchBytes.length);
- UnicodeUtil.UTF8toUTF16(scratchBytes, scratchChars);
- int lastStart = scratchChars.offset;
- final int chEnd = lastStart + scratchChars.length;
+ scratchChars.copyUTF8Bytes(scratchBytes);
+ int lastStart = 0;
+ final int chEnd = lastStart + scratchChars.length();
int outputUpto = nextRead;
for(int chIDX=lastStart;chIDX<=chEnd;chIDX++) {
- if (chIDX == chEnd || scratchChars.chars[chIDX] == SynonymMap.WORD_SEPARATOR) {
+ if (chIDX == chEnd || scratchChars.charAt(chIDX) == SynonymMap.WORD_SEPARATOR) {
final int outputLen = chIDX - lastStart;
// Caller is not allowed to have empty string in
// the output:
assert outputLen > 0: "output contains empty string: " + scratchChars;
final int endOffset;
final int posLen;
- if (chIDX == chEnd && lastStart == scratchChars.offset) {
+ if (chIDX == chEnd && lastStart == 0) {
// This rule had a single output token, so, we set
// this output's endOffset to the current
// endOffset (ie, endOffset of the last input
@@ -489,7 +490,7 @@ public final class SynonymFilter extends TokenFilter {
endOffset = -1;
posLen = 1;
}
- futureOutputs[outputUpto].add(scratchChars.chars, lastStart, outputLen, endOffset, posLen);
+ futureOutputs[outputUpto].add(scratchChars.chars(), lastStart, outputLen, endOffset, posLen);
//System.out.println(" " + new String(scratchChars.chars, lastStart, outputLen) + " outputUpto=" + outputUpto);
lastStart = 1+chIDX;
//System.out.println(" slot=" + outputUpto + " keepOrig=" + keepOrig);
diff --git a/lucene/analysis/common/src/java/org/apache/lucene/analysis/synonym/SynonymMap.java b/lucene/analysis/common/src/java/org/apache/lucene/analysis/synonym/SynonymMap.java
index 88b072ac49a..7c5799c66e0 100644
--- a/lucene/analysis/common/src/java/org/apache/lucene/analysis/synonym/SynonymMap.java
+++ b/lucene/analysis/common/src/java/org/apache/lucene/analysis/synonym/SynonymMap.java
@@ -32,9 +32,12 @@ import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute;
import org.apache.lucene.store.ByteArrayDataOutput;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.BytesRefHash;
import org.apache.lucene.util.CharsRef;
+import org.apache.lucene.util.CharsRefBuilder;
import org.apache.lucene.util.IntsRef;
+import org.apache.lucene.util.IntsRefBuilder;
import org.apache.lucene.util.UnicodeUtil;
import org.apache.lucene.util.fst.ByteSequenceOutputs;
import org.apache.lucene.util.fst.FST;
@@ -69,7 +72,7 @@ public class SynonymMap {
public static class Builder {
private final HashMap<CharsRef,MapEntry> workingSet = new HashMap<>();
private final BytesRefHash words = new BytesRefHash();
- private final BytesRef utf8Scratch = new BytesRef(8);
+ private final BytesRefBuilder utf8Scratch = new BytesRefBuilder();
private int maxHorizontalContext;
private final boolean dedup;
@@ -88,15 +91,15 @@ public class SynonymMap {
/** Sugar: just joins the provided terms with {@link
* SynonymMap#WORD_SEPARATOR}. reuse and its chars
* must not be null. */
- public static CharsRef join(String[] words, CharsRef reuse) {
+ public static CharsRef join(String[] words, CharsRefBuilder reuse) {
int upto = 0;
- char[] buffer = reuse.chars;
+ char[] buffer = reuse.chars();
for (String word : words) {
final int wordLen = word.length();
final int needed = (0 == upto ? wordLen : 1 + upto + wordLen); // Add 1 for WORD_SEPARATOR
if (needed > buffer.length) {
reuse.grow(needed);
- buffer = reuse.chars;
+ buffer = reuse.chars();
}
if (upto > 0) {
buffer[upto++] = SynonymMap.WORD_SEPARATOR;
@@ -105,8 +108,8 @@ public class SynonymMap {
word.getChars(0, wordLen, buffer, upto);
upto += wordLen;
}
- reuse.length = upto;
- return reuse;
+ reuse.setLength(upto);
+ return reuse.get();
}
@@ -153,9 +156,9 @@ public class SynonymMap {
assert !hasHoles(output): "output has holes: " + output;
//System.out.println("fmap.add input=" + input + " numInputWords=" + numInputWords + " output=" + output + " numOutputWords=" + numOutputWords);
- UnicodeUtil.UTF16toUTF8(output.chars, output.offset, output.length, utf8Scratch);
+ utf8Scratch.copyChars(output.chars, output.offset, output.length);
// lookup in hash
- int ord = words.add(utf8Scratch);
+ int ord = words.add(utf8Scratch.get());
if (ord < 0) {
// already exists in our hash
ord = (-ord)-1;
@@ -212,7 +215,7 @@ public class SynonymMap {
org.apache.lucene.util.fst.Builder<BytesRef> builder =
new org.apache.lucene.util.fst.Builder<>(FST.INPUT_TYPE.BYTE4, outputs);
- BytesRef scratch = new BytesRef(64);
+ BytesRefBuilder scratch = new BytesRefBuilder();
ByteArrayDataOutput scratchOutput = new ByteArrayDataOutput();
final Set<Integer> dedupSet;
@@ -229,7 +232,7 @@ public class SynonymMap {
CharsRef sortedKeys[] = keys.toArray(new CharsRef[keys.size()]);
Arrays.sort(sortedKeys, CharsRef.getUTF16SortedAsUTF8Comparator());
- final IntsRef scratchIntsRef = new IntsRef();
+ final IntsRefBuilder scratchIntsRef = new IntsRefBuilder();
//System.out.println("fmap.build");
for (int keyIdx = 0; keyIdx < sortedKeys.length; keyIdx++) {
@@ -241,8 +244,7 @@ public class SynonymMap {
int estimatedSize = 5 + numEntries * 5; // numEntries + one ord for each entry
scratch.grow(estimatedSize);
- scratchOutput.reset(scratch.bytes, scratch.offset, scratch.bytes.length);
- assert scratch.offset == 0;
+ scratchOutput.reset(scratch.bytes());
// now write our output data:
int count = 0;
@@ -265,17 +267,17 @@ public class SynonymMap {
final int vIntLen = pos2-pos;
// Move the count + includeOrig to the front of the byte[]:
- System.arraycopy(scratch.bytes, pos, spare, 0, vIntLen);
- System.arraycopy(scratch.bytes, 0, scratch.bytes, vIntLen, pos);
- System.arraycopy(spare, 0, scratch.bytes, 0, vIntLen);
+ System.arraycopy(scratch.bytes(), pos, spare, 0, vIntLen);
+ System.arraycopy(scratch.bytes(), 0, scratch.bytes(), vIntLen, pos);
+ System.arraycopy(spare, 0, scratch.bytes(), 0, vIntLen);
if (dedupSet != null) {
dedupSet.clear();
}
- scratch.length = scratchOutput.getPosition() - scratch.offset;
+ scratch.setLength(scratchOutput.getPosition());
//System.out.println(" add input=" + input + " output=" + scratch + " offset=" + scratch.offset + " length=" + scratch.length + " count=" + count);
- builder.add(Util.toUTF32(input, scratchIntsRef), BytesRef.deepCopyOf(scratch));
+ builder.add(Util.toUTF32(input, scratchIntsRef), scratch.toBytesRef());
}
FST<BytesRef> fst = builder.finish();
@@ -306,12 +308,12 @@ public class SynonymMap {
/** Sugar: analyzes the text with the analyzer and
* separates by {@link SynonymMap#WORD_SEPARATOR}.
* reuse and its chars must not be null. */
- public CharsRef analyze(String text, CharsRef reuse) throws IOException {
+ public CharsRef analyze(String text, CharsRefBuilder reuse) throws IOException {
try (TokenStream ts = analyzer.tokenStream("", text)) {
CharTermAttribute termAtt = ts.addAttribute(CharTermAttribute.class);
PositionIncrementAttribute posIncAtt = ts.addAttribute(PositionIncrementAttribute.class);
ts.reset();
- reuse.length = 0;
+ reuse.clear();
while (ts.incrementToken()) {
int length = termAtt.length();
if (length == 0) {
@@ -320,21 +322,21 @@ public class SynonymMap {
if (posIncAtt.getPositionIncrement() != 1) {
throw new IllegalArgumentException("term: " + text + " analyzed to a token with posinc != 1");
}
- reuse.grow(reuse.length + length + 1); /* current + word + separator */
- int end = reuse.offset + reuse.length;
- if (reuse.length > 0) {
- reuse.chars[end++] = SynonymMap.WORD_SEPARATOR;
- reuse.length++;
+ reuse.grow(reuse.length() + length + 1); /* current + word + separator */
+ int end = reuse.length();
+ if (reuse.length() > 0) {
+ reuse.setCharAt(end++, SynonymMap.WORD_SEPARATOR);
+ reuse.setLength(reuse.length() + 1);
}
- System.arraycopy(termAtt.buffer(), 0, reuse.chars, end, length);
- reuse.length += length;
+ System.arraycopy(termAtt.buffer(), 0, reuse.chars(), end, length);
+ reuse.setLength(reuse.length() + length);
}
ts.end();
}
- if (reuse.length == 0) {
+ if (reuse.length() == 0) {
throw new IllegalArgumentException("term: " + text + " was completely eliminated by analyzer");
}
- return reuse;
+ return reuse.get();
}
}
diff --git a/lucene/analysis/common/src/java/org/apache/lucene/analysis/synonym/WordnetSynonymParser.java b/lucene/analysis/common/src/java/org/apache/lucene/analysis/synonym/WordnetSynonymParser.java
index f4421bf5cea..42fa96476bd 100644
--- a/lucene/analysis/common/src/java/org/apache/lucene/analysis/synonym/WordnetSynonymParser.java
+++ b/lucene/analysis/common/src/java/org/apache/lucene/analysis/synonym/WordnetSynonymParser.java
@@ -21,9 +21,11 @@ import java.io.IOException;
import java.io.LineNumberReader;
import java.io.Reader;
import java.text.ParseException;
+import java.util.Arrays;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.util.CharsRef;
+import org.apache.lucene.util.CharsRefBuilder;
/**
* Parser for wordnet prolog format
@@ -58,12 +60,10 @@ public class WordnetSynonymParser extends SynonymMap.Parser {
}
if (synset.length <= synsetSize+1) {
- CharsRef larger[] = new CharsRef[synset.length * 2];
- System.arraycopy(synset, 0, larger, 0, synsetSize);
- synset = larger;
+ synset = Arrays.copyOf(synset, synset.length * 2);
}
- synset[synsetSize] = parseSynonym(line, synset[synsetSize]);
+ synset[synsetSize] = parseSynonym(line, new CharsRefBuilder());
synsetSize++;
lastSynSetID = synSetID;
}
@@ -79,9 +79,9 @@ public class WordnetSynonymParser extends SynonymMap.Parser {
}
}
- private CharsRef parseSynonym(String line, CharsRef reuse) throws IOException {
+ private CharsRef parseSynonym(String line, CharsRefBuilder reuse) throws IOException {
if (reuse == null) {
- reuse = new CharsRef(8);
+ reuse = new CharsRefBuilder();
}
int start = line.indexOf('\'')+1;
diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/hunspell/TestDictionary.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/hunspell/TestDictionary.java
index 63ac534e8f0..f38b4062744 100644
--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/hunspell/TestDictionary.java
+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/hunspell/TestDictionary.java
@@ -28,6 +28,7 @@ import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.CharsRef;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.IntsRef;
+import org.apache.lucene.util.IntsRefBuilder;
import org.apache.lucene.util.LuceneTestCase;
import org.apache.lucene.util.fst.Builder;
import org.apache.lucene.util.fst.CharSequenceOutputs;
@@ -187,23 +188,23 @@ public class TestDictionary extends LuceneTestCase {
public void testReplacements() throws Exception {
Outputs<CharsRef> outputs = CharSequenceOutputs.getSingleton();
Builder<CharsRef> builder = new Builder<>(FST.INPUT_TYPE.BYTE2, outputs);
- IntsRef scratchInts = new IntsRef();
+ IntsRefBuilder scratchInts = new IntsRefBuilder();
// a -> b
Util.toUTF16("a", scratchInts);
- builder.add(scratchInts, new CharsRef("b"));
+ builder.add(scratchInts.get(), new CharsRef("b"));
// ab -> c
Util.toUTF16("ab", scratchInts);
- builder.add(scratchInts, new CharsRef("c"));
+ builder.add(scratchInts.get(), new CharsRef("c"));
// c -> de
Util.toUTF16("c", scratchInts);
- builder.add(scratchInts, new CharsRef("de"));
+ builder.add(scratchInts.get(), new CharsRef("de"));
// def -> gh
Util.toUTF16("def", scratchInts);
- builder.add(scratchInts, new CharsRef("gh"));
+ builder.add(scratchInts.get(), new CharsRef("gh"));
FST<CharsRef> fst = builder.finish();
diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestLimitTokenPositionFilter.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestLimitTokenPositionFilter.java
index a3dbf8e0c62..1b541f3b7ce 100644
--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestLimitTokenPositionFilter.java
+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/miscellaneous/TestLimitTokenPositionFilter.java
@@ -23,6 +23,7 @@ import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.synonym.SynonymFilter;
import org.apache.lucene.analysis.synonym.SynonymMap;
import org.apache.lucene.util.CharsRef;
+import org.apache.lucene.util.CharsRefBuilder;
import org.junit.Test;
import java.io.IOException;
@@ -68,11 +69,11 @@ public class TestLimitTokenPositionFilter extends BaseTokenStreamTestCase {
builder.add(new CharsRef("one"), new CharsRef("first"), true);
builder.add(new CharsRef("one"), new CharsRef("alpha"), true);
builder.add(new CharsRef("one"), new CharsRef("beguine"), true);
- CharsRef multiWordCharsRef = new CharsRef();
+ CharsRefBuilder multiWordCharsRef = new CharsRefBuilder();
SynonymMap.Builder.join(new String[]{"and", "indubitably", "single", "only"}, multiWordCharsRef);
- builder.add(new CharsRef("one"), multiWordCharsRef, true);
+ builder.add(new CharsRef("one"), multiWordCharsRef.get(), true);
SynonymMap.Builder.join(new String[]{"dopple", "ganger"}, multiWordCharsRef);
- builder.add(new CharsRef("two"), multiWordCharsRef, true);
+ builder.add(new CharsRef("two"), multiWordCharsRef.get(), true);
SynonymMap synonymMap = builder.build();
TokenStream stream = new SynonymFilter(tokenizer, synonymMap, true);
stream = new LimitTokenPositionFilter(stream, 3, consumeAll);
diff --git a/lucene/analysis/common/src/test/org/apache/lucene/analysis/synonym/TestSynonymMapFilter.java b/lucene/analysis/common/src/test/org/apache/lucene/analysis/synonym/TestSynonymMapFilter.java
index b495e8ed40f..b8b95725bcd 100644
--- a/lucene/analysis/common/src/test/org/apache/lucene/analysis/synonym/TestSynonymMapFilter.java
+++ b/lucene/analysis/common/src/test/org/apache/lucene/analysis/synonym/TestSynonymMapFilter.java
@@ -38,6 +38,7 @@ import org.apache.lucene.analysis.MockGraphTokenFilter;
import org.apache.lucene.analysis.core.KeywordTokenizer;
import org.apache.lucene.analysis.tokenattributes.*;
import org.apache.lucene.util.CharsRef;
+import org.apache.lucene.util.CharsRefBuilder;
import org.apache.lucene.util.TestUtil;
public class TestSynonymMapFilter extends BaseTokenStreamTestCase {
@@ -54,13 +55,13 @@ public class TestSynonymMapFilter extends BaseTokenStreamTestCase {
if (VERBOSE) {
System.out.println(" add input=" + input + " output=" + output + " keepOrig=" + keepOrig);
}
- CharsRef inputCharsRef = new CharsRef();
+ CharsRefBuilder inputCharsRef = new CharsRefBuilder();
SynonymMap.Builder.join(input.split(" +"), inputCharsRef);
- CharsRef outputCharsRef = new CharsRef();
+ CharsRefBuilder outputCharsRef = new CharsRefBuilder();
SynonymMap.Builder.join(output.split(" +"), outputCharsRef);
- b.add(inputCharsRef, outputCharsRef, keepOrig);
+ b.add(inputCharsRef.get(), outputCharsRef.get(), keepOrig);
}
private void assertEquals(CharTermAttribute term, String expected) {
diff --git a/lucene/analysis/kuromoji/src/java/org/apache/lucene/analysis/ja/dict/UserDictionary.java b/lucene/analysis/kuromoji/src/java/org/apache/lucene/analysis/ja/dict/UserDictionary.java
index 2b76d2c24c0..c10e571f0df 100644
--- a/lucene/analysis/kuromoji/src/java/org/apache/lucene/analysis/ja/dict/UserDictionary.java
+++ b/lucene/analysis/kuromoji/src/java/org/apache/lucene/analysis/ja/dict/UserDictionary.java
@@ -29,6 +29,7 @@ import java.util.TreeMap;
import org.apache.lucene.analysis.ja.util.CSVUtil;
import org.apache.lucene.util.IntsRef;
+import org.apache.lucene.util.IntsRefBuilder;
import org.apache.lucene.util.fst.Builder;
import org.apache.lucene.util.fst.FST;
import org.apache.lucene.util.fst.PositiveIntOutputs;
@@ -90,7 +91,7 @@ public final class UserDictionary implements Dictionary {
PositiveIntOutputs fstOutput = PositiveIntOutputs.getSingleton();
Builder<Long> fstBuilder = new Builder<>(FST.INPUT_TYPE.BYTE2, fstOutput);
- IntsRef scratch = new IntsRef();
+ IntsRefBuilder scratch = new IntsRefBuilder();
long ord = 0;
for (String[] values : featureEntries) {
@@ -114,11 +115,11 @@ public final class UserDictionary implements Dictionary {
// add mapping to FST
String token = values[0];
scratch.grow(token.length());
- scratch.length = token.length();
+ scratch.setLength(token.length());
for (int i = 0; i < token.length(); i++) {
- scratch.ints[i] = (int) token.charAt(i);
+ scratch.setIntAt(i, (int) token.charAt(i));
}
- fstBuilder.add(scratch, ord);
+ fstBuilder.add(scratch.get(), ord);
segmentations.add(wordIdAndLength);
ord++;
}
diff --git a/lucene/analysis/kuromoji/src/tools/java/org/apache/lucene/analysis/ja/util/TokenInfoDictionaryBuilder.java b/lucene/analysis/kuromoji/src/tools/java/org/apache/lucene/analysis/ja/util/TokenInfoDictionaryBuilder.java
index 475840bb37e..f0707c67b0e 100644
--- a/lucene/analysis/kuromoji/src/tools/java/org/apache/lucene/analysis/ja/util/TokenInfoDictionaryBuilder.java
+++ b/lucene/analysis/kuromoji/src/tools/java/org/apache/lucene/analysis/ja/util/TokenInfoDictionaryBuilder.java
@@ -34,6 +34,7 @@ import java.util.List;
import org.apache.lucene.analysis.ja.util.DictionaryBuilder.DictionaryFormat;
import org.apache.lucene.util.IntsRef;
+import org.apache.lucene.util.IntsRefBuilder;
import org.apache.lucene.util.fst.Builder;
import org.apache.lucene.util.fst.FST;
import org.apache.lucene.util.fst.PositiveIntOutputs;
@@ -133,7 +134,7 @@ public class TokenInfoDictionaryBuilder {
PositiveIntOutputs fstOutput = PositiveIntOutputs.getSingleton();
Builder<Long> fstBuilder = new Builder<>(FST.INPUT_TYPE.BYTE2, 0, 0, true, true, Integer.MAX_VALUE, fstOutput, true, PackedInts.DEFAULT, true, 15);
- IntsRef scratch = new IntsRef();
+ IntsRefBuilder scratch = new IntsRefBuilder();
long ord = -1; // first ord will be 0
String lastValue = null;
@@ -152,11 +153,11 @@ public class TokenInfoDictionaryBuilder {
ord++;
lastValue = token;
scratch.grow(token.length());
- scratch.length = token.length();
+ scratch.setLength(token.length());
for (int i = 0; i < token.length(); i++) {
- scratch.ints[i] = (int) token.charAt(i);
+ scratch.setIntAt(i, (int) token.charAt(i));
}
- fstBuilder.add(scratch, ord);
+ fstBuilder.add(scratch.get(), ord);
}
dictionary.addMapping((int)ord, offset);
offset = next;
diff --git a/lucene/analysis/morfologik/src/java/org/apache/lucene/analysis/morfologik/MorfologikFilter.java b/lucene/analysis/morfologik/src/java/org/apache/lucene/analysis/morfologik/MorfologikFilter.java
index 56c16141663..ff54b413072 100644
--- a/lucene/analysis/morfologik/src/java/org/apache/lucene/analysis/morfologik/MorfologikFilter.java
+++ b/lucene/analysis/morfologik/src/java/org/apache/lucene/analysis/morfologik/MorfologikFilter.java
@@ -48,7 +48,7 @@ public class MorfologikFilter extends TokenFilter {
private final PositionIncrementAttribute posIncrAtt = addAttribute(PositionIncrementAttribute.class);
private final KeywordAttribute keywordAttr = addAttribute(KeywordAttribute.class);
- private final CharsRef scratch = new CharsRef(0);
+ private final CharsRefBuilder scratch = new CharsRefBuilder();
private final CharacterUtils charUtils = CharacterUtils.getInstance();
private State current;
@@ -151,16 +151,17 @@ public class MorfologikFilter extends TokenFilter {
* Convert to lowercase in-place.
*/
private CharSequence toLowercase(CharSequence chs) {
- final int length = scratch.length = chs.length();
+ final int length = chs.length();
+ scratch.setLength(length);
scratch.grow(length);
- char buffer[] = scratch.chars;
+ char buffer[] = scratch.chars();
for (int i = 0; i < length;) {
i += Character.toChars(
Character.toLowerCase(charUtils.codePointAt(chs, i)), buffer, i);
}
- return scratch;
+ return scratch.get();
}
/** Resets stems accumulator and hands over to superclass. */
diff --git a/lucene/classification/src/java/org/apache/lucene/classification/BooleanPerceptronClassifier.java b/lucene/classification/src/java/org/apache/lucene/classification/BooleanPerceptronClassifier.java
index 5eddf473418..2942dbae605 100644
--- a/lucene/classification/src/java/org/apache/lucene/classification/BooleanPerceptronClassifier.java
+++ b/lucene/classification/src/java/org/apache/lucene/classification/BooleanPerceptronClassifier.java
@@ -33,7 +33,9 @@ import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.WildcardQuery;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.IntsRef;
+import org.apache.lucene.util.IntsRefBuilder;
import org.apache.lucene.util.fst.Builder;
import org.apache.lucene.util.fst.FST;
import org.apache.lucene.util.fst.PositiveIntOutputs;
@@ -234,11 +236,11 @@ public class BooleanPerceptronClassifier implements Classifier<Boolean> {
private void updateFST(SortedMap<String,Double> weights) throws IOException {
PositiveIntOutputs outputs = PositiveIntOutputs.getSingleton();
Builder<Long> fstBuilder = new Builder<>(FST.INPUT_TYPE.BYTE1, outputs);
- BytesRef scratchBytes = new BytesRef();
- IntsRef scratchInts = new IntsRef();
+ BytesRefBuilder scratchBytes = new BytesRefBuilder();
+ IntsRefBuilder scratchInts = new IntsRefBuilder();
for (Map.Entry<String,Double> entry : weights.entrySet()) {
scratchBytes.copyChars(entry.getKey());
- fstBuilder.add(Util.toIntsRef(scratchBytes, scratchInts), entry
+ fstBuilder.add(Util.toIntsRef(scratchBytes.get(), scratchInts), entry
.getValue().longValue());
}
fst = fstBuilder.finish();
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/blockterms/BlockTermsReader.java b/lucene/codecs/src/java/org/apache/lucene/codecs/blockterms/BlockTermsReader.java
index 0e1240a06bf..64969029390 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/blockterms/BlockTermsReader.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/blockterms/BlockTermsReader.java
@@ -45,6 +45,7 @@ import org.apache.lucene.util.Accountable;
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.DoubleBarrelLRUCache;
import org.apache.lucene.util.RamUsageEstimator;
@@ -315,7 +316,7 @@ public class BlockTermsReader extends FieldsProducer {
private final boolean doOrd;
private final FieldAndTerm fieldTerm = new FieldAndTerm();
private final TermsIndexReaderBase.FieldIndexEnum indexEnum;
- private final BytesRef term = new BytesRef();
+ private final BytesRefBuilder term = new BytesRefBuilder();
/* This is true if indexEnum is "still" seek'd to the index term
for the current term. We set it to true on seeking, and then it
@@ -396,7 +397,7 @@ public class BlockTermsReader extends FieldsProducer {
// is after current term but before next index term:
if (indexIsCurrent) {
- final int cmp = BytesRef.getUTF8SortedAsUnicodeComparator().compare(term, target);
+ final int cmp = BytesRef.getUTF8SortedAsUnicodeComparator().compare(term.get(), target);
if (cmp == 0) {
// Already at the requested term
@@ -471,7 +472,7 @@ public class BlockTermsReader extends FieldsProducer {
// First, see if target term matches common prefix
// in this block:
if (common < termBlockPrefix) {
- final int cmp = (term.bytes[common]&0xFF) - (target.bytes[target.offset + common]&0xFF);
+ final int cmp = (term.byteAt(common)&0xFF) - (target.bytes[target.offset + common]&0xFF);
if (cmp < 0) {
// TODO: maybe we should store common prefix
@@ -490,11 +491,9 @@ public class BlockTermsReader extends FieldsProducer {
termSuffixesReader.skipBytes(termSuffixesReader.readVInt());
}
final int suffix = termSuffixesReader.readVInt();
- term.length = termBlockPrefix + suffix;
- if (term.bytes.length < term.length) {
- term.grow(term.length);
- }
- termSuffixesReader.readBytes(term.bytes, termBlockPrefix, suffix);
+ term.setLength(termBlockPrefix + suffix);
+ term.grow(term.length());
+ termSuffixesReader.readBytes(term.bytes(), termBlockPrefix, suffix);
}
state.ord++;
@@ -511,11 +510,9 @@ public class BlockTermsReader extends FieldsProducer {
assert state.termBlockOrd == 0;
final int suffix = termSuffixesReader.readVInt();
- term.length = termBlockPrefix + suffix;
- if (term.bytes.length < term.length) {
- term.grow(term.length);
- }
- termSuffixesReader.readBytes(term.bytes, termBlockPrefix, suffix);
+ term.setLength(termBlockPrefix + suffix);
+ term.grow(term.length());
+ termSuffixesReader.readBytes(term.bytes(), termBlockPrefix, suffix);
return SeekStatus.NOT_FOUND;
} else {
common++;
@@ -548,22 +545,18 @@ public class BlockTermsReader extends FieldsProducer {
} else if (cmp > 0) {
// Done! Current term is after target. Stop
// here, fill in real term, return NOT_FOUND.
- term.length = termBlockPrefix + suffix;
- if (term.bytes.length < term.length) {
- term.grow(term.length);
- }
- termSuffixesReader.readBytes(term.bytes, termBlockPrefix, suffix);
+ term.setLength(termBlockPrefix + suffix);
+ term.grow(term.length());
+ termSuffixesReader.readBytes(term.bytes(), termBlockPrefix, suffix);
//System.out.println(" NOT_FOUND");
return SeekStatus.NOT_FOUND;
}
}
if (!next && target.length <= termLen) {
- term.length = termBlockPrefix + suffix;
- if (term.bytes.length < term.length) {
- term.grow(term.length);
- }
- termSuffixesReader.readBytes(term.bytes, termBlockPrefix, suffix);
+ term.setLength(termBlockPrefix + suffix);
+ term.grow(term.length());
+ termSuffixesReader.readBytes(term.bytes(), termBlockPrefix, suffix);
if (target.length == termLen) {
// Done! Exact match. Stop here, fill in
@@ -578,11 +571,9 @@ public class BlockTermsReader extends FieldsProducer {
if (state.termBlockOrd == blockTermCount) {
// Must pre-fill term for next block's common prefix
- term.length = termBlockPrefix + suffix;
- if (term.bytes.length < term.length) {
- term.grow(term.length);
- }
- termSuffixesReader.readBytes(term.bytes, termBlockPrefix, suffix);
+ term.setLength(termBlockPrefix + suffix);
+ term.grow(term.length());
+ termSuffixesReader.readBytes(term.bytes(), termBlockPrefix, suffix);
break;
} else {
termSuffixesReader.skipBytes(suffix);
@@ -653,23 +644,21 @@ public class BlockTermsReader extends FieldsProducer {
final int suffix = termSuffixesReader.readVInt();
//System.out.println(" suffix=" + suffix);
- term.length = termBlockPrefix + suffix;
- if (term.bytes.length < term.length) {
- term.grow(term.length);
- }
- termSuffixesReader.readBytes(term.bytes, termBlockPrefix, suffix);
+ term.setLength(termBlockPrefix + suffix);
+ term.grow(term.length());
+ termSuffixesReader.readBytes(term.bytes(), termBlockPrefix, suffix);
state.termBlockOrd++;
// NOTE: meaningless in the non-ord case
state.ord++;
//System.out.println(" return term=" + fieldInfo.name + ":" + term.utf8ToString() + " " + term + " tbOrd=" + state.termBlockOrd);
- return term;
+ return term.get();
}
@Override
public BytesRef term() {
- return term;
+ return term.get();
}
@Override
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/blockterms/BlockTermsWriter.java b/lucene/codecs/src/java/org/apache/lucene/codecs/blockterms/BlockTermsWriter.java
index 638598a9758..1d31c3e3f99 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/blockterms/BlockTermsWriter.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/blockterms/BlockTermsWriter.java
@@ -20,6 +20,7 @@ package org.apache.lucene.codecs.blockterms;
import java.io.Closeable;
import java.io.IOException;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.List;
import org.apache.lucene.codecs.BlockTermState;
@@ -39,6 +40,7 @@ import org.apache.lucene.store.IndexOutput;
import org.apache.lucene.store.RAMOutputStream;
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.FixedBitSet;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.RamUsageEstimator;
@@ -200,7 +202,7 @@ public class BlockTermsWriter extends FieldsConsumer implements Closeable {
}
private static class TermEntry {
- public final BytesRef term = new BytesRef();
+ public final BytesRefBuilder term = new BytesRefBuilder();
public BlockTermState state;
}
@@ -237,7 +239,7 @@ public class BlockTermsWriter extends FieldsConsumer implements Closeable {
this.longsSize = postingsWriter.setField(fieldInfo);
}
- private final BytesRef lastPrevTerm = new BytesRef();
+ private final BytesRefBuilder lastPrevTerm = new BytesRefBuilder();
void write(BytesRef text, TermsEnum termsEnum) throws IOException {
@@ -267,12 +269,10 @@ public class BlockTermsWriter extends FieldsConsumer implements Closeable {
}
if (pendingTerms.length == pendingCount) {
- final TermEntry[] newArray = new TermEntry[ArrayUtil.oversize(pendingCount+1, RamUsageEstimator.NUM_BYTES_OBJECT_REF)];
- System.arraycopy(pendingTerms, 0, newArray, 0, pendingCount);
- for(int i=pendingCount;i<newArray.length;i++) {
- newArray[i] = new TermEntry();
+ pendingTerms = Arrays.copyOf(pendingTerms, ArrayUtil.oversize(pendingCount+1, RamUsageEstimator.NUM_BYTES_OBJECT_REF));
+ for(int i=pendingCount;i<pendingTerms.length;i++) {
+ pendingTerms[i] = new TermEntry();
}
- pendingTerms = newArray;
}
final TermEntry te = pendingTerms[pendingCount];
te.term.copyBytes(text);
@@ -330,11 +330,11 @@ public class BlockTermsWriter extends FieldsConsumer implements Closeable {
// First pass: compute common prefix for all terms
// in the block, against term before first term in
// this block:
- int commonPrefix = sharedPrefix(lastPrevTerm, pendingTerms[0].term);
+ int commonPrefix = sharedPrefix(lastPrevTerm.get(), pendingTerms[0].term.get());
for(int termCount=1;termCount<pendingCount;termCount++) {
commonPrefix = Math.min(commonPrefix,
- sharedPrefix(lastPrevTerm,
- pendingTerms[termCount].term));
+ sharedPrefix(lastPrevTerm.get(),
+ pendingTerms[termCount].term.get()));
}
out.writeVInt(pendingCount);
@@ -342,11 +342,11 @@ public class BlockTermsWriter extends FieldsConsumer implements Closeable {
// 2nd pass: write suffixes, as separate byte[] blob
for(int termCount=0;termCount<pendingCount;termCount++) {
- final int suffix = pendingTerms[termCount].term.length - commonPrefix;
+ final int suffix = pendingTerms[termCount].term.length() - commonPrefix;
// TODO: cutover to better intblock codec, instead
// of interleaving here:
bytesWriter.writeVInt(suffix);
- bytesWriter.writeBytes(pendingTerms[termCount].term.bytes, commonPrefix, suffix);
+ bytesWriter.writeBytes(pendingTerms[termCount].term.bytes(), commonPrefix, suffix);
}
out.writeVInt((int) bytesWriter.getFilePointer());
bytesWriter.writeTo(out);
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/blockterms/FixedGapTermsIndexWriter.java b/lucene/codecs/src/java/org/apache/lucene/codecs/blockterms/FixedGapTermsIndexWriter.java
index 3ddfc4141ea..729f4edf646 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/blockterms/FixedGapTermsIndexWriter.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/blockterms/FixedGapTermsIndexWriter.java
@@ -25,6 +25,7 @@ import org.apache.lucene.index.FieldInfo;
import org.apache.lucene.index.IndexFileNames;
import org.apache.lucene.index.SegmentWriteState;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.packed.MonotonicBlockPackedWriter;
import org.apache.lucene.util.packed.PackedInts;
@@ -131,7 +132,7 @@ public class FixedGapTermsIndexWriter extends TermsIndexWriterBase {
private RAMOutputStream addressBuffer = new RAMOutputStream();
private MonotonicBlockPackedWriter termAddresses = new MonotonicBlockPackedWriter(addressBuffer, BLOCKSIZE);
- private final BytesRef lastTerm = new BytesRef();
+ private final BytesRefBuilder lastTerm = new BytesRefBuilder();
SimpleFieldWriter(FieldInfo fieldInfo, long termsFilePointer) {
this.fieldInfo = fieldInfo;
@@ -163,7 +164,7 @@ public class FixedGapTermsIndexWriter extends TermsIndexWriterBase {
@Override
public void add(BytesRef text, TermStats stats, long termsFilePointer) throws IOException {
- final int indexedTermLength = indexedTermPrefixLength(lastTerm, text);
+ final int indexedTermLength = indexedTermPrefixLength(lastTerm.get(), text);
//System.out.println("FGW: add text=" + text.utf8ToString() + " " + text + " fp=" + termsFilePointer);
// write only the min prefix that shows the diff
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/blockterms/VariableGapTermsIndexWriter.java b/lucene/codecs/src/java/org/apache/lucene/codecs/blockterms/VariableGapTermsIndexWriter.java
index 33824481bc2..4990c275623 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/blockterms/VariableGapTermsIndexWriter.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/blockterms/VariableGapTermsIndexWriter.java
@@ -29,8 +29,10 @@ import org.apache.lucene.index.IndexFileNames;
import org.apache.lucene.index.SegmentWriteState;
import org.apache.lucene.store.IndexOutput;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.IntsRef;
+import org.apache.lucene.util.IntsRefBuilder;
import org.apache.lucene.util.fst.Builder;
import org.apache.lucene.util.fst.FST;
import org.apache.lucene.util.fst.PositiveIntOutputs;
@@ -231,7 +233,7 @@ public class VariableGapTermsIndexWriter extends TermsIndexWriterBase {
FST<Long> fst;
final long indexStart;
- private final BytesRef lastTerm = new BytesRef();
+ private final BytesRefBuilder lastTerm = new BytesRefBuilder();
private boolean first = true;
public FSTFieldWriter(FieldInfo fieldInfo, long termsFilePointer) throws IOException {
@@ -261,7 +263,7 @@ public class VariableGapTermsIndexWriter extends TermsIndexWriterBase {
}
}
- private final IntsRef scratchIntsRef = new IntsRef();
+ private final IntsRefBuilder scratchIntsRef = new IntsRefBuilder();
@Override
public void add(BytesRef text, TermStats stats, long termsFilePointer) throws IOException {
@@ -271,7 +273,7 @@ public class VariableGapTermsIndexWriter extends TermsIndexWriterBase {
return;
}
final int lengthSave = text.length;
- text.length = indexedTermPrefixLength(lastTerm, text);
+ text.length = indexedTermPrefixLength(lastTerm.get(), text);
try {
fstBuilder.add(Util.toIntsRef(text, scratchIntsRef), termsFilePointer);
} finally {
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsBlockTreeTermsWriter.java b/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsBlockTreeTermsWriter.java
index afa6ea2229a..b8fe071f473 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsBlockTreeTermsWriter.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsBlockTreeTermsWriter.java
@@ -39,9 +39,11 @@ import org.apache.lucene.store.IndexOutput;
import org.apache.lucene.store.RAMOutputStream;
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.FixedBitSet;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.IntsRef;
+import org.apache.lucene.util.IntsRefBuilder;
import org.apache.lucene.util.StringHelper;
import org.apache.lucene.util.fst.Builder;
import org.apache.lucene.util.fst.BytesRefFSTEnum;
@@ -340,7 +342,7 @@ public final class OrdsBlockTreeTermsWriter extends FieldsConsumer {
return "BLOCK: " + brToString(prefix);
}
- public void compileIndex(List<PendingBlock> blocks, RAMOutputStream scratchBytes, IntsRef scratchIntsRef) throws IOException {
+ public void compileIndex(List<PendingBlock> blocks, RAMOutputStream scratchBytes, IntsRefBuilder scratchIntsRef) throws IOException {
assert (isFloor && blocks.size() > 1) || (isFloor == false && blocks.size() == 1): "isFloor=" + isFloor + " blocks=" + blocks;
assert this == blocks.get(0);
@@ -418,7 +420,7 @@ public final class OrdsBlockTreeTermsWriter extends FieldsConsumer {
// TODO: maybe we could add bulk-add method to
// Builder? Takes FST and unions it w/ current
// FST.
- private void append(Builder<Output> builder, FST<Output> subIndex, long termOrdOffset, IntsRef scratchIntsRef) throws IOException {
+ private void append(Builder<Output> builder, FST<Output> subIndex, long termOrdOffset, IntsRefBuilder scratchIntsRef) throws IOException {
final BytesRefFSTEnum<Output> subIndexEnum = new BytesRefFSTEnum<>(subIndex);
BytesRefFSTEnum.InputOutput<Output> indexEnt;
while ((indexEnt = subIndexEnum.next()) != null) {
@@ -435,7 +437,7 @@ public final class OrdsBlockTreeTermsWriter extends FieldsConsumer {
}
private final RAMOutputStream scratchBytes = new RAMOutputStream();
- private final IntsRef scratchIntsRef = new IntsRef();
+ private final IntsRefBuilder scratchIntsRef = new IntsRefBuilder();
class TermsWriter {
private final FieldInfo fieldInfo;
@@ -451,7 +453,7 @@ public final class OrdsBlockTreeTermsWriter extends FieldsConsumer {
// startsByPrefix[0] is the index into pending for the first
// term/sub-block starting with 't'. We use this to figure out when
// to write a new block:
- private final BytesRef lastTerm = new BytesRef();
+ private final BytesRefBuilder lastTerm = new BytesRefBuilder();
private int[] prefixStarts = new int[8];
private final long[] longs;
@@ -589,7 +591,7 @@ public final class OrdsBlockTreeTermsWriter extends FieldsConsumer {
boolean hasFloorLeadLabel = isFloor && floorLeadLabel != -1;
final BytesRef prefix = new BytesRef(prefixLength + (hasFloorLeadLabel ? 1 : 0));
- System.arraycopy(lastTerm.bytes, 0, prefix.bytes, 0, prefixLength);
+ System.arraycopy(lastTerm.bytes(), 0, prefix.bytes, 0, prefixLength);
prefix.length = prefixLength;
// Write block header:
@@ -818,18 +820,18 @@ public final class OrdsBlockTreeTermsWriter extends FieldsConsumer {
/** Pushes the new term to the top of the stack, and writes new blocks. */
private void pushTerm(BytesRef text) throws IOException {
- int limit = Math.min(lastTerm.length, text.length);
+ int limit = Math.min(lastTerm.length(), text.length);
// Find common prefix between last term and current term:
int pos = 0;
- while (pos < limit && lastTerm.bytes[pos] == text.bytes[text.offset+pos]) {
+ while (pos < limit && lastTerm.byteAt(pos) == text.bytes[text.offset+pos]) {
pos++;
}
// if (DEBUG) System.out.println(" shared=" + pos + " lastTerm.length=" + lastTerm.length);
// Close the "abandoned" suffix now:
- for(int i=lastTerm.length-1;i>=pos;i--) {
+ for(int i=lastTerm.length()-1;i>=pos;i--) {
// How many items on top of the stack share the current suffix
// we are closing:
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsSegmentTermsEnum.java b/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsSegmentTermsEnum.java
index e3b19356055..9d43ca3d46a 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsSegmentTermsEnum.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsSegmentTermsEnum.java
@@ -35,7 +35,9 @@ import org.apache.lucene.store.IndexInput;
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.IntsRef;
+import org.apache.lucene.util.IntsRefBuilder;
import org.apache.lucene.util.RamUsageEstimator;
import org.apache.lucene.util.fst.FST;
import org.apache.lucene.util.fst.Util;
@@ -64,7 +66,7 @@ public final class OrdsSegmentTermsEnum extends TermsEnum {
// assert only:
private boolean eof;
- final BytesRef term = new BytesRef();
+ final BytesRefBuilder term = new BytesRefBuilder();
private final FST.BytesReader fstReader;
@SuppressWarnings({"rawtypes","unchecked"}) private FST.Arc<Output>[] arcs =
@@ -239,9 +241,7 @@ public final class OrdsSegmentTermsEnum extends TermsEnum {
throw new IllegalStateException("terms index was not loaded");
}
- if (term.bytes.length <= target.length) {
- term.bytes = ArrayUtil.grow(term.bytes, 1+target.length);
- }
+ term.grow(1+target.length);
assert clearEOF();
@@ -277,7 +277,7 @@ public final class OrdsSegmentTermsEnum extends TermsEnum {
targetUpto = 0;
OrdsSegmentTermsEnumFrame lastFrame = stack[0];
- assert validIndexPrefix <= term.length;
+ assert validIndexPrefix <= term.length();
final int targetLimit = Math.min(target.length, validIndexPrefix);
@@ -288,7 +288,7 @@ public final class OrdsSegmentTermsEnum extends TermsEnum {
// First compare up to valid seek frames:
while (targetUpto < targetLimit) {
- cmp = (term.bytes[targetUpto]&0xFF) - (target.bytes[target.offset + targetUpto]&0xFF);
+ cmp = (term.byteAt(targetUpto)&0xFF) - (target.bytes[target.offset + targetUpto]&0xFF);
// if (DEBUG) {
// System.out.println(" cycle targetUpto=" + targetUpto + " (vs limit=" + targetLimit + ") cmp=" + cmp + " (targetLabel=" + (char) (target.bytes[target.offset + targetUpto]) + " vs termLabel=" + (char) (term.bytes[targetUpto]) + ")" + " arc.output=" + arc.output + " output=" + output);
// }
@@ -313,9 +313,9 @@ public final class OrdsSegmentTermsEnum extends TermsEnum {
// don't save arc/output/frame; we only do this
// to find out if the target term is before,
// equal or after the current term
- final int targetLimit2 = Math.min(target.length, term.length);
+ final int targetLimit2 = Math.min(target.length, term.length());
while (targetUpto < targetLimit2) {
- cmp = (term.bytes[targetUpto]&0xFF) - (target.bytes[target.offset + targetUpto]&0xFF);
+ cmp = (term.byteAt(targetUpto)&0xFF) - (target.bytes[target.offset + targetUpto]&0xFF);
// if (DEBUG) {
// System.out.println(" cycle2 targetUpto=" + targetUpto + " (vs limit=" + targetLimit + ") cmp=" + cmp + " (targetLabel=" + (char) (target.bytes[target.offset + targetUpto]) + " vs termLabel=" + (char) (term.bytes[targetUpto]) + ")");
// }
@@ -326,7 +326,7 @@ public final class OrdsSegmentTermsEnum extends TermsEnum {
}
if (cmp == 0) {
- cmp = term.length - target.length;
+ cmp = term.length() - target.length;
}
targetUpto = targetUptoMid;
}
@@ -353,7 +353,7 @@ public final class OrdsSegmentTermsEnum extends TermsEnum {
currentFrame.rewind();
} else {
// Target is exactly the same as current term
- assert term.length == target.length;
+ assert term.length() == target.length;
if (termExists) {
// if (DEBUG) {
// System.out.println(" target is same as current; return true");
@@ -418,8 +418,8 @@ public final class OrdsSegmentTermsEnum extends TermsEnum {
if (!currentFrame.hasTerms) {
termExists = false;
- term.bytes[targetUpto] = (byte) targetLabel;
- term.length = 1+targetUpto;
+ term.setByteAt(targetUpto, (byte) targetLabel);
+ term.setLength(1+targetUpto);
// if (DEBUG) {
// System.out.println(" FAST NOT_FOUND term=" + brToString(term));
// }
@@ -443,7 +443,7 @@ public final class OrdsSegmentTermsEnum extends TermsEnum {
} else {
// Follow this arc
arc = nextArc;
- term.bytes[targetUpto] = (byte) targetLabel;
+ term.setByteAt(targetUpto, (byte) targetLabel);
// Aggregate output as we go:
assert arc.output != null;
if (arc.output != OrdsBlockTreeTermsWriter.NO_OUTPUT) {
@@ -471,7 +471,7 @@ public final class OrdsSegmentTermsEnum extends TermsEnum {
// Target term is entirely contained in the index:
if (!currentFrame.hasTerms) {
termExists = false;
- term.length = targetUpto;
+ term.setLength(targetUpto);
// if (DEBUG) {
// System.out.println(" FAST NOT_FOUND term=" + brToString(term));
// }
@@ -501,9 +501,7 @@ public final class OrdsSegmentTermsEnum extends TermsEnum {
throw new IllegalStateException("terms index was not loaded");
}
- if (term.bytes.length <= target.length) {
- term.bytes = ArrayUtil.grow(term.bytes, 1+target.length);
- }
+ term.grow(1+target.length);
assert clearEOF();
@@ -537,7 +535,7 @@ public final class OrdsSegmentTermsEnum extends TermsEnum {
targetUpto = 0;
OrdsSegmentTermsEnumFrame lastFrame = stack[0];
- assert validIndexPrefix <= term.length;
+ assert validIndexPrefix <= term.length();
final int targetLimit = Math.min(target.length, validIndexPrefix);
@@ -548,7 +546,7 @@ public final class OrdsSegmentTermsEnum extends TermsEnum {
// First compare up to valid seek frames:
while (targetUpto < targetLimit) {
- cmp = (term.bytes[targetUpto]&0xFF) - (target.bytes[target.offset + targetUpto]&0xFF);
+ cmp = (term.byteAt(targetUpto)&0xFF) - (target.bytes[target.offset + targetUpto]&0xFF);
//if (DEBUG) {
//System.out.println(" cycle targetUpto=" + targetUpto + " (vs limit=" + targetLimit + ") cmp=" + cmp + " (targetLabel=" + (char) (target.bytes[target.offset + targetUpto]) + " vs termLabel=" + (char) (term.bytes[targetUpto]) + ")" + " arc.output=" + arc.output + " output=" + output);
//}
@@ -576,9 +574,9 @@ public final class OrdsSegmentTermsEnum extends TermsEnum {
final int targetUptoMid = targetUpto;
// Second compare the rest of the term, but
// don't save arc/output/frame:
- final int targetLimit2 = Math.min(target.length, term.length);
+ final int targetLimit2 = Math.min(target.length, term.length());
while (targetUpto < targetLimit2) {
- cmp = (term.bytes[targetUpto]&0xFF) - (target.bytes[target.offset + targetUpto]&0xFF);
+ cmp = (term.byteAt(targetUpto)&0xFF) - (target.bytes[target.offset + targetUpto]&0xFF);
//if (DEBUG) {
//System.out.println(" cycle2 targetUpto=" + targetUpto + " (vs limit=" + targetLimit + ") cmp=" + cmp + " (targetLabel=" + (char) (target.bytes[target.offset + targetUpto]) + " vs termLabel=" + (char) (term.bytes[targetUpto]) + ")");
//}
@@ -589,7 +587,7 @@ public final class OrdsSegmentTermsEnum extends TermsEnum {
}
if (cmp == 0) {
- cmp = term.length - target.length;
+ cmp = term.length() - target.length;
}
targetUpto = targetUptoMid;
}
@@ -616,7 +614,7 @@ public final class OrdsSegmentTermsEnum extends TermsEnum {
currentFrame.rewind();
} else {
// Target is exactly the same as current term
- assert term.length == target.length;
+ assert term.length() == target.length;
if (termExists) {
//if (DEBUG) {
//System.out.println(" target is same as current; return FOUND");
@@ -702,7 +700,7 @@ public final class OrdsSegmentTermsEnum extends TermsEnum {
}
} else {
// Follow this arc
- term.bytes[targetUpto] = (byte) targetLabel;
+ term.setByteAt(targetUpto, (byte) targetLabel);
arc = nextArc;
// Aggregate output as we go:
assert arc.output != null;
@@ -762,7 +760,7 @@ public final class OrdsSegmentTermsEnum extends TermsEnum {
while(true) {
OrdsSegmentTermsEnumFrame f = getFrame(ord);
assert f != null;
- final BytesRef prefix = new BytesRef(term.bytes, 0, f.prefix);
+ final BytesRef prefix = new BytesRef(term.bytes(), 0, f.prefix);
if (f.nextEnt == -1) {
out.println(" frame " + (isSeekFrame ? "(seek)" : "(next)") + " ord=" + ord + " fp=" + f.fp + (f.isFloor ? (" (fpOrig=" + f.fpOrig + ")") : "") + " prefixLen=" + f.prefix + " prefix=" + brToString(prefix) + (f.nextEnt == -1 ? "" : (" (of " + f.entCount + ")")) + " hasTerms=" + f.hasTerms + " isFloor=" + f.isFloor + " code=" + ((f.fp<<OrdsBlockTreeTermsWriter.OUTPUT_FLAGS_NUM_BITS) + (f.hasTerms ? OrdsBlockTreeTermsWriter.OUTPUT_FLAG_HAS_TERMS:0) + (f.isFloor ? OrdsBlockTreeTermsWriter.OUTPUT_FLAG_IS_FLOOR:0)) + " isLastInFloor=" + f.isLastInFloor + " mdUpto=" + f.metaDataUpto + " tbOrd=" + f.getTermBlockOrd() + " termOrd=" + f.termOrd);
} else {
@@ -770,8 +768,8 @@ public final class OrdsSegmentTermsEnum extends TermsEnum {
}
if (fr.index != null) {
assert !isSeekFrame || f.arc != null: "isSeekFrame=" + isSeekFrame + " f.arc=" + f.arc;
- if (f.prefix > 0 && isSeekFrame && f.arc.label != (term.bytes[f.prefix-1]&0xFF)) {
- out.println(" broken seek state: arc.label=" + (char) f.arc.label + " vs term byte=" + (char) (term.bytes[f.prefix-1]&0xFF));
+ if (f.prefix > 0 && isSeekFrame && f.arc.label != (term.byteAt(f.prefix-1)&0xFF)) {
+ out.println(" broken seek state: arc.label=" + (char) f.arc.label + " vs term byte=" + (char) (term.byteAt(f.prefix-1)&0xFF));
throw new RuntimeException("seek state is broken");
}
Output output = Util.get(fr.index, prefix);
@@ -836,7 +834,7 @@ public final class OrdsSegmentTermsEnum extends TermsEnum {
// this method catches up all internal state so next()
// works properly:
// if (DEBUG) System.out.println(" re-seek to pending term=" + term.utf8ToString() + " " + term);
- final boolean result = seekExact(term);
+ final boolean result = seekExact(term.get());
assert result;
}
@@ -849,7 +847,7 @@ public final class OrdsSegmentTermsEnum extends TermsEnum {
if (currentFrame.ord == 0) {
//if (DEBUG) System.out.println(" return null");
assert setEOF();
- term.length = 0;
+ term.setLength(0);
validIndexPrefix = 0;
currentFrame.rewind();
termExists = false;
@@ -862,7 +860,7 @@ public final class OrdsSegmentTermsEnum extends TermsEnum {
if (currentFrame.nextEnt == -1 || currentFrame.lastSubFP != lastFP) {
// We popped into a frame that's not loaded
// yet or not scan'd to the right entry
- currentFrame.scanToFloorFrame(term);
+ currentFrame.scanToFloorFrame(term.get());
currentFrame.loadBlock();
currentFrame.scanToSubBlock(lastFP);
}
@@ -881,7 +879,7 @@ public final class OrdsSegmentTermsEnum extends TermsEnum {
if (currentFrame.next()) {
// Push to new block:
//if (DEBUG) System.out.println(" push frame");
- currentFrame = pushFrame(null, currentFrame.lastSubFP, term.length, prevTermOrd);
+ currentFrame = pushFrame(null, currentFrame.lastSubFP, term.length(), prevTermOrd);
// This is a "next" frame -- even if it's
// floor'd we must pretend it isn't so we don't
// try to scan to the right floor frame:
@@ -891,7 +889,7 @@ public final class OrdsSegmentTermsEnum extends TermsEnum {
} else {
//if (DEBUG) System.out.println(" return term=" + term.utf8ToString() + " " + term + " currentFrame.ord=" + currentFrame.ord);
positioned = true;
- return term;
+ return term.get();
}
}
}
@@ -899,7 +897,7 @@ public final class OrdsSegmentTermsEnum extends TermsEnum {
@Override
public BytesRef term() {
assert !eof;
- return term;
+ return term.get();
}
@Override
@@ -956,7 +954,7 @@ public final class OrdsSegmentTermsEnum extends TermsEnum {
// System.out.println("BTTR.seekExact termState seg=" + segment + " target=" + target.utf8ToString() + " " + target + " state=" + otherState);
// }
assert clearEOF();
- if (target.compareTo(term) != 0 || !termExists) {
+ if (target.compareTo(term.get()) != 0 || !termExists) {
assert otherState != null && otherState instanceof BlockTermState;
BlockTermState blockState = (BlockTermState) otherState;
currentFrame = staticFrame;
@@ -996,9 +994,7 @@ public final class OrdsSegmentTermsEnum extends TermsEnum {
// First do reverse lookup in the index to find the block that holds this term:
InputOutput io = getByOutput(targetOrd);
- if (term.bytes.length < io.input.length) {
- term.bytes = ArrayUtil.grow(term.bytes, io.input.length);
- }
+ term.grow(io.input.length);
Util.toBytesRef(io.input, term);
if (io.input.length == 0) {
@@ -1054,7 +1050,7 @@ public final class OrdsSegmentTermsEnum extends TermsEnum {
/** Specialized getByOutput that can understand the ranges (startOrd to endOrd) we use here, not just startOrd. */
private InputOutput getByOutput(long targetOrd) throws IOException {
- final IntsRef result = new IntsRef();
+ final IntsRefBuilder result = new IntsRefBuilder();
fr.index.getFirstArc(arc);
Output output = arc.output;
@@ -1086,9 +1082,7 @@ public final class OrdsSegmentTermsEnum extends TermsEnum {
if (FST.targetHasArcs(arc)) {
// System.out.println(" targetHasArcs");
- if (result.ints.length == upto) {
- result.grow(1+upto);
- }
+ result.grow(1+upto);
fr.index.readFirstRealTargetArc(arc.target, arc, fstReader);
@@ -1128,9 +1122,9 @@ public final class OrdsSegmentTermsEnum extends TermsEnum {
// Keep recursing
arc.arcIdx = mid-1;
} else {
- result.length = bestUpto;
+ result.setLength(bestUpto);
InputOutput io = new InputOutput();
- io.input = result;
+ io.input = result.get();
io.output = bestOutput;
// System.out.println(" ret0=" + io);
return io;
@@ -1139,7 +1133,7 @@ public final class OrdsSegmentTermsEnum extends TermsEnum {
fr.index.readNextRealArc(arc, fstReader);
// Recurse on this arc:
- result.ints[upto++] = arc.label;
+ result.setIntAt(upto++, arc.label);
output = OrdsBlockTreeTermsWriter.FST_OUTPUTS.add(output, arc.output);
} else {
@@ -1157,12 +1151,12 @@ public final class OrdsSegmentTermsEnum extends TermsEnum {
if (targetOrd >= minArcOutput.startOrd && targetOrd <= endOrd) {
// Recurse on this arc:
output = minArcOutput;
- result.ints[upto++] = arc.label;
+ result.setIntAt(upto++, arc.label);
break;
} else if (targetOrd < endOrd || arc.isLast()) {
- result.length = bestUpto;
+ result.setLength(bestUpto);
InputOutput io = new InputOutput();
- io.input = result;
+ io.input = result.get();
assert bestOutput != null;
io.output = bestOutput;
// System.out.println(" ret2=" + io);
@@ -1175,9 +1169,9 @@ public final class OrdsSegmentTermsEnum extends TermsEnum {
}
}
} else {
- result.length = bestUpto;
+ result.setLength(bestUpto);
InputOutput io = new InputOutput();
- io.input = result;
+ io.input = result.get();
io.output = bestOutput;
// System.out.println(" ret3=" + io);
return io;
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsSegmentTermsEnumFrame.java b/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsSegmentTermsEnumFrame.java
index 17911425e88..db6c099124c 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsSegmentTermsEnumFrame.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/blocktreeords/OrdsSegmentTermsEnumFrame.java
@@ -296,11 +296,9 @@ final class OrdsSegmentTermsEnumFrame {
termOrd++;
suffix = suffixesReader.readVInt();
startBytePos = suffixesReader.getPosition();
- ste.term.length = prefix + suffix;
- if (ste.term.bytes.length < ste.term.length) {
- ste.term.grow(ste.term.length);
- }
- suffixesReader.readBytes(ste.term.bytes, prefix, suffix);
+ ste.term.setLength(prefix + suffix);
+ ste.term.grow(ste.term.length());
+ suffixesReader.readBytes(ste.term.bytes(), prefix, suffix);
// A normal term
ste.termExists = true;
return false;
@@ -313,11 +311,9 @@ final class OrdsSegmentTermsEnumFrame {
final int code = suffixesReader.readVInt();
suffix = code >>> 1;
startBytePos = suffixesReader.getPosition();
- ste.term.length = prefix + suffix;
- if (ste.term.bytes.length < ste.term.length) {
- ste.term.grow(ste.term.length);
- }
- suffixesReader.readBytes(ste.term.bytes, prefix, suffix);
+ ste.term.setLength(prefix + suffix);
+ ste.term.grow(ste.term.length());
+ suffixesReader.readBytes(ste.term.bytes(), prefix, suffix);
if ((code & 1) == 0) {
// A normal term
ste.termExists = true;
@@ -524,7 +520,7 @@ final class OrdsSegmentTermsEnumFrame {
// Used only by assert
private boolean prefixMatches(BytesRef target) {
for(int bytePos=0;bytePos<prefix;bytePos++) {
- if (target.bytes[target.offset + bytePos] != ste.term.bytes[bytePos]) {
+ if (target.bytes[target.offset + bytePos] != ste.term.byteAt(bytePos)) {
return false;
}
}
@@ -787,7 +783,7 @@ final class OrdsSegmentTermsEnumFrame {
ste.currentFrame = ste.pushFrame(null, ste.currentFrame.lastSubFP, termLen, prevTermOrd);
ste.currentFrame.loadBlock();
while (ste.currentFrame.next()) {
- ste.currentFrame = ste.pushFrame(null, ste.currentFrame.lastSubFP, ste.term.length, prevTermOrd);
+ ste.currentFrame = ste.pushFrame(null, ste.currentFrame.lastSubFP, ste.term.length(), prevTermOrd);
ste.currentFrame.loadBlock();
}
}
@@ -831,10 +827,8 @@ final class OrdsSegmentTermsEnumFrame {
private void fillTerm() {
final int termLength = prefix + suffix;
- ste.term.length = prefix + suffix;
- if (ste.term.bytes.length < termLength) {
- ste.term.grow(termLength);
- }
- System.arraycopy(suffixBytes, startBytePos, ste.term.bytes, prefix, suffix);
+ ste.term.setLength(prefix + suffix);
+ ste.term.grow(termLength);
+ System.arraycopy(suffixBytes, startBytePos, ste.term.bytes(), prefix, suffix);
}
}
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/memory/FSTOrdTermsReader.java b/lucene/codecs/src/java/org/apache/lucene/codecs/memory/FSTOrdTermsReader.java
index c5725b516be..914852a238b 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/memory/FSTOrdTermsReader.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/memory/FSTOrdTermsReader.java
@@ -45,6 +45,7 @@ import org.apache.lucene.util.automaton.ByteRunAutomaton;
import org.apache.lucene.util.automaton.CompiledAutomaton;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.RamUsageEstimator;
import org.apache.lucene.util.fst.BytesRefFSTEnum;
@@ -277,8 +278,6 @@ public class FSTOrdTermsReader extends FieldsProducer {
// Only wraps common operations for PBF interact
abstract class BaseTermsEnum extends TermsEnum {
- /* Current term, null when enum ends or unpositioned */
- BytesRef term;
/* Current term's ord, starts from 0 */
long ord;
@@ -306,7 +305,6 @@ public class FSTOrdTermsReader extends FieldsProducer {
BaseTermsEnum() throws IOException {
this.state = postingsReader.newTermState();
- this.term = null;
this.statsReader.reset(statsBlock);
this.metaLongsReader.reset(metaLongsBlock);
this.metaBytesReader.reset(metaBytesBlock);
@@ -393,11 +391,6 @@ public class FSTOrdTermsReader extends FieldsProducer {
return state.clone();
}
- @Override
- public BytesRef term() {
- return term;
- }
-
@Override
public int docFreq() throws IOException {
return state.docFreq;
@@ -439,6 +432,8 @@ public class FSTOrdTermsReader extends FieldsProducer {
// Iterates through all terms in this field
private final class SegmentTermsEnum extends BaseTermsEnum {
final BytesRefFSTEnum<Long> fstEnum;
+ /* Current term, null when enum ends or unpositioned */
+ BytesRef term;
/* True when current term's metadata is decoded */
boolean decoded;
@@ -452,6 +447,11 @@ public class FSTOrdTermsReader extends FieldsProducer {
this.seekPending = false;
}
+ @Override
+ public BytesRef term() throws IOException {
+ return term;
+ }
+
@Override
void decodeMetaData() throws IOException {
if (!decoded && !seekPending) {
@@ -512,6 +512,9 @@ public class FSTOrdTermsReader extends FieldsProducer {
// Iterates intersect result with automaton (cannot seek!)
private final class IntersectTermsEnum extends BaseTermsEnum {
+ /* Current term, null when enum ends or unpositioned */
+ BytesRefBuilder term;
+
/* True when current term's metadata is decoded */
boolean decoded;
@@ -575,10 +578,15 @@ public class FSTOrdTermsReader extends FieldsProducer {
pending = isAccept(topFrame());
} else {
doSeekCeil(startTerm);
- pending = !startTerm.equals(term) && isValid(topFrame()) && isAccept(topFrame());
+ pending = (term == null || !startTerm.equals(term.get())) && isValid(topFrame()) && isAccept(topFrame());
}
}
+ @Override
+ public BytesRef term() throws IOException {
+ return term == null ? null : term.get();
+ }
+
@Override
void decodeMetaData() throws IOException {
if (!decoded) {
@@ -606,7 +614,7 @@ public class FSTOrdTermsReader extends FieldsProducer {
if (pending) {
pending = false;
decodeStats();
- return term;
+ return term();
}
decoded = false;
DFS:
@@ -633,7 +641,7 @@ public class FSTOrdTermsReader extends FieldsProducer {
return null;
}
decodeStats();
- return term;
+ return term();
}
BytesRef doSeekCeil(BytesRef target) throws IOException {
@@ -652,11 +660,11 @@ public class FSTOrdTermsReader extends FieldsProducer {
upto++;
}
if (upto == limit) { // got target
- return term;
+ return term();
}
if (frame != null) { // got larger term('s prefix)
pushFrame(frame);
- return isAccept(frame) ? term : next();
+ return isAccept(frame) ? term() : next();
}
while (level > 0) { // got target's prefix, advance to larger term
frame = popFrame();
@@ -665,7 +673,7 @@ public class FSTOrdTermsReader extends FieldsProducer {
}
if (loadNextFrame(topFrame(), frame) != null) {
pushFrame(frame);
- return isAccept(frame) ? term : next();
+ return isAccept(frame) ? term() : next();
}
}
return null;
@@ -777,23 +785,20 @@ public class FSTOrdTermsReader extends FieldsProducer {
return stack[level];
}
- BytesRef grow(int label) {
+ BytesRefBuilder grow(int label) {
if (term == null) {
- term = new BytesRef(new byte[16], 0, 0);
+ term = new BytesRefBuilder();
} else {
- if (term.length == term.bytes.length) {
- term.grow(term.length+1);
- }
- term.bytes[term.length++] = (byte)label;
+ term.append((byte) label);
}
return term;
}
- BytesRef shrink() {
- if (term.length == 0) {
+ BytesRefBuilder shrink() {
+ if (term.length() == 0) {
term = null;
} else {
- term.length--;
+ term.setLength(term.length() - 1);
}
return term;
}
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/memory/FSTOrdTermsWriter.java b/lucene/codecs/src/java/org/apache/lucene/codecs/memory/FSTOrdTermsWriter.java
index 5337b9bc51c..d128e9ce5e1 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/memory/FSTOrdTermsWriter.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/memory/FSTOrdTermsWriter.java
@@ -40,6 +40,7 @@ import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.FixedBitSet;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.IntsRef;
+import org.apache.lucene.util.IntsRefBuilder;
import org.apache.lucene.util.fst.Builder;
import org.apache.lucene.util.fst.FST;
import org.apache.lucene.util.fst.PositiveIntOutputs;
@@ -294,7 +295,7 @@ public class FSTOrdTermsWriter extends FieldsConsumer {
private final int longsSize;
private long numTerms;
- private final IntsRef scratchTerm = new IntsRef();
+ private final IntsRefBuilder scratchTerm = new IntsRefBuilder();
private final RAMOutputStream statsOut = new RAMOutputStream();
private final RAMOutputStream metaLongsOut = new RAMOutputStream();
private final RAMOutputStream metaBytesOut = new RAMOutputStream();
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/memory/FSTTermsReader.java b/lucene/codecs/src/java/org/apache/lucene/codecs/memory/FSTTermsReader.java
index 8c00f9afd5f..b19917c17a8 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/memory/FSTTermsReader.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/memory/FSTTermsReader.java
@@ -44,6 +44,7 @@ import org.apache.lucene.util.automaton.CompiledAutomaton;
import org.apache.lucene.util.Accountable;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.RamUsageEstimator;
import org.apache.lucene.util.fst.BytesRefFSTEnum;
@@ -244,8 +245,6 @@ public class FSTTermsReader extends FieldsProducer {
// Only wraps common operations for PBF interact
abstract class BaseTermsEnum extends TermsEnum {
- /* Current term, null when enum ends or unpositioned */
- BytesRef term;
/* Current term stats + decoded metadata (customized by PBF) */
final BlockTermState state;
@@ -260,7 +259,6 @@ public class FSTTermsReader extends FieldsProducer {
BaseTermsEnum() throws IOException {
this.state = postingsReader.newTermState();
this.bytesReader = new ByteArrayDataInput();
- this.term = null;
// NOTE: metadata will only be initialized in child class
}
@@ -270,11 +268,6 @@ public class FSTTermsReader extends FieldsProducer {
return state.clone();
}
- @Override
- public BytesRef term() {
- return term;
- }
-
@Override
public int docFreq() throws IOException {
return state.docFreq;
@@ -314,6 +307,8 @@ public class FSTTermsReader extends FieldsProducer {
// Iterates through all terms in this field
private final class SegmentTermsEnum extends BaseTermsEnum {
+ /* Current term, null when enum ends or unpositioned */
+ BytesRef term;
final BytesRefFSTEnum<FSTTermOutputs.TermData> fstEnum;
/* True when current term's metadata is decoded */
@@ -330,6 +325,11 @@ public class FSTTermsReader extends FieldsProducer {
this.meta = null;
}
+ @Override
+ public BytesRef term() throws IOException {
+ return term;
+ }
+
// Let PBF decode metadata from long[] and byte[]
@Override
void decodeMetaData() throws IOException {
@@ -395,6 +395,8 @@ public class FSTTermsReader extends FieldsProducer {
// Iterates intersect result with automaton (cannot seek!)
private final class IntersectTermsEnum extends BaseTermsEnum {
+ /* Current term, null when enum ends or unpositioned */
+ BytesRefBuilder term;
/* True when current term's metadata is decoded */
boolean decoded;
@@ -465,10 +467,15 @@ public class FSTTermsReader extends FieldsProducer {
pending = isAccept(topFrame());
} else {
doSeekCeil(startTerm);
- pending = !startTerm.equals(term) && isValid(topFrame()) && isAccept(topFrame());
+ pending = (term == null || !startTerm.equals(term.get())) && isValid(topFrame()) && isAccept(topFrame());
}
}
+ @Override
+ public BytesRef term() throws IOException {
+ return term == null ? null : term.get();
+ }
+
@Override
void decodeMetaData() throws IOException {
assert term != null;
@@ -503,7 +510,7 @@ public class FSTTermsReader extends FieldsProducer {
@Override
public SeekStatus seekCeil(BytesRef target) throws IOException {
decoded = false;
- term = doSeekCeil(target);
+ doSeekCeil(target);
loadMetaData();
if (term == null) {
return SeekStatus.END;
@@ -518,7 +525,7 @@ public class FSTTermsReader extends FieldsProducer {
if (pending) {
pending = false;
loadMetaData();
- return term;
+ return term();
}
decoded = false;
DFS:
@@ -545,7 +552,7 @@ public class FSTTermsReader extends FieldsProducer {
return null;
}
loadMetaData();
- return term;
+ return term();
}
private BytesRef doSeekCeil(BytesRef target) throws IOException {
@@ -564,11 +571,11 @@ public class FSTTermsReader extends FieldsProducer {
upto++;
}
if (upto == limit) { // got target
- return term;
+ return term();
}
if (frame != null) { // got larger term('s prefix)
pushFrame(frame);
- return isAccept(frame) ? term : next();
+ return isAccept(frame) ? term() : next();
}
while (level > 0) { // got target's prefix, advance to larger term
frame = popFrame();
@@ -577,7 +584,7 @@ public class FSTTermsReader extends FieldsProducer {
}
if (loadNextFrame(topFrame(), frame) != null) {
pushFrame(frame);
- return isAccept(frame) ? term : next();
+ return isAccept(frame) ? term() : next();
}
}
return null;
@@ -690,23 +697,20 @@ public class FSTTermsReader extends FieldsProducer {
return stack[level];
}
- BytesRef grow(int label) {
+ BytesRefBuilder grow(int label) {
if (term == null) {
- term = new BytesRef(new byte[16], 0, 0);
+ term = new BytesRefBuilder();
} else {
- if (term.length == term.bytes.length) {
- term.grow(term.length+1);
- }
- term.bytes[term.length++] = (byte)label;
+ term.append((byte)label);
}
return term;
}
- BytesRef shrink() {
- if (term.length == 0) {
+ BytesRefBuilder shrink() {
+ if (term.length() == 0) {
term = null;
} else {
- term.length--;
+ term.setLength(term.length() - 1);
}
return term;
}
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/memory/FSTTermsWriter.java b/lucene/codecs/src/java/org/apache/lucene/codecs/memory/FSTTermsWriter.java
index 88abf78ff11..bce56260173 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/memory/FSTTermsWriter.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/memory/FSTTermsWriter.java
@@ -40,6 +40,7 @@ import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.FixedBitSet;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.IntsRef;
+import org.apache.lucene.util.IntsRefBuilder;
import org.apache.lucene.util.fst.Builder;
import org.apache.lucene.util.fst.FST;
import org.apache.lucene.util.fst.Util;
@@ -256,7 +257,7 @@ public class FSTTermsWriter extends FieldsConsumer {
private final int longsSize;
private long numTerms;
- private final IntsRef scratchTerm = new IntsRef();
+ private final IntsRefBuilder scratchTerm = new IntsRefBuilder();
private final RAMOutputStream metaWriter = new RAMOutputStream();
TermsWriter(FieldInfo fieldInfo) {
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/memory/MemoryDocValuesConsumer.java b/lucene/codecs/src/java/org/apache/lucene/codecs/memory/MemoryDocValuesConsumer.java
index 11d30f355f4..2f6dfe1bd99 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/memory/MemoryDocValuesConsumer.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/memory/MemoryDocValuesConsumer.java
@@ -34,6 +34,7 @@ import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.IntsRef;
+import org.apache.lucene.util.IntsRefBuilder;
import org.apache.lucene.util.MathUtil;
import org.apache.lucene.util.fst.Builder;
import org.apache.lucene.util.fst.FST.INPUT_TYPE;
@@ -359,7 +360,7 @@ class MemoryDocValuesConsumer extends DocValuesConsumer {
meta.writeLong(data.getFilePointer());
PositiveIntOutputs outputs = PositiveIntOutputs.getSingleton();
Builder<Long> builder = new Builder<>(INPUT_TYPE.BYTE1, outputs);
- IntsRef scratch = new IntsRef();
+ IntsRefBuilder scratch = new IntsRefBuilder();
long ord = 0;
for (BytesRef v : values) {
builder.add(Util.toIntsRef(v, scratch), ord);
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/memory/MemoryDocValuesProducer.java b/lucene/codecs/src/java/org/apache/lucene/codecs/memory/MemoryDocValuesProducer.java
index 97bfd654c0c..5d732d93b0e 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/memory/MemoryDocValuesProducer.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/memory/MemoryDocValuesProducer.java
@@ -43,9 +43,11 @@ import org.apache.lucene.store.ChecksumIndexInput;
import org.apache.lucene.store.IndexInput;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.FixedBitSet;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.IntsRef;
+import org.apache.lucene.util.IntsRefBuilder;
import org.apache.lucene.util.LongValues;
import org.apache.lucene.util.PagedBytes;
import org.apache.lucene.util.RamUsageEstimator;
@@ -397,11 +399,11 @@ class MemoryDocValuesProducer extends DocValuesProducer {
final BytesReader in = fst.getBytesReader();
final Arc<Long> firstArc = new Arc<>();
final Arc<Long> scratchArc = new Arc<>();
- final IntsRef scratchInts = new IntsRef();
+ final IntsRefBuilder scratchInts = new IntsRefBuilder();
final BytesRefFSTEnum<Long> fstEnum = new BytesRefFSTEnum<>(fst);
return new SortedDocValues() {
- final BytesRef term = new BytesRef();
+ final BytesRefBuilder term = new BytesRefBuilder();
@Override
public int getOrd(int docID) {
@@ -414,8 +416,7 @@ class MemoryDocValuesProducer extends DocValuesProducer {
in.setPosition(0);
fst.getFirstArc(firstArc);
IntsRef output = Util.getByOutput(fst, ord, in, firstArc, scratchArc, scratchInts);
- Util.toBytesRef(output, term);
- return term;
+ return Util.toBytesRef(output, term);
} catch (IOException bogus) {
throw new RuntimeException(bogus);
}
@@ -545,11 +546,11 @@ class MemoryDocValuesProducer extends DocValuesProducer {
final BytesReader in = fst.getBytesReader();
final Arc<Long> firstArc = new Arc<>();
final Arc<Long> scratchArc = new Arc<>();
- final IntsRef scratchInts = new IntsRef();
+ final IntsRefBuilder scratchInts = new IntsRefBuilder();
final BytesRefFSTEnum<Long> fstEnum = new BytesRefFSTEnum<>(fst);
final ByteArrayDataInput input = new ByteArrayDataInput();
return new SortedSetDocValues() {
- final BytesRef term = new BytesRef();
+ final BytesRefBuilder term = new BytesRefBuilder();
BytesRef ref;
long currentOrd;
@@ -576,8 +577,7 @@ class MemoryDocValuesProducer extends DocValuesProducer {
in.setPosition(0);
fst.getFirstArc(firstArc);
IntsRef output = Util.getByOutput(fst, ord, in, firstArc, scratchArc, scratchInts);
- Util.toBytesRef(output, term);
- return term;
+ return Util.toBytesRef(output, term);
} catch (IOException bogus) {
throw new RuntimeException(bogus);
}
@@ -711,8 +711,8 @@ class MemoryDocValuesProducer extends DocValuesProducer {
final FST.BytesReader bytesReader;
final Arc<Long> firstArc = new Arc<>();
final Arc<Long> scratchArc = new Arc<>();
- final IntsRef scratchInts = new IntsRef();
- final BytesRef scratchBytes = new BytesRef();
+ final IntsRefBuilder scratchInts = new IntsRefBuilder();
+ final BytesRefBuilder scratchBytes = new BytesRefBuilder();
FSTTermsEnum(FST<Long> fst) {
this.fst = fst;
@@ -759,12 +759,8 @@ class MemoryDocValuesProducer extends DocValuesProducer {
bytesReader.setPosition(0);
fst.getFirstArc(firstArc);
IntsRef output = Util.getByOutput(fst, ord, bytesReader, firstArc, scratchArc, scratchInts);
- scratchBytes.bytes = new byte[output.length];
- scratchBytes.offset = 0;
- scratchBytes.length = 0;
- Util.toBytesRef(output, scratchBytes);
// TODO: we could do this lazily, better to try to push into FSTEnum though?
- in.seekExact(scratchBytes);
+ in.seekExact(Util.toBytesRef(output, new BytesRefBuilder()));
}
@Override
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/memory/MemoryPostingsFormat.java b/lucene/codecs/src/java/org/apache/lucene/codecs/memory/MemoryPostingsFormat.java
index ed15e5bb108..671c9ffa753 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/memory/MemoryPostingsFormat.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/memory/MemoryPostingsFormat.java
@@ -53,6 +53,7 @@ import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.FixedBitSet;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.IntsRef;
+import org.apache.lucene.util.IntsRefBuilder;
import org.apache.lucene.util.RamUsageEstimator;
import org.apache.lucene.util.fst.Builder;
import org.apache.lucene.util.fst.ByteSequenceOutputs;
@@ -218,7 +219,7 @@ public final class MemoryPostingsFormat extends PostingsFormat {
private final BytesRef spare = new BytesRef();
private byte[] finalBuffer = new byte[128];
- private final IntsRef scratchIntsRef = new IntsRef();
+ private final IntsRefBuilder scratchIntsRef = new IntsRefBuilder();
private void finishTerm(BytesRef text, TermStats stats) throws IOException {
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/pulsing/PulsingPostingsReader.java b/lucene/codecs/src/java/org/apache/lucene/codecs/pulsing/PulsingPostingsReader.java
index cadd84d568b..d705b80edbf 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/pulsing/PulsingPostingsReader.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/pulsing/PulsingPostingsReader.java
@@ -41,6 +41,7 @@ import org.apache.lucene.util.AttributeImpl;
import org.apache.lucene.util.AttributeSource;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.IOUtils;
/** Concrete class that reads the current doc/freq/skip
@@ -405,7 +406,7 @@ public class PulsingPostingsReader extends PostingsReaderBase {
private int posPending;
private int position;
private int payloadLength;
- private BytesRef payload;
+ private BytesRefBuilder payload;
private int startOffset;
private int offsetLength;
@@ -552,17 +553,16 @@ public class PulsingPostingsReader extends PostingsReaderBase {
public BytesRef getPayload() throws IOException {
//System.out.println("PR getPayload payloadLength=" + payloadLength + " this=" + this);
if (payloadRetrieved) {
- return payload;
+ return payload.get();
} else if (storePayloads && payloadLength > 0) {
payloadRetrieved = true;
if (payload == null) {
- payload = new BytesRef(payloadLength);
- } else {
- payload.grow(payloadLength);
+ payload = new BytesRefBuilder();
}
- postings.readBytes(payload.bytes, 0, payloadLength);
- payload.length = payloadLength;
- return payload;
+ payload.grow(payloadLength);
+ postings.readBytes(payload.bytes(), 0, payloadLength);
+ payload.setLength(payloadLength);
+ return payload.get();
} else {
return null;
}
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextDocValuesReader.java b/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextDocValuesReader.java
index 64247414d90..67d86dd05af 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextDocValuesReader.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextDocValuesReader.java
@@ -55,6 +55,7 @@ import org.apache.lucene.store.ChecksumIndexInput;
import org.apache.lucene.store.IndexInput;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.RamUsageEstimator;
import org.apache.lucene.util.StringHelper;
@@ -77,7 +78,7 @@ class SimpleTextDocValuesReader extends DocValuesProducer {
final int maxDoc;
final IndexInput data;
- final BytesRef scratch = new BytesRef();
+ final BytesRefBuilder scratch = new BytesRefBuilder();
final Map<String,OneField> fields = new HashMap<>();
public SimpleTextDocValuesReader(SegmentReadState state, String ext) throws IOException {
@@ -87,10 +88,10 @@ class SimpleTextDocValuesReader extends DocValuesProducer {
while(true) {
readLine();
//System.out.println("READ field=" + scratch.utf8ToString());
- if (scratch.equals(END)) {
+ if (scratch.get().equals(END)) {
break;
}
- assert startsWith(FIELD) : scratch.utf8ToString();
+ assert startsWith(FIELD) : scratch.get().utf8ToString();
String fieldName = stripPrefix(FIELD);
//System.out.println(" field=" + fieldName);
@@ -98,13 +99,13 @@ class SimpleTextDocValuesReader extends DocValuesProducer {
fields.put(fieldName, field);
readLine();
- assert startsWith(TYPE) : scratch.utf8ToString();
+ assert startsWith(TYPE) : scratch.get().utf8ToString();
DocValuesType dvType = DocValuesType.valueOf(stripPrefix(TYPE));
assert dvType != null;
if (dvType == DocValuesType.NUMERIC) {
readLine();
- assert startsWith(MINVALUE): "got " + scratch.utf8ToString() + " field=" + fieldName + " ext=" + ext;
+ assert startsWith(MINVALUE): "got " + scratch.get().utf8ToString() + " field=" + fieldName + " ext=" + ext;
field.minValue = Long.parseLong(stripPrefix(MINVALUE));
readLine();
assert startsWith(PATTERN);
@@ -155,7 +156,7 @@ class SimpleTextDocValuesReader extends DocValuesProducer {
assert field != null: "field=" + fieldInfo.name + " fields=" + fields;
final IndexInput in = data.clone();
- final BytesRef scratch = new BytesRef();
+ final BytesRefBuilder scratch = new BytesRefBuilder();
final DecimalFormat decoder = new DecimalFormat(field.pattern, new DecimalFormatSymbols(Locale.ROOT));
decoder.setParseBigDecimal(true);
@@ -173,7 +174,7 @@ class SimpleTextDocValuesReader extends DocValuesProducer {
//System.out.println("parsing delta: " + scratch.utf8ToString());
BigDecimal bd;
try {
- bd = (BigDecimal) decoder.parse(scratch.utf8ToString());
+ bd = (BigDecimal) decoder.parse(scratch.get().utf8ToString());
} catch (ParseException pe) {
throw new CorruptIndexException("failed to parse BigDecimal value (resource=" + in + ")", pe);
}
@@ -189,7 +190,7 @@ class SimpleTextDocValuesReader extends DocValuesProducer {
private Bits getNumericDocsWithField(FieldInfo fieldInfo) throws IOException {
final OneField field = fields.get(fieldInfo.name);
final IndexInput in = data.clone();
- final BytesRef scratch = new BytesRef();
+ final BytesRefBuilder scratch = new BytesRefBuilder();
return new Bits() {
@Override
public boolean get(int index) {
@@ -197,7 +198,7 @@ class SimpleTextDocValuesReader extends DocValuesProducer {
in.seek(field.dataStartFilePointer + (1+field.pattern.length()+2)*index);
SimpleTextUtil.readLine(in, scratch); // data
SimpleTextUtil.readLine(in, scratch); // 'T' or 'F'
- return scratch.bytes[scratch.offset] == (byte) 'T';
+ return scratch.byteAt(0) == (byte) 'T';
} catch (IOException e) {
throw new RuntimeException(e);
}
@@ -219,11 +220,11 @@ class SimpleTextDocValuesReader extends DocValuesProducer {
assert field != null;
final IndexInput in = data.clone();
- final BytesRef scratch = new BytesRef();
+ final BytesRefBuilder scratch = new BytesRefBuilder();
final DecimalFormat decoder = new DecimalFormat(field.pattern, new DecimalFormatSymbols(Locale.ROOT));
return new BinaryDocValues() {
- final BytesRef term = new BytesRef();
+ final BytesRefBuilder term = new BytesRefBuilder();
@Override
public BytesRef get(int docID) {
@@ -233,18 +234,17 @@ class SimpleTextDocValuesReader extends DocValuesProducer {
}
in.seek(field.dataStartFilePointer + (9+field.pattern.length() + field.maxLength+2)*docID);
SimpleTextUtil.readLine(in, scratch);
- assert StringHelper.startsWith(scratch, LENGTH);
+ assert StringHelper.startsWith(scratch.get(), LENGTH);
int len;
try {
- len = decoder.parse(new String(scratch.bytes, scratch.offset + LENGTH.length, scratch.length - LENGTH.length, StandardCharsets.UTF_8)).intValue();
+ len = decoder.parse(new String(scratch.bytes(), LENGTH.length, scratch.length() - LENGTH.length, StandardCharsets.UTF_8)).intValue();
} catch (ParseException pe) {
throw new CorruptIndexException("failed to parse int length (resource=" + in + ")", pe);
}
term.grow(len);
- term.offset = 0;
- term.length = len;
- in.readBytes(term.bytes, 0, len);
- return term;
+ term.setLength(len);
+ in.readBytes(term.bytes(), 0, len);
+ return term.get();
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
@@ -255,7 +255,7 @@ class SimpleTextDocValuesReader extends DocValuesProducer {
private Bits getBinaryDocsWithField(FieldInfo fieldInfo) throws IOException {
final OneField field = fields.get(fieldInfo.name);
final IndexInput in = data.clone();
- final BytesRef scratch = new BytesRef();
+ final BytesRefBuilder scratch = new BytesRefBuilder();
final DecimalFormat decoder = new DecimalFormat(field.pattern, new DecimalFormatSymbols(Locale.ROOT));
return new Bits() {
@@ -264,10 +264,10 @@ class SimpleTextDocValuesReader extends DocValuesProducer {
try {
in.seek(field.dataStartFilePointer + (9+field.pattern.length() + field.maxLength+2)*index);
SimpleTextUtil.readLine(in, scratch);
- assert StringHelper.startsWith(scratch, LENGTH);
+ assert StringHelper.startsWith(scratch.get(), LENGTH);
int len;
try {
- len = decoder.parse(new String(scratch.bytes, scratch.offset + LENGTH.length, scratch.length - LENGTH.length, StandardCharsets.UTF_8)).intValue();
+ len = decoder.parse(new String(scratch.bytes(), LENGTH.length, scratch.length() - LENGTH.length, StandardCharsets.UTF_8)).intValue();
} catch (ParseException pe) {
throw new CorruptIndexException("failed to parse int length (resource=" + in + ")", pe);
}
@@ -276,7 +276,7 @@ class SimpleTextDocValuesReader extends DocValuesProducer {
in.readBytes(bytes, 0, len);
SimpleTextUtil.readLine(in, scratch); // newline
SimpleTextUtil.readLine(in, scratch); // 'T' or 'F'
- return scratch.bytes[scratch.offset] == (byte) 'T';
+ return scratch.byteAt(0) == (byte) 'T';
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
@@ -298,12 +298,12 @@ class SimpleTextDocValuesReader extends DocValuesProducer {
assert field != null;
final IndexInput in = data.clone();
- final BytesRef scratch = new BytesRef();
+ final BytesRefBuilder scratch = new BytesRefBuilder();
final DecimalFormat decoder = new DecimalFormat(field.pattern, new DecimalFormatSymbols(Locale.ROOT));
final DecimalFormat ordDecoder = new DecimalFormat(field.ordPattern, new DecimalFormatSymbols(Locale.ROOT));
return new SortedDocValues() {
- final BytesRef term = new BytesRef();
+ final BytesRefBuilder term = new BytesRefBuilder();
@Override
public int getOrd(int docID) {
@@ -314,7 +314,7 @@ class SimpleTextDocValuesReader extends DocValuesProducer {
in.seek(field.dataStartFilePointer + field.numValues * (9 + field.pattern.length() + field.maxLength) + docID * (1 + field.ordPattern.length()));
SimpleTextUtil.readLine(in, scratch);
try {
- return (int) ordDecoder.parse(scratch.utf8ToString()).longValue()-1;
+ return (int) ordDecoder.parse(scratch.get().utf8ToString()).longValue()-1;
} catch (ParseException pe) {
throw new CorruptIndexException("failed to parse ord (resource=" + in + ")", pe);
}
@@ -331,18 +331,17 @@ class SimpleTextDocValuesReader extends DocValuesProducer {
}
in.seek(field.dataStartFilePointer + ord * (9 + field.pattern.length() + field.maxLength));
SimpleTextUtil.readLine(in, scratch);
- assert StringHelper.startsWith(scratch, LENGTH): "got " + scratch.utf8ToString() + " in=" + in;
+ assert StringHelper.startsWith(scratch.get(), LENGTH): "got " + scratch.get().utf8ToString() + " in=" + in;
int len;
try {
- len = decoder.parse(new String(scratch.bytes, scratch.offset + LENGTH.length, scratch.length - LENGTH.length, StandardCharsets.UTF_8)).intValue();
+ len = decoder.parse(new String(scratch.bytes(), LENGTH.length, scratch.length() - LENGTH.length, StandardCharsets.UTF_8)).intValue();
} catch (ParseException pe) {
throw new CorruptIndexException("failed to parse int length (resource=" + in + ")", pe);
}
term.grow(len);
- term.offset = 0;
- term.length = len;
- in.readBytes(term.bytes, 0, len);
- return term;
+ term.setLength(len);
+ in.readBytes(term.bytes(), 0, len);
+ return term.get();
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
@@ -396,13 +395,13 @@ class SimpleTextDocValuesReader extends DocValuesProducer {
assert field != null;
final IndexInput in = data.clone();
- final BytesRef scratch = new BytesRef();
+ final BytesRefBuilder scratch = new BytesRefBuilder();
final DecimalFormat decoder = new DecimalFormat(field.pattern, new DecimalFormatSymbols(Locale.ROOT));
return new SortedSetDocValues() {
String[] currentOrds = new String[0];
int currentIndex = 0;
- final BytesRef term = new BytesRef();
+ final BytesRefBuilder term = new BytesRefBuilder();
@Override
public long nextOrd() {
@@ -421,7 +420,7 @@ class SimpleTextDocValuesReader extends DocValuesProducer {
try {
in.seek(field.dataStartFilePointer + field.numValues * (9 + field.pattern.length() + field.maxLength) + docID * (1 + field.ordPattern.length()));
SimpleTextUtil.readLine(in, scratch);
- String ordList = scratch.utf8ToString().trim();
+ String ordList = scratch.get().utf8ToString().trim();
if (ordList.isEmpty()) {
currentOrds = new String[0];
} else {
@@ -441,18 +440,17 @@ class SimpleTextDocValuesReader extends DocValuesProducer {
}
in.seek(field.dataStartFilePointer + ord * (9 + field.pattern.length() + field.maxLength));
SimpleTextUtil.readLine(in, scratch);
- assert StringHelper.startsWith(scratch, LENGTH): "got " + scratch.utf8ToString() + " in=" + in;
+ assert StringHelper.startsWith(scratch.get(), LENGTH): "got " + scratch.get().utf8ToString() + " in=" + in;
int len;
try {
- len = decoder.parse(new String(scratch.bytes, scratch.offset + LENGTH.length, scratch.length - LENGTH.length, StandardCharsets.UTF_8)).intValue();
+ len = decoder.parse(new String(scratch.bytes(), LENGTH.length, scratch.length() - LENGTH.length, StandardCharsets.UTF_8)).intValue();
} catch (ParseException pe) {
throw new CorruptIndexException("failed to parse int length (resource=" + in + ")", pe);
}
term.grow(len);
- term.offset = 0;
- term.length = len;
- in.readBytes(term.bytes, 0, len);
- return term;
+ term.setLength(len);
+ in.readBytes(term.bytes(), 0, len);
+ return term.get();
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
@@ -496,29 +494,29 @@ class SimpleTextDocValuesReader extends DocValuesProducer {
/** Used only in ctor: */
private boolean startsWith(BytesRef prefix) {
- return StringHelper.startsWith(scratch, prefix);
+ return StringHelper.startsWith(scratch.get(), prefix);
}
/** Used only in ctor: */
private String stripPrefix(BytesRef prefix) throws IOException {
- return new String(scratch.bytes, scratch.offset + prefix.length, scratch.length - prefix.length, StandardCharsets.UTF_8);
+ return new String(scratch.bytes(), prefix.length, scratch.length() - prefix.length, StandardCharsets.UTF_8);
}
@Override
public long ramBytesUsed() {
- return BASE_RAM_BYTES_USED + RamUsageEstimator.sizeOf(scratch.bytes)
+ return BASE_RAM_BYTES_USED + RamUsageEstimator.sizeOf(scratch.bytes())
+ fields.size() * (RamUsageEstimator.NUM_BYTES_OBJECT_REF * 2L + OneField.BASE_RAM_BYTES_USED);
}
@Override
public void checkIntegrity() throws IOException {
- BytesRef scratch = new BytesRef();
+ BytesRefBuilder scratch = new BytesRefBuilder();
IndexInput clone = data.clone();
clone.seek(0);
ChecksumIndexInput input = new BufferedChecksumIndexInput(clone);
while(true) {
SimpleTextUtil.readLine(input, scratch);
- if (scratch.equals(END)) {
+ if (scratch.get().equals(END)) {
SimpleTextUtil.checkFooter(input);
break;
}
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextDocValuesWriter.java b/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextDocValuesWriter.java
index 1e7bbfed37a..f3607d18fde 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextDocValuesWriter.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextDocValuesWriter.java
@@ -33,6 +33,7 @@ import org.apache.lucene.index.SegmentWriteState;
import org.apache.lucene.index.FieldInfo.DocValuesType;
import org.apache.lucene.store.IndexOutput;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.IOUtils;
class SimpleTextDocValuesWriter extends DocValuesConsumer {
@@ -50,7 +51,7 @@ class SimpleTextDocValuesWriter extends DocValuesConsumer {
final static BytesRef ORDPATTERN = new BytesRef(" ordpattern ");
IndexOutput data;
- final BytesRef scratch = new BytesRef();
+ final BytesRefBuilder scratch = new BytesRefBuilder();
final int numDocs;
private final Set<String> fieldsSeen = new HashSet<>(); // for asserting
@@ -279,7 +280,7 @@ class SimpleTextDocValuesWriter extends DocValuesConsumer {
@Override
public Iterator<BytesRef> iterator() {
final StringBuilder builder = new StringBuilder();
- final BytesRef scratch = new BytesRef();
+ final BytesRefBuilder scratch = new BytesRefBuilder();
final Iterator<Number> counts = docToValueCount.iterator();
final Iterator<Number> numbers = values.iterator();
@@ -301,7 +302,7 @@ class SimpleTextDocValuesWriter extends DocValuesConsumer {
builder.append(Long.toString(numbers.next().longValue()));
}
scratch.copyChars(builder);
- return scratch;
+ return scratch.get();
}
@Override
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextFieldInfosReader.java b/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextFieldInfosReader.java
index 8ba8e9eb727..b9e49a82c2e 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextFieldInfosReader.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextFieldInfosReader.java
@@ -32,7 +32,7 @@ import org.apache.lucene.index.FieldInfo.IndexOptions;
import org.apache.lucene.store.ChecksumIndexInput;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.IOContext;
-import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.StringHelper;
@@ -50,76 +50,76 @@ public class SimpleTextFieldInfosReader extends FieldInfosReader {
public FieldInfos read(Directory directory, String segmentName, String segmentSuffix, IOContext iocontext) throws IOException {
final String fileName = IndexFileNames.segmentFileName(segmentName, segmentSuffix, FIELD_INFOS_EXTENSION);
ChecksumIndexInput input = directory.openChecksumInput(fileName, iocontext);
- BytesRef scratch = new BytesRef();
+ BytesRefBuilder scratch = new BytesRefBuilder();
boolean success = false;
try {
SimpleTextUtil.readLine(input, scratch);
- assert StringHelper.startsWith(scratch, NUMFIELDS);
+ assert StringHelper.startsWith(scratch.get(), NUMFIELDS);
final int size = Integer.parseInt(readString(NUMFIELDS.length, scratch));
FieldInfo infos[] = new FieldInfo[size];
for (int i = 0; i < size; i++) {
SimpleTextUtil.readLine(input, scratch);
- assert StringHelper.startsWith(scratch, NAME);
+ assert StringHelper.startsWith(scratch.get(), NAME);
String name = readString(NAME.length, scratch);
SimpleTextUtil.readLine(input, scratch);
- assert StringHelper.startsWith(scratch, NUMBER);
+ assert StringHelper.startsWith(scratch.get(), NUMBER);
int fieldNumber = Integer.parseInt(readString(NUMBER.length, scratch));
SimpleTextUtil.readLine(input, scratch);
- assert StringHelper.startsWith(scratch, ISINDEXED);
+ assert StringHelper.startsWith(scratch.get(), ISINDEXED);
boolean isIndexed = Boolean.parseBoolean(readString(ISINDEXED.length, scratch));
final IndexOptions indexOptions;
if (isIndexed) {
SimpleTextUtil.readLine(input, scratch);
- assert StringHelper.startsWith(scratch, INDEXOPTIONS);
+ assert StringHelper.startsWith(scratch.get(), INDEXOPTIONS);
indexOptions = IndexOptions.valueOf(readString(INDEXOPTIONS.length, scratch));
} else {
indexOptions = null;
}
SimpleTextUtil.readLine(input, scratch);
- assert StringHelper.startsWith(scratch, STORETV);
+ assert StringHelper.startsWith(scratch.get(), STORETV);
boolean storeTermVector = Boolean.parseBoolean(readString(STORETV.length, scratch));
SimpleTextUtil.readLine(input, scratch);
- assert StringHelper.startsWith(scratch, PAYLOADS);
+ assert StringHelper.startsWith(scratch.get(), PAYLOADS);
boolean storePayloads = Boolean.parseBoolean(readString(PAYLOADS.length, scratch));
SimpleTextUtil.readLine(input, scratch);
- assert StringHelper.startsWith(scratch, NORMS);
+ assert StringHelper.startsWith(scratch.get(), NORMS);
boolean omitNorms = !Boolean.parseBoolean(readString(NORMS.length, scratch));
SimpleTextUtil.readLine(input, scratch);
- assert StringHelper.startsWith(scratch, NORMS_TYPE);
+ assert StringHelper.startsWith(scratch.get(), NORMS_TYPE);
String nrmType = readString(NORMS_TYPE.length, scratch);
final DocValuesType normsType = docValuesType(nrmType);
SimpleTextUtil.readLine(input, scratch);
- assert StringHelper.startsWith(scratch, DOCVALUES);
+ assert StringHelper.startsWith(scratch.get(), DOCVALUES);
String dvType = readString(DOCVALUES.length, scratch);
final DocValuesType docValuesType = docValuesType(dvType);
SimpleTextUtil.readLine(input, scratch);
- assert StringHelper.startsWith(scratch, DOCVALUES_GEN);
+ assert StringHelper.startsWith(scratch.get(), DOCVALUES_GEN);
final long dvGen = Long.parseLong(readString(DOCVALUES_GEN.length, scratch));
SimpleTextUtil.readLine(input, scratch);
- assert StringHelper.startsWith(scratch, NUM_ATTS);
+ assert StringHelper.startsWith(scratch.get(), NUM_ATTS);
int numAtts = Integer.parseInt(readString(NUM_ATTS.length, scratch));
Map<String,String> atts = new HashMap<>();
for (int j = 0; j < numAtts; j++) {
SimpleTextUtil.readLine(input, scratch);
- assert StringHelper.startsWith(scratch, ATT_KEY);
+ assert StringHelper.startsWith(scratch.get(), ATT_KEY);
String key = readString(ATT_KEY.length, scratch);
SimpleTextUtil.readLine(input, scratch);
- assert StringHelper.startsWith(scratch, ATT_VALUE);
+ assert StringHelper.startsWith(scratch.get(), ATT_VALUE);
String value = readString(ATT_VALUE.length, scratch);
atts.put(key, value);
}
@@ -150,7 +150,7 @@ public class SimpleTextFieldInfosReader extends FieldInfosReader {
}
}
- private String readString(int offset, BytesRef scratch) {
- return new String(scratch.bytes, scratch.offset+offset, scratch.length-offset, StandardCharsets.UTF_8);
+ private String readString(int offset, BytesRefBuilder scratch) {
+ return new String(scratch.bytes(), offset, scratch.length()-offset, StandardCharsets.UTF_8);
}
}
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextFieldInfosWriter.java b/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextFieldInfosWriter.java
index bb4fa141119..57c4ccaa530 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextFieldInfosWriter.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextFieldInfosWriter.java
@@ -29,6 +29,7 @@ import org.apache.lucene.store.Directory;
import org.apache.lucene.store.IOContext;
import org.apache.lucene.store.IndexOutput;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.IOUtils;
/**
@@ -63,7 +64,7 @@ public class SimpleTextFieldInfosWriter extends FieldInfosWriter {
public void write(Directory directory, String segmentName, String segmentSuffix, FieldInfos infos, IOContext context) throws IOException {
final String fileName = IndexFileNames.segmentFileName(segmentName, segmentSuffix, FIELD_INFOS_EXTENSION);
IndexOutput out = directory.createOutput(fileName, context);
- BytesRef scratch = new BytesRef();
+ BytesRefBuilder scratch = new BytesRefBuilder();
boolean success = false;
try {
SimpleTextUtil.write(out, NUMFIELDS);
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextFieldsReader.java b/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextFieldsReader.java
index 8513a0f362b..0ef7d3bf31d 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextFieldsReader.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextFieldsReader.java
@@ -51,10 +51,13 @@ import org.apache.lucene.util.Accountable;
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.CharsRef;
+import org.apache.lucene.util.CharsRefBuilder;
import org.apache.lucene.util.FixedBitSet;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.IntsRef;
+import org.apache.lucene.util.IntsRefBuilder;
import org.apache.lucene.util.RamUsageEstimator;
import org.apache.lucene.util.StringHelper;
import org.apache.lucene.util.UnicodeUtil;
@@ -93,16 +96,16 @@ class SimpleTextFieldsReader extends FieldsProducer {
private TreeMap<String,Long> readFields(IndexInput in) throws IOException {
ChecksumIndexInput input = new BufferedChecksumIndexInput(in);
- BytesRef scratch = new BytesRef(10);
+ BytesRefBuilder scratch = new BytesRefBuilder();
TreeMap<String,Long> fields = new TreeMap<>();
while (true) {
SimpleTextUtil.readLine(input, scratch);
- if (scratch.equals(END)) {
+ if (scratch.get().equals(END)) {
SimpleTextUtil.checkFooter(input);
return fields;
- } else if (StringHelper.startsWith(scratch, FIELD)) {
- String fieldName = new String(scratch.bytes, scratch.offset + FIELD.length, scratch.length - FIELD.length, StandardCharsets.UTF_8);
+ } else if (StringHelper.startsWith(scratch.get(), FIELD)) {
+ String fieldName = new String(scratch.bytes(), FIELD.length, scratch.length() - FIELD.length, StandardCharsets.UTF_8);
fields.put(fieldName, input.getFilePointer());
}
}
@@ -240,8 +243,8 @@ class SimpleTextFieldsReader extends FieldsProducer {
private int docID = -1;
private int tf;
private Bits liveDocs;
- private final BytesRef scratch = new BytesRef(10);
- private final CharsRef scratchUTF16 = new CharsRef(10);
+ private final BytesRefBuilder scratch = new BytesRefBuilder();
+ private final CharsRefBuilder scratchUTF16 = new CharsRefBuilder();
private int cost;
public SimpleTextDocsEnum() {
@@ -283,7 +286,7 @@ class SimpleTextFieldsReader extends FieldsProducer {
while(true) {
final long lineStart = in.getFilePointer();
SimpleTextUtil.readLine(in, scratch);
- if (StringHelper.startsWith(scratch, DOC)) {
+ if (StringHelper.startsWith(scratch.get(), DOC)) {
if (!first && (liveDocs == null || liveDocs.get(docID))) {
in.seek(lineStart);
if (!omitTF) {
@@ -291,23 +294,23 @@ class SimpleTextFieldsReader extends FieldsProducer {
}
return docID;
}
- UnicodeUtil.UTF8toUTF16(scratch.bytes, scratch.offset+DOC.length, scratch.length-DOC.length, scratchUTF16);
- docID = ArrayUtil.parseInt(scratchUTF16.chars, 0, scratchUTF16.length);
+ scratchUTF16.copyUTF8Bytes(scratch.bytes(), DOC.length, scratch.length()-DOC.length);
+ docID = ArrayUtil.parseInt(scratchUTF16.chars(), 0, scratchUTF16.length());
termFreq = 0;
first = false;
- } else if (StringHelper.startsWith(scratch, FREQ)) {
- UnicodeUtil.UTF8toUTF16(scratch.bytes, scratch.offset+FREQ.length, scratch.length-FREQ.length, scratchUTF16);
- termFreq = ArrayUtil.parseInt(scratchUTF16.chars, 0, scratchUTF16.length);
- } else if (StringHelper.startsWith(scratch, POS)) {
+ } else if (StringHelper.startsWith(scratch.get(), FREQ)) {
+ scratchUTF16.copyUTF8Bytes(scratch.bytes(), FREQ.length, scratch.length()-FREQ.length);
+ termFreq = ArrayUtil.parseInt(scratchUTF16.chars(), 0, scratchUTF16.length());
+ } else if (StringHelper.startsWith(scratch.get(), POS)) {
// skip termFreq++;
- } else if (StringHelper.startsWith(scratch, START_OFFSET)) {
+ } else if (StringHelper.startsWith(scratch.get(), START_OFFSET)) {
// skip
- } else if (StringHelper.startsWith(scratch, END_OFFSET)) {
+ } else if (StringHelper.startsWith(scratch.get(), END_OFFSET)) {
// skip
- } else if (StringHelper.startsWith(scratch, PAYLOAD)) {
+ } else if (StringHelper.startsWith(scratch.get(), PAYLOAD)) {
// skip
} else {
- assert StringHelper.startsWith(scratch, TERM) || StringHelper.startsWith(scratch, FIELD) || StringHelper.startsWith(scratch, END): "scratch=" + scratch.utf8ToString();
+ assert StringHelper.startsWith(scratch.get(), TERM) || StringHelper.startsWith(scratch.get(), FIELD) || StringHelper.startsWith(scratch.get(), END): "scratch=" + scratch.get().utf8ToString();
if (!first && (liveDocs == null || liveDocs.get(docID))) {
in.seek(lineStart);
if (!omitTF) {
@@ -338,10 +341,10 @@ class SimpleTextFieldsReader extends FieldsProducer {
private int docID = -1;
private int tf;
private Bits liveDocs;
- private final BytesRef scratch = new BytesRef(10);
- private final BytesRef scratch2 = new BytesRef(10);
- private final CharsRef scratchUTF16 = new CharsRef(10);
- private final CharsRef scratchUTF16_2 = new CharsRef(10);
+ private final BytesRefBuilder scratch = new BytesRefBuilder();
+ private final BytesRefBuilder scratch2 = new BytesRefBuilder();
+ private final CharsRefBuilder scratchUTF16 = new CharsRefBuilder();
+ private final CharsRefBuilder scratchUTF16_2 = new CharsRefBuilder();
private BytesRef payload;
private long nextDocStart;
private boolean readOffsets;
@@ -392,30 +395,30 @@ class SimpleTextFieldsReader extends FieldsProducer {
final long lineStart = in.getFilePointer();
SimpleTextUtil.readLine(in, scratch);
//System.out.println("NEXT DOC: " + scratch.utf8ToString());
- if (StringHelper.startsWith(scratch, DOC)) {
+ if (StringHelper.startsWith(scratch.get(), DOC)) {
if (!first && (liveDocs == null || liveDocs.get(docID))) {
nextDocStart = lineStart;
in.seek(posStart);
return docID;
}
- UnicodeUtil.UTF8toUTF16(scratch.bytes, scratch.offset+DOC.length, scratch.length-DOC.length, scratchUTF16);
- docID = ArrayUtil.parseInt(scratchUTF16.chars, 0, scratchUTF16.length);
+ scratchUTF16.copyUTF8Bytes(scratch.bytes(), DOC.length, scratch.length()-DOC.length);
+ docID = ArrayUtil.parseInt(scratchUTF16.chars(), 0, scratchUTF16.length());
tf = 0;
first = false;
- } else if (StringHelper.startsWith(scratch, FREQ)) {
- UnicodeUtil.UTF8toUTF16(scratch.bytes, scratch.offset+FREQ.length, scratch.length-FREQ.length, scratchUTF16);
- tf = ArrayUtil.parseInt(scratchUTF16.chars, 0, scratchUTF16.length);
+ } else if (StringHelper.startsWith(scratch.get(), FREQ)) {
+ scratchUTF16.copyUTF8Bytes(scratch.bytes(), FREQ.length, scratch.length()-FREQ.length);
+ tf = ArrayUtil.parseInt(scratchUTF16.chars(), 0, scratchUTF16.length());
posStart = in.getFilePointer();
- } else if (StringHelper.startsWith(scratch, POS)) {
+ } else if (StringHelper.startsWith(scratch.get(), POS)) {
// skip
- } else if (StringHelper.startsWith(scratch, START_OFFSET)) {
+ } else if (StringHelper.startsWith(scratch.get(), START_OFFSET)) {
// skip
- } else if (StringHelper.startsWith(scratch, END_OFFSET)) {
+ } else if (StringHelper.startsWith(scratch.get(), END_OFFSET)) {
// skip
- } else if (StringHelper.startsWith(scratch, PAYLOAD)) {
+ } else if (StringHelper.startsWith(scratch.get(), PAYLOAD)) {
// skip
} else {
- assert StringHelper.startsWith(scratch, TERM) || StringHelper.startsWith(scratch, FIELD) || StringHelper.startsWith(scratch, END);
+ assert StringHelper.startsWith(scratch.get(), TERM) || StringHelper.startsWith(scratch.get(), FIELD) || StringHelper.startsWith(scratch.get(), END);
if (!first && (liveDocs == null || liveDocs.get(docID))) {
nextDocStart = lineStart;
in.seek(posStart);
@@ -437,34 +440,33 @@ class SimpleTextFieldsReader extends FieldsProducer {
final int pos;
if (readPositions) {
SimpleTextUtil.readLine(in, scratch);
- assert StringHelper.startsWith(scratch, POS): "got line=" + scratch.utf8ToString();
- UnicodeUtil.UTF8toUTF16(scratch.bytes, scratch.offset+POS.length, scratch.length-POS.length, scratchUTF16_2);
- pos = ArrayUtil.parseInt(scratchUTF16_2.chars, 0, scratchUTF16_2.length);
+ assert StringHelper.startsWith(scratch.get(), POS): "got line=" + scratch.get().utf8ToString();
+ scratchUTF16_2.copyUTF8Bytes(scratch.bytes(), POS.length, scratch.length()-POS.length);
+ pos = ArrayUtil.parseInt(scratchUTF16_2.chars(), 0, scratchUTF16_2.length());
} else {
pos = -1;
}
if (readOffsets) {
SimpleTextUtil.readLine(in, scratch);
- assert StringHelper.startsWith(scratch, START_OFFSET): "got line=" + scratch.utf8ToString();
- UnicodeUtil.UTF8toUTF16(scratch.bytes, scratch.offset+START_OFFSET.length, scratch.length-START_OFFSET.length, scratchUTF16_2);
- startOffset = ArrayUtil.parseInt(scratchUTF16_2.chars, 0, scratchUTF16_2.length);
+ assert StringHelper.startsWith(scratch.get(), START_OFFSET): "got line=" + scratch.get().utf8ToString();
+ scratchUTF16_2.copyUTF8Bytes(scratch.bytes(), START_OFFSET.length, scratch.length()-START_OFFSET.length);
+ startOffset = ArrayUtil.parseInt(scratchUTF16_2.chars(), 0, scratchUTF16_2.length());
SimpleTextUtil.readLine(in, scratch);
- assert StringHelper.startsWith(scratch, END_OFFSET): "got line=" + scratch.utf8ToString();
- UnicodeUtil.UTF8toUTF16(scratch.bytes, scratch.offset+END_OFFSET.length, scratch.length-END_OFFSET.length, scratchUTF16_2);
- endOffset = ArrayUtil.parseInt(scratchUTF16_2.chars, 0, scratchUTF16_2.length);
+ assert StringHelper.startsWith(scratch.get(), END_OFFSET): "got line=" + scratch.get().utf8ToString();
+ scratchUTF16_2.grow(scratch.length()-END_OFFSET.length);
+ scratchUTF16_2.copyUTF8Bytes(scratch.bytes(), END_OFFSET.length, scratch.length()-END_OFFSET.length);
+ endOffset = ArrayUtil.parseInt(scratchUTF16_2.chars(), 0, scratchUTF16_2.length());
}
final long fp = in.getFilePointer();
SimpleTextUtil.readLine(in, scratch);
- if (StringHelper.startsWith(scratch, PAYLOAD)) {
- final int len = scratch.length - PAYLOAD.length;
- if (scratch2.bytes.length < len) {
- scratch2.grow(len);
- }
- System.arraycopy(scratch.bytes, PAYLOAD.length, scratch2.bytes, 0, len);
- scratch2.length = len;
- payload = scratch2;
+ if (StringHelper.startsWith(scratch.get(), PAYLOAD)) {
+ final int len = scratch.length() - PAYLOAD.length;
+ scratch2.grow(len);
+ System.arraycopy(scratch.bytes(), PAYLOAD.length, scratch2.bytes(), 0, len);
+ scratch2.setLength(len);
+ payload = scratch2.get();
} else {
payload = null;
in.seek(fp);
@@ -516,8 +518,8 @@ class SimpleTextFieldsReader extends FieldsProducer {
private int docCount;
private FST<PairOutputs.Pair<Long,PairOutputs.Pair<Long,Long>>> fst;
private int termCount;
- private final BytesRef scratch = new BytesRef(10);
- private final CharsRef scratchUTF16 = new CharsRef(10);
+ private final BytesRefBuilder scratch = new BytesRefBuilder();
+ private final CharsRefBuilder scratchUTF16 = new CharsRefBuilder();
public SimpleTextTerms(String field, long termsStart, int maxDoc) throws IOException {
this.maxDoc = maxDoc;
@@ -535,43 +537,41 @@ class SimpleTextFieldsReader extends FieldsProducer {
b = new Builder<>(FST.INPUT_TYPE.BYTE1, outputs);
IndexInput in = SimpleTextFieldsReader.this.in.clone();
in.seek(termsStart);
- final BytesRef lastTerm = new BytesRef(10);
+ final BytesRefBuilder lastTerm = new BytesRefBuilder();
long lastDocsStart = -1;
int docFreq = 0;
long totalTermFreq = 0;
FixedBitSet visitedDocs = new FixedBitSet(maxDoc);
- final IntsRef scratchIntsRef = new IntsRef();
+ final IntsRefBuilder scratchIntsRef = new IntsRefBuilder();
while(true) {
SimpleTextUtil.readLine(in, scratch);
- if (scratch.equals(END) || StringHelper.startsWith(scratch, FIELD)) {
+ if (scratch.get().equals(END) || StringHelper.startsWith(scratch.get(), FIELD)) {
if (lastDocsStart != -1) {
- b.add(Util.toIntsRef(lastTerm, scratchIntsRef),
+ b.add(Util.toIntsRef(lastTerm.get(), scratchIntsRef),
outputs.newPair(lastDocsStart,
outputsInner.newPair((long) docFreq, totalTermFreq)));
sumTotalTermFreq += totalTermFreq;
}
break;
- } else if (StringHelper.startsWith(scratch, DOC)) {
+ } else if (StringHelper.startsWith(scratch.get(), DOC)) {
docFreq++;
sumDocFreq++;
- UnicodeUtil.UTF8toUTF16(scratch.bytes, scratch.offset+DOC.length, scratch.length-DOC.length, scratchUTF16);
- int docID = ArrayUtil.parseInt(scratchUTF16.chars, 0, scratchUTF16.length);
+ scratchUTF16.copyUTF8Bytes(scratch.bytes(), DOC.length, scratch.length()-DOC.length);
+ int docID = ArrayUtil.parseInt(scratchUTF16.chars(), 0, scratchUTF16.length());
visitedDocs.set(docID);
- } else if (StringHelper.startsWith(scratch, FREQ)) {
- UnicodeUtil.UTF8toUTF16(scratch.bytes, scratch.offset+FREQ.length, scratch.length-FREQ.length, scratchUTF16);
- totalTermFreq += ArrayUtil.parseInt(scratchUTF16.chars, 0, scratchUTF16.length);
- } else if (StringHelper.startsWith(scratch, TERM)) {
+ } else if (StringHelper.startsWith(scratch.get(), FREQ)) {
+ scratchUTF16.copyUTF8Bytes(scratch.bytes(), FREQ.length, scratch.length()-FREQ.length);
+ totalTermFreq += ArrayUtil.parseInt(scratchUTF16.chars(), 0, scratchUTF16.length());
+ } else if (StringHelper.startsWith(scratch.get(), TERM)) {
if (lastDocsStart != -1) {
- b.add(Util.toIntsRef(lastTerm, scratchIntsRef), outputs.newPair(lastDocsStart,
+ b.add(Util.toIntsRef(lastTerm.get(), scratchIntsRef), outputs.newPair(lastDocsStart,
outputsInner.newPair((long) docFreq, totalTermFreq)));
}
lastDocsStart = in.getFilePointer();
- final int len = scratch.length - TERM.length;
- if (len > lastTerm.length) {
- lastTerm.grow(len);
- }
- System.arraycopy(scratch.bytes, TERM.length, lastTerm.bytes, 0, len);
- lastTerm.length = len;
+ final int len = scratch.length() - TERM.length;
+ lastTerm.grow(len);
+ System.arraycopy(scratch.bytes(), TERM.length, lastTerm.bytes(), 0, len);
+ lastTerm.setLength(len);
docFreq = 0;
sumTotalTermFreq += totalTermFreq;
totalTermFreq = 0;
@@ -592,7 +592,7 @@ class SimpleTextFieldsReader extends FieldsProducer {
@Override
public long ramBytesUsed() {
return TERMS_BASE_RAM_BYTES_USED + (fst!=null ? fst.ramBytesUsed() : 0)
- + RamUsageEstimator.sizeOf(scratch.bytes) + RamUsageEstimator.sizeOf(scratchUTF16.chars);
+ + RamUsageEstimator.sizeOf(scratch.bytes()) + RamUsageEstimator.sizeOf(scratchUTF16.chars());
}
@Override
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextFieldsWriter.java b/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextFieldsWriter.java
index a6ecbf691e3..656713d1c62 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextFieldsWriter.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextFieldsWriter.java
@@ -30,11 +30,12 @@ import org.apache.lucene.index.Terms;
import org.apache.lucene.index.TermsEnum;
import org.apache.lucene.store.IndexOutput;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
class SimpleTextFieldsWriter extends FieldsConsumer {
private IndexOutput out;
- private final BytesRef scratch = new BytesRef(10);
+ private final BytesRefBuilder scratch = new BytesRefBuilder();
private final SegmentWriteState writeState;
final static BytesRef END = new BytesRef("END");
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextLiveDocsFormat.java b/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextLiveDocsFormat.java
index ba14cfee661..7e277943b52 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextLiveDocsFormat.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextLiveDocsFormat.java
@@ -31,7 +31,9 @@ import org.apache.lucene.store.IndexOutput;
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.CharsRef;
+import org.apache.lucene.util.CharsRefBuilder;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.MutableBits;
import org.apache.lucene.util.StringHelper;
@@ -65,8 +67,8 @@ public class SimpleTextLiveDocsFormat extends LiveDocsFormat {
@Override
public Bits readLiveDocs(Directory dir, SegmentCommitInfo info, IOContext context) throws IOException {
assert info.hasDeletions();
- BytesRef scratch = new BytesRef();
- CharsRef scratchUTF16 = new CharsRef();
+ BytesRefBuilder scratch = new BytesRefBuilder();
+ CharsRefBuilder scratchUTF16 = new CharsRefBuilder();
String fileName = IndexFileNames.fileNameFromGeneration(info.info.name, LIVEDOCS_EXTENSION, info.getDelGen());
ChecksumIndexInput in = null;
@@ -75,15 +77,15 @@ public class SimpleTextLiveDocsFormat extends LiveDocsFormat {
in = dir.openChecksumInput(fileName, context);
SimpleTextUtil.readLine(in, scratch);
- assert StringHelper.startsWith(scratch, SIZE);
- int size = parseIntAt(scratch, SIZE.length, scratchUTF16);
+ assert StringHelper.startsWith(scratch.get(), SIZE);
+ int size = parseIntAt(scratch.get(), SIZE.length, scratchUTF16);
BitSet bits = new BitSet(size);
SimpleTextUtil.readLine(in, scratch);
- while (!scratch.equals(END)) {
- assert StringHelper.startsWith(scratch, DOC);
- int docid = parseIntAt(scratch, DOC.length, scratchUTF16);
+ while (!scratch.get().equals(END)) {
+ assert StringHelper.startsWith(scratch.get(), DOC);
+ int docid = parseIntAt(scratch.get(), DOC.length, scratchUTF16);
bits.set(docid);
SimpleTextUtil.readLine(in, scratch);
}
@@ -101,16 +103,16 @@ public class SimpleTextLiveDocsFormat extends LiveDocsFormat {
}
}
- private int parseIntAt(BytesRef bytes, int offset, CharsRef scratch) {
- UnicodeUtil.UTF8toUTF16(bytes.bytes, bytes.offset+offset, bytes.length-offset, scratch);
- return ArrayUtil.parseInt(scratch.chars, 0, scratch.length);
+ private int parseIntAt(BytesRef bytes, int offset, CharsRefBuilder scratch) {
+ scratch.copyUTF8Bytes(bytes.bytes, bytes.offset + offset, bytes.length-offset);
+ return ArrayUtil.parseInt(scratch.chars(), 0, scratch.length());
}
@Override
public void writeLiveDocs(MutableBits bits, Directory dir, SegmentCommitInfo info, int newDelCount, IOContext context) throws IOException {
BitSet set = ((SimpleTextBits) bits).bits;
int size = bits.length();
- BytesRef scratch = new BytesRef();
+ BytesRefBuilder scratch = new BytesRefBuilder();
String fileName = IndexFileNames.fileNameFromGeneration(info.info.name, LIVEDOCS_EXTENSION, info.getNextDelGen());
IndexOutput out = null;
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextSegmentInfoReader.java b/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextSegmentInfoReader.java
index f00eec59f59..13a97e257be 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextSegmentInfoReader.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextSegmentInfoReader.java
@@ -39,7 +39,7 @@ import org.apache.lucene.index.SegmentInfo;
import org.apache.lucene.store.ChecksumIndexInput;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.IOContext;
-import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.StringHelper;
@@ -53,47 +53,47 @@ public class SimpleTextSegmentInfoReader extends SegmentInfoReader {
@Override
public SegmentInfo read(Directory directory, String segmentName, IOContext context) throws IOException {
- BytesRef scratch = new BytesRef();
+ BytesRefBuilder scratch = new BytesRefBuilder();
String segFileName = IndexFileNames.segmentFileName(segmentName, "", SimpleTextSegmentInfoFormat.SI_EXTENSION);
ChecksumIndexInput input = directory.openChecksumInput(segFileName, context);
boolean success = false;
try {
SimpleTextUtil.readLine(input, scratch);
- assert StringHelper.startsWith(scratch, SI_VERSION);
+ assert StringHelper.startsWith(scratch.get(), SI_VERSION);
final String version = readString(SI_VERSION.length, scratch);
SimpleTextUtil.readLine(input, scratch);
- assert StringHelper.startsWith(scratch, SI_DOCCOUNT);
+ assert StringHelper.startsWith(scratch.get(), SI_DOCCOUNT);
final int docCount = Integer.parseInt(readString(SI_DOCCOUNT.length, scratch));
SimpleTextUtil.readLine(input, scratch);
- assert StringHelper.startsWith(scratch, SI_USECOMPOUND);
+ assert StringHelper.startsWith(scratch.get(), SI_USECOMPOUND);
final boolean isCompoundFile = Boolean.parseBoolean(readString(SI_USECOMPOUND.length, scratch));
SimpleTextUtil.readLine(input, scratch);
- assert StringHelper.startsWith(scratch, SI_NUM_DIAG);
+ assert StringHelper.startsWith(scratch.get(), SI_NUM_DIAG);
int numDiag = Integer.parseInt(readString(SI_NUM_DIAG.length, scratch));
Map<String,String> diagnostics = new HashMap<>();
for (int i = 0; i < numDiag; i++) {
SimpleTextUtil.readLine(input, scratch);
- assert StringHelper.startsWith(scratch, SI_DIAG_KEY);
+ assert StringHelper.startsWith(scratch.get(), SI_DIAG_KEY);
String key = readString(SI_DIAG_KEY.length, scratch);
SimpleTextUtil.readLine(input, scratch);
- assert StringHelper.startsWith(scratch, SI_DIAG_VALUE);
+ assert StringHelper.startsWith(scratch.get(), SI_DIAG_VALUE);
String value = readString(SI_DIAG_VALUE.length, scratch);
diagnostics.put(key, value);
}
SimpleTextUtil.readLine(input, scratch);
- assert StringHelper.startsWith(scratch, SI_NUM_FILES);
+ assert StringHelper.startsWith(scratch.get(), SI_NUM_FILES);
int numFiles = Integer.parseInt(readString(SI_NUM_FILES.length, scratch));
Set<String> files = new HashSet<>();
for (int i = 0; i < numFiles; i++) {
SimpleTextUtil.readLine(input, scratch);
- assert StringHelper.startsWith(scratch, SI_FILE);
+ assert StringHelper.startsWith(scratch.get(), SI_FILE);
String fileName = readString(SI_FILE.length, scratch);
files.add(fileName);
}
@@ -114,7 +114,7 @@ public class SimpleTextSegmentInfoReader extends SegmentInfoReader {
}
}
- private String readString(int offset, BytesRef scratch) {
- return new String(scratch.bytes, scratch.offset+offset, scratch.length-offset, StandardCharsets.UTF_8);
+ private String readString(int offset, BytesRefBuilder scratch) {
+ return new String(scratch.bytes(), offset, scratch.length()-offset, StandardCharsets.UTF_8);
}
}
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextSegmentInfoWriter.java b/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextSegmentInfoWriter.java
index 362e25355e8..e8402391d98 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextSegmentInfoWriter.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextSegmentInfoWriter.java
@@ -29,6 +29,7 @@ import org.apache.lucene.store.Directory;
import org.apache.lucene.store.IOContext;
import org.apache.lucene.store.IndexOutput;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.IOUtils;
/**
@@ -58,7 +59,7 @@ public class SimpleTextSegmentInfoWriter extends SegmentInfoWriter {
IndexOutput output = dir.createOutput(segFileName, ioContext);
try {
- BytesRef scratch = new BytesRef();
+ BytesRefBuilder scratch = new BytesRefBuilder();
SimpleTextUtil.write(output, SI_VERSION);
SimpleTextUtil.write(output, si.getVersion(), scratch);
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextStoredFieldsReader.java b/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextStoredFieldsReader.java
index 9f9d512b931..9a0531ab363 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextStoredFieldsReader.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextStoredFieldsReader.java
@@ -34,7 +34,9 @@ import org.apache.lucene.store.IOContext;
import org.apache.lucene.store.IndexInput;
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.CharsRef;
+import org.apache.lucene.util.CharsRefBuilder;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.RamUsageEstimator;
import org.apache.lucene.util.StringHelper;
@@ -57,8 +59,8 @@ public class SimpleTextStoredFieldsReader extends StoredFieldsReader {
private long offsets[]; /* docid -> offset in .fld file */
private IndexInput in;
- private BytesRef scratch = new BytesRef();
- private CharsRef scratchUTF16 = new CharsRef();
+ private BytesRefBuilder scratch = new BytesRefBuilder();
+ private CharsRefBuilder scratchUTF16 = new CharsRefBuilder();
private final FieldInfos fieldInfos;
public SimpleTextStoredFieldsReader(Directory directory, SegmentInfo si, FieldInfos fn, IOContext context) throws IOException {
@@ -91,9 +93,9 @@ public class SimpleTextStoredFieldsReader extends StoredFieldsReader {
ChecksumIndexInput input = new BufferedChecksumIndexInput(in);
offsets = new long[size];
int upto = 0;
- while (!scratch.equals(END)) {
+ while (!scratch.get().equals(END)) {
SimpleTextUtil.readLine(input, scratch);
- if (StringHelper.startsWith(scratch, DOC)) {
+ if (StringHelper.startsWith(scratch.get(), DOC)) {
offsets[upto] = input.getFilePointer();
upto++;
}
@@ -108,28 +110,28 @@ public class SimpleTextStoredFieldsReader extends StoredFieldsReader {
while (true) {
readLine();
- if (StringHelper.startsWith(scratch, FIELD) == false) {
+ if (StringHelper.startsWith(scratch.get(), FIELD) == false) {
break;
}
int fieldNumber = parseIntAt(FIELD.length);
FieldInfo fieldInfo = fieldInfos.fieldInfo(fieldNumber);
readLine();
- assert StringHelper.startsWith(scratch, NAME);
+ assert StringHelper.startsWith(scratch.get(), NAME);
readLine();
- assert StringHelper.startsWith(scratch, TYPE);
+ assert StringHelper.startsWith(scratch.get(), TYPE);
final BytesRef type;
- if (equalsAt(TYPE_STRING, scratch, TYPE.length)) {
+ if (equalsAt(TYPE_STRING, scratch.get(), TYPE.length)) {
type = TYPE_STRING;
- } else if (equalsAt(TYPE_BINARY, scratch, TYPE.length)) {
+ } else if (equalsAt(TYPE_BINARY, scratch.get(), TYPE.length)) {
type = TYPE_BINARY;
- } else if (equalsAt(TYPE_INT, scratch, TYPE.length)) {
+ } else if (equalsAt(TYPE_INT, scratch.get(), TYPE.length)) {
type = TYPE_INT;
- } else if (equalsAt(TYPE_LONG, scratch, TYPE.length)) {
+ } else if (equalsAt(TYPE_LONG, scratch.get(), TYPE.length)) {
type = TYPE_LONG;
- } else if (equalsAt(TYPE_FLOAT, scratch, TYPE.length)) {
+ } else if (equalsAt(TYPE_FLOAT, scratch.get(), TYPE.length)) {
type = TYPE_FLOAT;
- } else if (equalsAt(TYPE_DOUBLE, scratch, TYPE.length)) {
+ } else if (equalsAt(TYPE_DOUBLE, scratch.get(), TYPE.length)) {
type = TYPE_DOUBLE;
} else {
throw new RuntimeException("unknown field type");
@@ -141,7 +143,7 @@ public class SimpleTextStoredFieldsReader extends StoredFieldsReader {
break;
case NO:
readLine();
- assert StringHelper.startsWith(scratch, VALUE);
+ assert StringHelper.startsWith(scratch.get(), VALUE);
break;
case STOP: return;
}
@@ -150,24 +152,24 @@ public class SimpleTextStoredFieldsReader extends StoredFieldsReader {
private void readField(BytesRef type, FieldInfo fieldInfo, StoredFieldVisitor visitor) throws IOException {
readLine();
- assert StringHelper.startsWith(scratch, VALUE);
+ assert StringHelper.startsWith(scratch.get(), VALUE);
if (type == TYPE_STRING) {
- visitor.stringField(fieldInfo, new String(scratch.bytes, scratch.offset+VALUE.length, scratch.length-VALUE.length, StandardCharsets.UTF_8));
+ visitor.stringField(fieldInfo, new String(scratch.bytes(), VALUE.length, scratch.length()-VALUE.length, StandardCharsets.UTF_8));
} else if (type == TYPE_BINARY) {
- byte[] copy = new byte[scratch.length-VALUE.length];
- System.arraycopy(scratch.bytes, scratch.offset+VALUE.length, copy, 0, copy.length);
+ byte[] copy = new byte[scratch.length()-VALUE.length];
+ System.arraycopy(scratch.bytes(), VALUE.length, copy, 0, copy.length);
visitor.binaryField(fieldInfo, copy);
} else if (type == TYPE_INT) {
- UnicodeUtil.UTF8toUTF16(scratch.bytes, scratch.offset+VALUE.length, scratch.length-VALUE.length, scratchUTF16);
+ scratchUTF16.copyUTF8Bytes(scratch.bytes(), VALUE.length, scratch.length()-VALUE.length);
visitor.intField(fieldInfo, Integer.parseInt(scratchUTF16.toString()));
} else if (type == TYPE_LONG) {
- UnicodeUtil.UTF8toUTF16(scratch.bytes, scratch.offset+VALUE.length, scratch.length-VALUE.length, scratchUTF16);
+ scratchUTF16.copyUTF8Bytes(scratch.bytes(), VALUE.length, scratch.length()-VALUE.length);
visitor.longField(fieldInfo, Long.parseLong(scratchUTF16.toString()));
} else if (type == TYPE_FLOAT) {
- UnicodeUtil.UTF8toUTF16(scratch.bytes, scratch.offset+VALUE.length, scratch.length-VALUE.length, scratchUTF16);
+ scratchUTF16.copyUTF8Bytes(scratch.bytes(), VALUE.length, scratch.length()-VALUE.length);
visitor.floatField(fieldInfo, Float.parseFloat(scratchUTF16.toString()));
} else if (type == TYPE_DOUBLE) {
- UnicodeUtil.UTF8toUTF16(scratch.bytes, scratch.offset+VALUE.length, scratch.length-VALUE.length, scratchUTF16);
+ scratchUTF16.copyUTF8Bytes(scratch.bytes(), VALUE.length, scratch.length()-VALUE.length);
visitor.doubleField(fieldInfo, Double.parseDouble(scratchUTF16.toString()));
}
}
@@ -195,8 +197,8 @@ public class SimpleTextStoredFieldsReader extends StoredFieldsReader {
}
private int parseIntAt(int offset) {
- UnicodeUtil.UTF8toUTF16(scratch.bytes, scratch.offset+offset, scratch.length-offset, scratchUTF16);
- return ArrayUtil.parseInt(scratchUTF16.chars, 0, scratchUTF16.length);
+ scratchUTF16.copyUTF8Bytes(scratch.bytes(), offset, scratch.length()-offset);
+ return ArrayUtil.parseInt(scratchUTF16.chars(), 0, scratchUTF16.length());
}
private boolean equalsAt(BytesRef a, BytesRef b, int bOffset) {
@@ -207,7 +209,7 @@ public class SimpleTextStoredFieldsReader extends StoredFieldsReader {
@Override
public long ramBytesUsed() {
return BASE_RAM_BYTES_USED + RamUsageEstimator.sizeOf(offsets)
- + RamUsageEstimator.sizeOf(scratch.bytes) + RamUsageEstimator.sizeOf(scratchUTF16.chars);
+ + RamUsageEstimator.sizeOf(scratch.bytes()) + RamUsageEstimator.sizeOf(scratchUTF16.chars());
}
@Override
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextStoredFieldsWriter.java b/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextStoredFieldsWriter.java
index 02149ce1666..31929c48fbc 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextStoredFieldsWriter.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextStoredFieldsWriter.java
@@ -28,6 +28,7 @@ import org.apache.lucene.store.Directory;
import org.apache.lucene.store.IOContext;
import org.apache.lucene.store.IndexOutput;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.IOUtils;
/**
@@ -58,7 +59,7 @@ public class SimpleTextStoredFieldsWriter extends StoredFieldsWriter {
final static BytesRef TYPE = new BytesRef(" type ");
final static BytesRef VALUE = new BytesRef(" value ");
- private final BytesRef scratch = new BytesRef();
+ private final BytesRefBuilder scratch = new BytesRefBuilder();
public SimpleTextStoredFieldsWriter(Directory directory, String segment, IOContext context) throws IOException {
this.directory = directory;
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextTermVectorsReader.java b/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextTermVectorsReader.java
index 2ec9f42a8fe..45794ee9762 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextTermVectorsReader.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextTermVectorsReader.java
@@ -41,11 +41,12 @@ import org.apache.lucene.store.IndexInput;
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.CharsRef;
+import org.apache.lucene.util.CharsRefBuilder;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.RamUsageEstimator;
import org.apache.lucene.util.StringHelper;
-import org.apache.lucene.util.UnicodeUtil;
import static org.apache.lucene.codecs.simpletext.SimpleTextTermVectorsWriter.*;
@@ -64,8 +65,8 @@ public class SimpleTextTermVectorsReader extends TermVectorsReader {
private long offsets[]; /* docid -> offset in .vec file */
private IndexInput in;
- private BytesRef scratch = new BytesRef();
- private CharsRef scratchUTF16 = new CharsRef();
+ private BytesRefBuilder scratch = new BytesRefBuilder();
+ private CharsRefBuilder scratchUTF16 = new CharsRefBuilder();
public SimpleTextTermVectorsReader(Directory directory, SegmentInfo si, IOContext context) throws IOException {
boolean success = false;
@@ -95,9 +96,9 @@ public class SimpleTextTermVectorsReader extends TermVectorsReader {
ChecksumIndexInput input = new BufferedChecksumIndexInput(in);
offsets = new long[maxDoc];
int upto = 0;
- while (!scratch.equals(END)) {
+ while (!scratch.get().equals(END)) {
SimpleTextUtil.readLine(input, scratch);
- if (StringHelper.startsWith(scratch, DOC)) {
+ if (StringHelper.startsWith(scratch.get(), DOC)) {
offsets[upto] = input.getFilePointer();
upto++;
}
@@ -111,54 +112,54 @@ public class SimpleTextTermVectorsReader extends TermVectorsReader {
SortedMap<String,SimpleTVTerms> fields = new TreeMap<>();
in.seek(offsets[doc]);
readLine();
- assert StringHelper.startsWith(scratch, NUMFIELDS);
+ assert StringHelper.startsWith(scratch.get(), NUMFIELDS);
int numFields = parseIntAt(NUMFIELDS.length);
if (numFields == 0) {
return null; // no vectors for this doc
}
for (int i = 0; i < numFields; i++) {
readLine();
- assert StringHelper.startsWith(scratch, FIELD);
+ assert StringHelper.startsWith(scratch.get(), FIELD);
// skip fieldNumber:
parseIntAt(FIELD.length);
readLine();
- assert StringHelper.startsWith(scratch, FIELDNAME);
+ assert StringHelper.startsWith(scratch.get(), FIELDNAME);
String fieldName = readString(FIELDNAME.length, scratch);
readLine();
- assert StringHelper.startsWith(scratch, FIELDPOSITIONS);
+ assert StringHelper.startsWith(scratch.get(), FIELDPOSITIONS);
boolean positions = Boolean.parseBoolean(readString(FIELDPOSITIONS.length, scratch));
readLine();
- assert StringHelper.startsWith(scratch, FIELDOFFSETS);
+ assert StringHelper.startsWith(scratch.get(), FIELDOFFSETS);
boolean offsets = Boolean.parseBoolean(readString(FIELDOFFSETS.length, scratch));
readLine();
- assert StringHelper.startsWith(scratch, FIELDPAYLOADS);
+ assert StringHelper.startsWith(scratch.get(), FIELDPAYLOADS);
boolean payloads = Boolean.parseBoolean(readString(FIELDPAYLOADS.length, scratch));
readLine();
- assert StringHelper.startsWith(scratch, FIELDTERMCOUNT);
+ assert StringHelper.startsWith(scratch.get(), FIELDTERMCOUNT);
int termCount = parseIntAt(FIELDTERMCOUNT.length);
SimpleTVTerms terms = new SimpleTVTerms(offsets, positions, payloads);
fields.put(fieldName, terms);
+ BytesRefBuilder term = new BytesRefBuilder();
for (int j = 0; j < termCount; j++) {
readLine();
- assert StringHelper.startsWith(scratch, TERMTEXT);
- BytesRef term = new BytesRef();
- int termLength = scratch.length - TERMTEXT.length;
+ assert StringHelper.startsWith(scratch.get(), TERMTEXT);
+ int termLength = scratch.length() - TERMTEXT.length;
term.grow(termLength);
- term.length = termLength;
- System.arraycopy(scratch.bytes, scratch.offset+TERMTEXT.length, term.bytes, term.offset, termLength);
+ term.setLength(termLength);
+ System.arraycopy(scratch.bytes(), TERMTEXT.length, term.bytes(), 0, termLength);
SimpleTVPostings postings = new SimpleTVPostings();
- terms.terms.put(term, postings);
+ terms.terms.put(term.toBytesRef(), postings);
readLine();
- assert StringHelper.startsWith(scratch, TERMFREQ);
+ assert StringHelper.startsWith(scratch.get(), TERMFREQ);
postings.freq = parseIntAt(TERMFREQ.length);
if (positions || offsets) {
@@ -177,16 +178,16 @@ public class SimpleTextTermVectorsReader extends TermVectorsReader {
for (int k = 0; k < postings.freq; k++) {
if (positions) {
readLine();
- assert StringHelper.startsWith(scratch, POSITION);
+ assert StringHelper.startsWith(scratch.get(), POSITION);
postings.positions[k] = parseIntAt(POSITION.length);
if (payloads) {
readLine();
- assert StringHelper.startsWith(scratch, PAYLOAD);
- if (scratch.length - PAYLOAD.length == 0) {
+ assert StringHelper.startsWith(scratch.get(), PAYLOAD);
+ if (scratch.length() - PAYLOAD.length == 0) {
postings.payloads[k] = null;
} else {
- byte payloadBytes[] = new byte[scratch.length - PAYLOAD.length];
- System.arraycopy(scratch.bytes, scratch.offset+PAYLOAD.length, payloadBytes, 0, payloadBytes.length);
+ byte payloadBytes[] = new byte[scratch.length() - PAYLOAD.length];
+ System.arraycopy(scratch.bytes(), PAYLOAD.length, payloadBytes, 0, payloadBytes.length);
postings.payloads[k] = new BytesRef(payloadBytes);
}
}
@@ -194,11 +195,11 @@ public class SimpleTextTermVectorsReader extends TermVectorsReader {
if (offsets) {
readLine();
- assert StringHelper.startsWith(scratch, STARTOFFSET);
+ assert StringHelper.startsWith(scratch.get(), STARTOFFSET);
postings.startOffsets[k] = parseIntAt(STARTOFFSET.length);
readLine();
- assert StringHelper.startsWith(scratch, ENDOFFSET);
+ assert StringHelper.startsWith(scratch.get(), ENDOFFSET);
postings.endOffsets[k] = parseIntAt(ENDOFFSET.length);
}
}
@@ -231,12 +232,12 @@ public class SimpleTextTermVectorsReader extends TermVectorsReader {
}
private int parseIntAt(int offset) {
- UnicodeUtil.UTF8toUTF16(scratch.bytes, scratch.offset+offset, scratch.length-offset, scratchUTF16);
- return ArrayUtil.parseInt(scratchUTF16.chars, 0, scratchUTF16.length);
+ scratchUTF16.copyUTF8Bytes(scratch.bytes(), offset, scratch.length()-offset);
+ return ArrayUtil.parseInt(scratchUTF16.chars(), 0, scratchUTF16.length());
}
- private String readString(int offset, BytesRef scratch) {
- UnicodeUtil.UTF8toUTF16(scratch.bytes, scratch.offset+offset, scratch.length-offset, scratchUTF16);
+ private String readString(int offset, BytesRefBuilder scratch) {
+ scratchUTF16.copyUTF8Bytes(scratch.bytes(), offset, scratch.length()-offset);
return scratchUTF16.toString();
}
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextTermVectorsWriter.java b/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextTermVectorsWriter.java
index 09d99cbccbd..88267255918 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextTermVectorsWriter.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextTermVectorsWriter.java
@@ -27,6 +27,7 @@ import org.apache.lucene.store.Directory;
import org.apache.lucene.store.IOContext;
import org.apache.lucene.store.IndexOutput;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.IOUtils;
/**
@@ -59,7 +60,7 @@ public class SimpleTextTermVectorsWriter extends TermVectorsWriter {
private final String segment;
private IndexOutput out;
private int numDocsWritten = 0;
- private final BytesRef scratch = new BytesRef();
+ private final BytesRefBuilder scratch = new BytesRefBuilder();
private boolean offsets;
private boolean positions;
private boolean payloads;
diff --git a/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextUtil.java b/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextUtil.java
index 30870feddd5..212f3d24674 100644
--- a/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextUtil.java
+++ b/lucene/codecs/src/java/org/apache/lucene/codecs/simpletext/SimpleTextUtil.java
@@ -26,6 +26,7 @@ import org.apache.lucene.store.DataInput;
import org.apache.lucene.store.DataOutput;
import org.apache.lucene.store.IndexOutput;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.StringHelper;
import org.apache.lucene.util.UnicodeUtil;
@@ -34,9 +35,9 @@ class SimpleTextUtil {
public final static byte ESCAPE = 92;
final static BytesRef CHECKSUM = new BytesRef("checksum ");
- public static void write(DataOutput out, String s, BytesRef scratch) throws IOException {
- UnicodeUtil.UTF16toUTF8(s, 0, s.length(), scratch);
- write(out, scratch);
+ public static void write(DataOutput out, String s, BytesRefBuilder scratch) throws IOException {
+ scratch.copyChars(s, 0, s.length());
+ write(out, scratch.get());
}
public static void write(DataOutput out, BytesRef b) throws IOException {
@@ -53,28 +54,25 @@ class SimpleTextUtil {
out.writeByte(NEWLINE);
}
- public static void readLine(DataInput in, BytesRef scratch) throws IOException {
+ public static void readLine(DataInput in, BytesRefBuilder scratch) throws IOException {
int upto = 0;
while(true) {
byte b = in.readByte();
- if (scratch.bytes.length == upto) {
- scratch.grow(1+upto);
- }
+ scratch.grow(1+upto);
if (b == ESCAPE) {
- scratch.bytes[upto++] = in.readByte();
+ scratch.setByteAt(upto++, in.readByte());
} else {
if (b == NEWLINE) {
break;
} else {
- scratch.bytes[upto++] = b;
+ scratch.setByteAt(upto++, b);
}
}
}
- scratch.offset = 0;
- scratch.length = upto;
+ scratch.setLength(upto);
}
- public static void writeChecksum(IndexOutput out, BytesRef scratch) throws IOException {
+ public static void writeChecksum(IndexOutput out, BytesRefBuilder scratch) throws IOException {
// Pad with zeros so different checksum values use the
// same number of bytes
// (BaseIndexFileFormatTestCase.testMergeStability cares):
@@ -85,13 +83,13 @@ class SimpleTextUtil {
}
public static void checkFooter(ChecksumIndexInput input) throws IOException {
- BytesRef scratch = new BytesRef();
+ BytesRefBuilder scratch = new BytesRefBuilder();
String expectedChecksum = String.format(Locale.ROOT, "%020d", input.getChecksum());
SimpleTextUtil.readLine(input, scratch);
- if (StringHelper.startsWith(scratch, CHECKSUM) == false) {
- throw new CorruptIndexException("SimpleText failure: expected checksum line but got " + scratch.utf8ToString() + " (resource=" + input + ")");
+ if (StringHelper.startsWith(scratch.get(), CHECKSUM) == false) {
+ throw new CorruptIndexException("SimpleText failure: expected checksum line but got " + scratch.get().utf8ToString() + " (resource=" + input + ")");
}
- String actualChecksum = new BytesRef(scratch.bytes, CHECKSUM.length, scratch.length - CHECKSUM.length).utf8ToString();
+ String actualChecksum = new BytesRef(scratch.bytes(), CHECKSUM.length, scratch.length() - CHECKSUM.length).utf8ToString();
if (!expectedChecksum.equals(actualChecksum)) {
throw new CorruptIndexException("SimpleText checksum failure: " + actualChecksum + " != " + expectedChecksum + " (resource=" + input + ")");
}
diff --git a/lucene/core/src/java/org/apache/lucene/analysis/NumericTokenStream.java b/lucene/core/src/java/org/apache/lucene/analysis/NumericTokenStream.java
index 231333b99dc..d851d449424 100644
--- a/lucene/core/src/java/org/apache/lucene/analysis/NumericTokenStream.java
+++ b/lucene/core/src/java/org/apache/lucene/analysis/NumericTokenStream.java
@@ -32,6 +32,7 @@ import org.apache.lucene.util.AttributeFactory;
import org.apache.lucene.util.AttributeImpl;
import org.apache.lucene.util.AttributeReflector;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.NumericUtils;
/**
@@ -146,7 +147,7 @@ public final class NumericTokenStream extends TokenStream {
public static final class NumericTermAttributeImpl extends AttributeImpl implements NumericTermAttribute,TermToBytesRefAttribute {
private long value = 0L;
private int valueSize = 0, shift = 0, precisionStep = 0;
- private BytesRef bytes = new BytesRef();
+ private BytesRefBuilder bytes = new BytesRefBuilder();
/**
* Creates, but does not yet initialize this attribute instance
@@ -156,7 +157,7 @@ public final class NumericTokenStream extends TokenStream {
@Override
public BytesRef getBytesRef() {
- return bytes;
+ return bytes.get();
}
@Override
@@ -167,6 +168,7 @@ public final class NumericTokenStream extends TokenStream {
} else {
NumericUtils.intToPrefixCoded((int) value, shift, bytes);
}
+ bytes.get();
}
@Override
@@ -200,7 +202,7 @@ public final class NumericTokenStream extends TokenStream {
@Override
public void reflectWith(AttributeReflector reflector) {
fillBytesRef();
- reflector.reflect(TermToBytesRefAttribute.class, "bytes", BytesRef.deepCopyOf(bytes));
+ reflector.reflect(TermToBytesRefAttribute.class, "bytes", bytes.toBytesRef());
reflector.reflect(NumericTermAttribute.class, "shift", shift);
reflector.reflect(NumericTermAttribute.class, "rawValue", getRawValue());
reflector.reflect(NumericTermAttribute.class, "valueSize", valueSize);
diff --git a/lucene/core/src/java/org/apache/lucene/analysis/tokenattributes/CharTermAttributeImpl.java b/lucene/core/src/java/org/apache/lucene/analysis/tokenattributes/CharTermAttributeImpl.java
index 484ec68130c..0ebd252b694 100644
--- a/lucene/core/src/java/org/apache/lucene/analysis/tokenattributes/CharTermAttributeImpl.java
+++ b/lucene/core/src/java/org/apache/lucene/analysis/tokenattributes/CharTermAttributeImpl.java
@@ -23,8 +23,8 @@ import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.AttributeImpl;
import org.apache.lucene.util.AttributeReflector;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.RamUsageEstimator;
-import org.apache.lucene.util.UnicodeUtil;
/** Default implementation of {@link CharTermAttribute}. */
public class CharTermAttributeImpl extends AttributeImpl implements CharTermAttribute, TermToBytesRefAttribute, Cloneable {
@@ -83,16 +83,17 @@ public class CharTermAttributeImpl extends AttributeImpl implements CharTermAttr
}
// *** TermToBytesRefAttribute interface ***
- private BytesRef bytes = new BytesRef(MIN_BUFFER_SIZE);
+ private BytesRefBuilder bytes = new BytesRefBuilder();
@Override
public void fillBytesRef() {
- UnicodeUtil.UTF16toUTF8(termBuffer, 0, termLength, bytes);
+ bytes.copyChars(termBuffer, 0, termLength);
+ bytes.get();
}
@Override
public BytesRef getBytesRef() {
- return bytes;
+ return bytes.get();
}
// *** CharSequence interface ***
@@ -228,7 +229,8 @@ public class CharTermAttributeImpl extends AttributeImpl implements CharTermAttr
// Do a deep clone
t.termBuffer = new char[this.termLength];
System.arraycopy(this.termBuffer, 0, t.termBuffer, 0, this.termLength);
- t.bytes = BytesRef.deepCopyOf(bytes);
+ t.bytes = new BytesRefBuilder();
+ t.bytes.copyBytes(bytes.get());
return t;
}
@@ -271,7 +273,7 @@ public class CharTermAttributeImpl extends AttributeImpl implements CharTermAttr
public void reflectWith(AttributeReflector reflector) {
reflector.reflect(CharTermAttribute.class, "term", toString());
fillBytesRef();
- reflector.reflect(TermToBytesRefAttribute.class, "bytes", BytesRef.deepCopyOf(bytes));
+ reflector.reflect(TermToBytesRefAttribute.class, "bytes", bytes.toBytesRef());
}
@Override
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/TermVectorsWriter.java b/lucene/core/src/java/org/apache/lucene/codecs/TermVectorsWriter.java
index c3a30193991..81ca327243b 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/TermVectorsWriter.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/TermVectorsWriter.java
@@ -33,6 +33,7 @@ import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.store.DataInput;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
/**
* Codec API for writing term vectors:
@@ -124,7 +125,7 @@ public abstract class TermVectorsWriter implements Closeable {
public void addProx(int numProx, DataInput positions, DataInput offsets) throws IOException {
int position = 0;
int lastOffset = 0;
- BytesRef payload = null;
+ BytesRefBuilder payload = null;
for (int i = 0; i < numProx; i++) {
final int startOffset;
@@ -142,15 +143,13 @@ public abstract class TermVectorsWriter implements Closeable {
final int payloadLength = positions.readVInt();
if (payload == null) {
- payload = new BytesRef();
- payload.bytes = new byte[payloadLength];
- } else if (payload.bytes.length < payloadLength) {
- payload.grow(payloadLength);
+ payload = new BytesRefBuilder();
}
+ payload.grow(payloadLength);
- positions.readBytes(payload.bytes, 0, payloadLength);
- payload.length = payloadLength;
- thisPayload = payload;
+ positions.readBytes(payload.bytes(), 0, payloadLength);
+ payload.setLength(payloadLength);
+ thisPayload = payload.get();
} else {
thisPayload = null;
}
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/blocktree/BlockTreeTermsWriter.java b/lucene/core/src/java/org/apache/lucene/codecs/blocktree/BlockTreeTermsWriter.java
index 9f6667b488e..39a1becfd01 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/blocktree/BlockTreeTermsWriter.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/blocktree/BlockTreeTermsWriter.java
@@ -38,9 +38,11 @@ import org.apache.lucene.store.IndexOutput;
import org.apache.lucene.store.RAMOutputStream;
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.FixedBitSet;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.IntsRef;
+import org.apache.lucene.util.IntsRefBuilder;
import org.apache.lucene.util.StringHelper;
import org.apache.lucene.util.fst.Builder;
import org.apache.lucene.util.fst.ByteSequenceOutputs;
@@ -459,7 +461,7 @@ public final class BlockTreeTermsWriter extends FieldsConsumer {
return "BLOCK: " + brToString(prefix);
}
- public void compileIndex(List<PendingBlock> blocks, RAMOutputStream scratchBytes, IntsRef scratchIntsRef) throws IOException {
+ public void compileIndex(List<PendingBlock> blocks, RAMOutputStream scratchBytes, IntsRefBuilder scratchIntsRef) throws IOException {
assert (isFloor && blocks.size() > 1) || (isFloor == false && blocks.size() == 1): "isFloor=" + isFloor + " blocks=" + blocks;
assert this == blocks.get(0);
@@ -524,7 +526,7 @@ public final class BlockTreeTermsWriter extends FieldsConsumer {
// TODO: maybe we could add bulk-add method to
// Builder? Takes FST and unions it w/ current
// FST.
- private void append(Builder<BytesRef> builder, FST<BytesRef> subIndex, IntsRef scratchIntsRef) throws IOException {
+ private void append(Builder<BytesRef> builder, FST<BytesRef> subIndex, IntsRefBuilder scratchIntsRef) throws IOException {
final BytesRefFSTEnum<BytesRef> subIndexEnum = new BytesRefFSTEnum<>(subIndex);
BytesRefFSTEnum.InputOutput<BytesRef> indexEnt;
while((indexEnt = subIndexEnum.next()) != null) {
@@ -537,7 +539,7 @@ public final class BlockTreeTermsWriter extends FieldsConsumer {
}
private final RAMOutputStream scratchBytes = new RAMOutputStream();
- private final IntsRef scratchIntsRef = new IntsRef();
+ private final IntsRefBuilder scratchIntsRef = new IntsRefBuilder();
class TermsWriter {
private final FieldInfo fieldInfo;
@@ -553,7 +555,7 @@ public final class BlockTreeTermsWriter extends FieldsConsumer {
// startsByPrefix[0] is the index into pending for the first
// term/sub-block starting with 't'. We use this to figure out when
// to write a new block:
- private final BytesRef lastTerm = new BytesRef();
+ private final BytesRefBuilder lastTerm = new BytesRefBuilder();
private int[] prefixStarts = new int[8];
private final long[] longs;
@@ -689,7 +691,7 @@ public final class BlockTreeTermsWriter extends FieldsConsumer {
boolean hasFloorLeadLabel = isFloor && floorLeadLabel != -1;
final BytesRef prefix = new BytesRef(prefixLength + (hasFloorLeadLabel ? 1 : 0));
- System.arraycopy(lastTerm.bytes, 0, prefix.bytes, 0, prefixLength);
+ System.arraycopy(lastTerm.get().bytes, 0, prefix.bytes, 0, prefixLength);
prefix.length = prefixLength;
// Write block header:
@@ -909,18 +911,18 @@ public final class BlockTreeTermsWriter extends FieldsConsumer {
/** Pushes the new term to the top of the stack, and writes new blocks. */
private void pushTerm(BytesRef text) throws IOException {
- int limit = Math.min(lastTerm.length, text.length);
+ int limit = Math.min(lastTerm.length(), text.length);
// Find common prefix between last term and current term:
int pos = 0;
- while (pos < limit && lastTerm.bytes[pos] == text.bytes[text.offset+pos]) {
+ while (pos < limit && lastTerm.byteAt(pos) == text.bytes[text.offset+pos]) {
pos++;
}
// if (DEBUG) System.out.println(" shared=" + pos + " lastTerm.length=" + lastTerm.length);
// Close the "abandoned" suffix now:
- for(int i=lastTerm.length-1;i>=pos;i--) {
+ for(int i=lastTerm.length()-1;i>=pos;i--) {
// How many items on top of the stack share the current suffix
// we are closing:
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/blocktree/SegmentTermsEnum.java b/lucene/core/src/java/org/apache/lucene/codecs/blocktree/SegmentTermsEnum.java
index 182587fc51d..32566deca6e 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/blocktree/SegmentTermsEnum.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/blocktree/SegmentTermsEnum.java
@@ -31,10 +31,9 @@ import org.apache.lucene.store.IndexInput;
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.RamUsageEstimator;
-import org.apache.lucene.util.fst.ByteSequenceOutputs;
import org.apache.lucene.util.fst.FST;
-import org.apache.lucene.util.fst.Outputs;
import org.apache.lucene.util.fst.Util;
/** Iterates through terms in this field */
@@ -62,7 +61,7 @@ final class SegmentTermsEnum extends TermsEnum {
// assert only:
private boolean eof;
- final BytesRef term = new BytesRef();
+ final BytesRefBuilder term = new BytesRefBuilder();
private final FST.BytesReader fstReader;
@SuppressWarnings({"rawtypes","unchecked"}) private FST.Arc<BytesRef>[] arcs = new FST.Arc[1];
@@ -173,7 +172,7 @@ final class SegmentTermsEnum extends TermsEnum {
while(true) {
if (currentFrame.next()) {
// Push to new block:
- currentFrame = pushFrame(null, currentFrame.lastSubFP, term.length);
+ currentFrame = pushFrame(null, currentFrame.lastSubFP, term.length());
currentFrame.fpOrig = currentFrame.fp;
// This is a "next" frame -- even if it's
// floor'd we must pretend it isn't so we don't
@@ -183,7 +182,7 @@ final class SegmentTermsEnum extends TermsEnum {
currentFrame.loadBlock();
stats.startBlock(currentFrame, !currentFrame.isLastInFloor);
} else {
- stats.term(term);
+ stats.term(term.get());
break;
}
}
@@ -204,7 +203,7 @@ final class SegmentTermsEnum extends TermsEnum {
currentFrame.rewind();
currentFrame.loadBlock();
validIndexPrefix = 0;
- term.length = 0;
+ term.clear();
return stats;
}
@@ -317,9 +316,7 @@ final class SegmentTermsEnum extends TermsEnum {
throw new IllegalStateException("terms index was not loaded");
}
- if (term.bytes.length <= target.length) {
- term.bytes = ArrayUtil.grow(term.bytes, 1+target.length);
- }
+ term.grow(1 + target.length);
assert clearEOF();
@@ -353,7 +350,7 @@ final class SegmentTermsEnum extends TermsEnum {
targetUpto = 0;
SegmentTermsEnumFrame lastFrame = stack[0];
- assert validIndexPrefix <= term.length;
+ assert validIndexPrefix <= term.length();
final int targetLimit = Math.min(target.length, validIndexPrefix);
@@ -364,7 +361,7 @@ final class SegmentTermsEnum extends TermsEnum {
// First compare up to valid seek frames:
while (targetUpto < targetLimit) {
- cmp = (term.bytes[targetUpto]&0xFF) - (target.bytes[target.offset + targetUpto]&0xFF);
+ cmp = (term.byteAt(targetUpto)&0xFF) - (target.bytes[target.offset + targetUpto]&0xFF);
// if (DEBUG) {
// System.out.println(" cycle targetUpto=" + targetUpto + " (vs limit=" + targetLimit + ") cmp=" + cmp + " (targetLabel=" + (char) (target.bytes[target.offset + targetUpto]) + " vs termLabel=" + (char) (term.bytes[targetUpto]) + ")" + " arc.output=" + arc.output + " output=" + output);
// }
@@ -389,9 +386,9 @@ final class SegmentTermsEnum extends TermsEnum {
// don't save arc/output/frame; we only do this
// to find out if the target term is before,
// equal or after the current term
- final int targetLimit2 = Math.min(target.length, term.length);
+ final int targetLimit2 = Math.min(target.length, term.length());
while (targetUpto < targetLimit2) {
- cmp = (term.bytes[targetUpto]&0xFF) - (target.bytes[target.offset + targetUpto]&0xFF);
+ cmp = (term.byteAt(targetUpto)&0xFF) - (target.bytes[target.offset + targetUpto]&0xFF);
// if (DEBUG) {
// System.out.println(" cycle2 targetUpto=" + targetUpto + " (vs limit=" + targetLimit + ") cmp=" + cmp + " (targetLabel=" + (char) (target.bytes[target.offset + targetUpto]) + " vs termLabel=" + (char) (term.bytes[targetUpto]) + ")");
// }
@@ -402,7 +399,7 @@ final class SegmentTermsEnum extends TermsEnum {
}
if (cmp == 0) {
- cmp = term.length - target.length;
+ cmp = term.length() - target.length;
}
targetUpto = targetUptoMid;
}
@@ -429,7 +426,7 @@ final class SegmentTermsEnum extends TermsEnum {
currentFrame.rewind();
} else {
// Target is exactly the same as current term
- assert term.length == target.length;
+ assert term.length() == target.length;
if (termExists) {
// if (DEBUG) {
// System.out.println(" target is same as current; return true");
@@ -492,8 +489,8 @@ final class SegmentTermsEnum extends TermsEnum {
if (!currentFrame.hasTerms) {
termExists = false;
- term.bytes[targetUpto] = (byte) targetLabel;
- term.length = 1+targetUpto;
+ term.setByteAt(targetUpto, (byte) targetLabel);
+ term.setLength(1+targetUpto);
// if (DEBUG) {
// System.out.println(" FAST NOT_FOUND term=" + brToString(term));
// }
@@ -517,7 +514,7 @@ final class SegmentTermsEnum extends TermsEnum {
} else {
// Follow this arc
arc = nextArc;
- term.bytes[targetUpto] = (byte) targetLabel;
+ term.setByteAt(targetUpto, (byte) targetLabel);
// Aggregate output as we go:
assert arc.output != null;
if (arc.output != BlockTreeTermsWriter.NO_OUTPUT) {
@@ -545,7 +542,7 @@ final class SegmentTermsEnum extends TermsEnum {
// Target term is entirely contained in the index:
if (!currentFrame.hasTerms) {
termExists = false;
- term.length = targetUpto;
+ term.setLength(targetUpto);
// if (DEBUG) {
// System.out.println(" FAST NOT_FOUND term=" + brToString(term));
// }
@@ -574,10 +571,8 @@ final class SegmentTermsEnum extends TermsEnum {
if (fr.index == null) {
throw new IllegalStateException("terms index was not loaded");
}
-
- if (term.bytes.length <= target.length) {
- term.bytes = ArrayUtil.grow(term.bytes, 1+target.length);
- }
+
+ term.grow(1 + target.length);
assert clearEOF();
@@ -611,7 +606,7 @@ final class SegmentTermsEnum extends TermsEnum {
targetUpto = 0;
SegmentTermsEnumFrame lastFrame = stack[0];
- assert validIndexPrefix <= term.length;
+ assert validIndexPrefix <= term.length();
final int targetLimit = Math.min(target.length, validIndexPrefix);
@@ -622,7 +617,7 @@ final class SegmentTermsEnum extends TermsEnum {
// First compare up to valid seek frames:
while (targetUpto < targetLimit) {
- cmp = (term.bytes[targetUpto]&0xFF) - (target.bytes[target.offset + targetUpto]&0xFF);
+ cmp = (term.byteAt(targetUpto)&0xFF) - (target.bytes[target.offset + targetUpto]&0xFF);
//if (DEBUG) {
//System.out.println(" cycle targetUpto=" + targetUpto + " (vs limit=" + targetLimit + ") cmp=" + cmp + " (targetLabel=" + (char) (target.bytes[target.offset + targetUpto]) + " vs termLabel=" + (char) (term.bytes[targetUpto]) + ")" + " arc.output=" + arc.output + " output=" + output);
//}
@@ -650,9 +645,9 @@ final class SegmentTermsEnum extends TermsEnum {
final int targetUptoMid = targetUpto;
// Second compare the rest of the term, but
// don't save arc/output/frame:
- final int targetLimit2 = Math.min(target.length, term.length);
+ final int targetLimit2 = Math.min(target.length, term.length());
while (targetUpto < targetLimit2) {
- cmp = (term.bytes[targetUpto]&0xFF) - (target.bytes[target.offset + targetUpto]&0xFF);
+ cmp = (term.byteAt(targetUpto)&0xFF) - (target.bytes[target.offset + targetUpto]&0xFF);
//if (DEBUG) {
//System.out.println(" cycle2 targetUpto=" + targetUpto + " (vs limit=" + targetLimit + ") cmp=" + cmp + " (targetLabel=" + (char) (target.bytes[target.offset + targetUpto]) + " vs termLabel=" + (char) (term.bytes[targetUpto]) + ")");
//}
@@ -663,7 +658,7 @@ final class SegmentTermsEnum extends TermsEnum {
}
if (cmp == 0) {
- cmp = term.length - target.length;
+ cmp = term.length() - target.length;
}
targetUpto = targetUptoMid;
}
@@ -690,7 +685,7 @@ final class SegmentTermsEnum extends TermsEnum {
currentFrame.rewind();
} else {
// Target is exactly the same as current term
- assert term.length == target.length;
+ assert term.length() == target.length;
if (termExists) {
//if (DEBUG) {
//System.out.println(" target is same as current; return FOUND");
@@ -774,7 +769,7 @@ final class SegmentTermsEnum extends TermsEnum {
}
} else {
// Follow this arc
- term.bytes[targetUpto] = (byte) targetLabel;
+ term.setByteAt(targetUpto, (byte) targetLabel);
arc = nextArc;
// Aggregate output as we go:
assert arc.output != null;
@@ -834,7 +829,7 @@ final class SegmentTermsEnum extends TermsEnum {
while(true) {
SegmentTermsEnumFrame f = getFrame(ord);
assert f != null;
- final BytesRef prefix = new BytesRef(term.bytes, 0, f.prefix);
+ final BytesRef prefix = new BytesRef(term.get().bytes, 0, f.prefix);
if (f.nextEnt == -1) {
out.println(" frame " + (isSeekFrame ? "(seek)" : "(next)") + " ord=" + ord + " fp=" + f.fp + (f.isFloor ? (" (fpOrig=" + f.fpOrig + ")") : "") + " prefixLen=" + f.prefix + " prefix=" + prefix + (f.nextEnt == -1 ? "" : (" (of " + f.entCount + ")")) + " hasTerms=" + f.hasTerms + " isFloor=" + f.isFloor + " code=" + ((f.fp<<BlockTreeTermsWriter.OUTPUT_FLAGS_NUM_BITS) + (f.hasTerms ? BlockTreeTermsWriter.OUTPUT_FLAG_HAS_TERMS:0) + (f.isFloor ? BlockTreeTermsWriter.OUTPUT_FLAG_IS_FLOOR:0)) + " isLastInFloor=" + f.isLastInFloor + " mdUpto=" + f.metaDataUpto + " tbOrd=" + f.getTermBlockOrd());
} else {
@@ -842,8 +837,8 @@ final class SegmentTermsEnum extends TermsEnum {
}
if (fr.index != null) {
assert !isSeekFrame || f.arc != null: "isSeekFrame=" + isSeekFrame + " f.arc=" + f.arc;
- if (f.prefix > 0 && isSeekFrame && f.arc.label != (term.bytes[f.prefix-1]&0xFF)) {
- out.println(" broken seek state: arc.label=" + (char) f.arc.label + " vs term byte=" + (char) (term.bytes[f.prefix-1]&0xFF));
+ if (f.prefix > 0 && isSeekFrame && f.arc.label != (term.byteAt(f.prefix-1)&0xFF)) {
+ out.println(" broken seek state: arc.label=" + (char) f.arc.label + " vs term byte=" + (char) (term.byteAt(f.prefix-1)&0xFF));
throw new RuntimeException("seek state is broken");
}
BytesRef output = Util.get(fr.index, prefix);
@@ -906,7 +901,7 @@ final class SegmentTermsEnum extends TermsEnum {
// this method catches up all internal state so next()
// works properly:
//if (DEBUG) System.out.println(" re-seek to pending term=" + term.utf8ToString() + " " + term);
- final boolean result = seekExact(term);
+ final boolean result = seekExact(term.get());
assert result;
}
@@ -919,7 +914,7 @@ final class SegmentTermsEnum extends TermsEnum {
if (currentFrame.ord == 0) {
//if (DEBUG) System.out.println(" return null");
assert setEOF();
- term.length = 0;
+ term.clear();
validIndexPrefix = 0;
currentFrame.rewind();
termExists = false;
@@ -931,7 +926,7 @@ final class SegmentTermsEnum extends TermsEnum {
if (currentFrame.nextEnt == -1 || currentFrame.lastSubFP != lastFP) {
// We popped into a frame that's not loaded
// yet or not scan'd to the right entry
- currentFrame.scanToFloorFrame(term);
+ currentFrame.scanToFloorFrame(term.get());
currentFrame.loadBlock();
currentFrame.scanToSubBlock(lastFP);
}
@@ -949,7 +944,7 @@ final class SegmentTermsEnum extends TermsEnum {
if (currentFrame.next()) {
// Push to new block:
//if (DEBUG) System.out.println(" push frame");
- currentFrame = pushFrame(null, currentFrame.lastSubFP, term.length);
+ currentFrame = pushFrame(null, currentFrame.lastSubFP, term.length());
// This is a "next" frame -- even if it's
// floor'd we must pretend it isn't so we don't
// try to scan to the right floor frame:
@@ -958,7 +953,7 @@ final class SegmentTermsEnum extends TermsEnum {
currentFrame.loadBlock();
} else {
//if (DEBUG) System.out.println(" return term=" + term.utf8ToString() + " " + term + " currentFrame.ord=" + currentFrame.ord);
- return term;
+ return term.get();
}
}
}
@@ -966,7 +961,7 @@ final class SegmentTermsEnum extends TermsEnum {
@Override
public BytesRef term() {
assert !eof;
- return term;
+ return term.get();
}
@Override
@@ -1016,7 +1011,7 @@ final class SegmentTermsEnum extends TermsEnum {
// System.out.println("BTTR.seekExact termState seg=" + segment + " target=" + target.utf8ToString() + " " + target + " state=" + otherState);
// }
assert clearEOF();
- if (target.compareTo(term) != 0 || !termExists) {
+ if (target.compareTo(term.get()) != 0 || !termExists) {
assert otherState != null && otherState instanceof BlockTermState;
currentFrame = staticFrame;
currentFrame.state.copyFrom(otherState);
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/blocktree/SegmentTermsEnumFrame.java b/lucene/core/src/java/org/apache/lucene/codecs/blocktree/SegmentTermsEnumFrame.java
index c888b1339b7..f69220e0d9a 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/blocktree/SegmentTermsEnumFrame.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/blocktree/SegmentTermsEnumFrame.java
@@ -273,11 +273,9 @@ final class SegmentTermsEnumFrame {
nextEnt++;
suffix = suffixesReader.readVInt();
startBytePos = suffixesReader.getPosition();
- ste.term.length = prefix + suffix;
- if (ste.term.bytes.length < ste.term.length) {
- ste.term.grow(ste.term.length);
- }
- suffixesReader.readBytes(ste.term.bytes, prefix, suffix);
+ ste.term.setLength(prefix + suffix);
+ ste.term.grow(ste.term.length());
+ suffixesReader.readBytes(ste.term.bytes(), prefix, suffix);
// A normal term
ste.termExists = true;
return false;
@@ -290,11 +288,9 @@ final class SegmentTermsEnumFrame {
final int code = suffixesReader.readVInt();
suffix = code >>> 1;
startBytePos = suffixesReader.getPosition();
- ste.term.length = prefix + suffix;
- if (ste.term.bytes.length < ste.term.length) {
- ste.term.grow(ste.term.length);
- }
- suffixesReader.readBytes(ste.term.bytes, prefix, suffix);
+ ste.term.setLength(prefix + suffix);
+ ste.term.grow(ste.term.length());
+ suffixesReader.readBytes(ste.term.bytes(), prefix, suffix);
if ((code & 1) == 0) {
// A normal term
ste.termExists = true;
@@ -426,7 +422,7 @@ final class SegmentTermsEnumFrame {
// Used only by assert
private boolean prefixMatches(BytesRef target) {
for(int bytePos=0;bytePos<prefix;bytePos++) {
- if (target.bytes[target.offset + bytePos] != ste.term.bytes[bytePos]) {
+ if (target.bytes[target.offset + bytePos] != ste.term.byteAt(bytePos)) {
return false;
}
}
@@ -681,7 +677,7 @@ final class SegmentTermsEnumFrame {
ste.currentFrame = ste.pushFrame(null, ste.currentFrame.lastSubFP, termLen);
ste.currentFrame.loadBlock();
while (ste.currentFrame.next()) {
- ste.currentFrame = ste.pushFrame(null, ste.currentFrame.lastSubFP, ste.term.length);
+ ste.currentFrame = ste.pushFrame(null, ste.currentFrame.lastSubFP, ste.term.length());
ste.currentFrame.loadBlock();
}
}
@@ -725,10 +721,8 @@ final class SegmentTermsEnumFrame {
private void fillTerm() {
final int termLength = prefix + suffix;
- ste.term.length = prefix + suffix;
- if (ste.term.bytes.length < termLength) {
- ste.term.grow(termLength);
- }
- System.arraycopy(suffixBytes, startBytePos, ste.term.bytes, prefix, suffix);
+ ste.term.setLength(termLength);
+ ste.term.grow(termLength);
+ System.arraycopy(suffixBytes, startBytePos, ste.term.bytes(), prefix, suffix);
}
}
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene40/Lucene40PostingsReader.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene40/Lucene40PostingsReader.java
index aefed2ddbca..0730d7b288d 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene40/Lucene40PostingsReader.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene40/Lucene40PostingsReader.java
@@ -31,14 +31,13 @@ import org.apache.lucene.index.FieldInfos;
import org.apache.lucene.index.IndexFileNames;
import org.apache.lucene.index.SegmentInfo;
import org.apache.lucene.index.TermState;
-import org.apache.lucene.store.ByteArrayDataInput;
import org.apache.lucene.store.DataInput;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.IOContext;
import org.apache.lucene.store.IndexInput;
-import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.IOUtils;
/**
@@ -890,7 +889,7 @@ public class Lucene40PostingsReader extends PostingsReaderBase {
boolean skipped;
Lucene40SkipListReader skipper;
- private BytesRef payload;
+ private BytesRefBuilder payload;
private long lazyProxPointer;
boolean storePayloads;
@@ -911,8 +910,7 @@ public class Lucene40PostingsReader extends PostingsReaderBase {
assert fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0;
assert storePayloads || storeOffsets;
if (payload == null) {
- payload = new BytesRef();
- payload.bytes = new byte[1];
+ payload = new BytesRefBuilder();
}
this.liveDocs = liveDocs;
@@ -1142,16 +1140,14 @@ public class Lucene40PostingsReader extends PostingsReaderBase {
assert posPendingCount < freq;
if (payloadPending) {
- if (payloadLength > payload.bytes.length) {
- payload.grow(payloadLength);
- }
+ payload.grow(payloadLength);
- proxIn.readBytes(payload.bytes, 0, payloadLength);
- payload.length = payloadLength;
+ proxIn.readBytes(payload.bytes(), 0, payloadLength);
+ payload.setLength(payloadLength);
payloadPending = false;
}
- return payload;
+ return payload.get();
} else {
return null;
}
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene40/Lucene40TermVectorsReader.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene40/Lucene40TermVectorsReader.java
index 040b844f5de..c04d10dc828 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene40/Lucene40TermVectorsReader.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene40/Lucene40TermVectorsReader.java
@@ -41,6 +41,7 @@ import org.apache.lucene.store.IOContext;
import org.apache.lucene.store.IndexInput;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.IOUtils;
/**
@@ -386,8 +387,8 @@ public class Lucene40TermVectorsReader extends TermVectorsReader implements Clos
private int numTerms;
private int nextTerm;
private int freq;
- private BytesRef lastTerm = new BytesRef();
- private BytesRef term = new BytesRef();
+ private BytesRefBuilder lastTerm = new BytesRefBuilder();
+ private BytesRefBuilder term = new BytesRefBuilder();
private boolean storePositions;
private boolean storeOffsets;
private boolean storePayloads;
@@ -433,7 +434,7 @@ public class Lucene40TermVectorsReader extends TermVectorsReader implements Clos
public SeekStatus seekCeil(BytesRef text)
throws IOException {
if (nextTerm != 0) {
- final int cmp = text.compareTo(term);
+ final int cmp = text.compareTo(term.get());
if (cmp < 0) {
nextTerm = 0;
tvf.seek(tvfFP);
@@ -443,7 +444,7 @@ public class Lucene40TermVectorsReader extends TermVectorsReader implements Clos
}
while (next() != null) {
- final int cmp = text.compareTo(term);
+ final int cmp = text.compareTo(term.get());
if (cmp < 0) {
return SeekStatus.NOT_FOUND;
} else if (cmp == 0) {
@@ -464,12 +465,12 @@ public class Lucene40TermVectorsReader extends TermVectorsReader implements Clos
if (nextTerm >= numTerms) {
return null;
}
- term.copyBytes(lastTerm);
+ term.copyBytes(lastTerm.get());
final int start = tvf.readVInt();
final int deltaLen = tvf.readVInt();
- term.length = start + deltaLen;
- term.grow(term.length);
- tvf.readBytes(term.bytes, start, deltaLen);
+ term.setLength(start + deltaLen);
+ term.grow(term.length());
+ tvf.readBytes(term.bytes(), start, deltaLen);
freq = tvf.readVInt();
if (storePayloads) {
@@ -513,14 +514,14 @@ public class Lucene40TermVectorsReader extends TermVectorsReader implements Clos
}
}
- lastTerm.copyBytes(term);
+ lastTerm.copyBytes(term.get());
nextTerm++;
- return term;
+ return term.get();
}
@Override
public BytesRef term() {
- return term;
+ return term.get();
}
@Override
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene40/Lucene40TermVectorsWriter.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene40/Lucene40TermVectorsWriter.java
index 0ce958133fd..243c72b144e 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene40/Lucene40TermVectorsWriter.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene40/Lucene40TermVectorsWriter.java
@@ -36,6 +36,7 @@ import org.apache.lucene.store.IndexOutput;
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.StringHelper;
@@ -110,7 +111,7 @@ public final class Lucene40TermVectorsWriter extends TermVectorsWriter {
this.positions = positions;
this.offsets = offsets;
this.payloads = payloads;
- lastTerm.length = 0;
+ lastTerm.clear();
lastPayloadLength = -1; // force first payload to write its length
fps[fieldCount++] = tvf.getFilePointer();
tvd.writeVInt(info.number);
@@ -133,13 +134,13 @@ public final class Lucene40TermVectorsWriter extends TermVectorsWriter {
}
}
- private final BytesRef lastTerm = new BytesRef(10);
+ private final BytesRefBuilder lastTerm = new BytesRefBuilder();
// NOTE: we override addProx, so we don't need to buffer when indexing.
// we also don't buffer during bulk merges.
private int offsetStartBuffer[] = new int[10];
private int offsetEndBuffer[] = new int[10];
- private BytesRef payloadData = new BytesRef(10);
+ private BytesRefBuilder payloadData = new BytesRefBuilder();
private int bufferedIndex = 0;
private int bufferedFreq = 0;
private boolean positions = false;
@@ -148,7 +149,7 @@ public final class Lucene40TermVectorsWriter extends TermVectorsWriter {
@Override
public void startTerm(BytesRef term, int freq) throws IOException {
- final int prefix = StringHelper.bytesDifference(lastTerm, term);
+ final int prefix = StringHelper.bytesDifference(lastTerm.get(), term);
final int suffix = term.length - prefix;
tvf.writeVInt(prefix);
tvf.writeVInt(suffix);
@@ -164,14 +165,14 @@ public final class Lucene40TermVectorsWriter extends TermVectorsWriter {
}
bufferedIndex = 0;
bufferedFreq = freq;
- payloadData.length = 0;
+ payloadData.clear();
}
int lastPosition = 0;
int lastOffset = 0;
int lastPayloadLength = -1; // force first payload to write its length
- BytesRef scratch = new BytesRef(); // used only by this optimized flush below
+ BytesRefBuilder scratch = new BytesRefBuilder(); // used only by this optimized flush below
@Override
public void addProx(int numProx, DataInput positions, DataInput offsets) throws IOException {
@@ -183,14 +184,14 @@ public final class Lucene40TermVectorsWriter extends TermVectorsWriter {
if ((code & 1) == 1) {
int length = positions.readVInt();
scratch.grow(length);
- scratch.length = length;
- positions.readBytes(scratch.bytes, scratch.offset, scratch.length);
- writePosition(code >>> 1, scratch);
+ scratch.setLength(length);
+ positions.readBytes(scratch.bytes(), 0, scratch.length());
+ writePosition(code >>> 1, scratch.get());
} else {
writePosition(code >>> 1, null);
}
}
- tvf.writeBytes(payloadData.bytes, payloadData.offset, payloadData.length);
+ tvf.writeBytes(payloadData.bytes(), 0, payloadData.length());
} else if (positions != null) {
// pure positions, no payloads
for (int i = 0; i < numProx; i++) {
@@ -239,7 +240,7 @@ public final class Lucene40TermVectorsWriter extends TermVectorsWriter {
assert positions && (offsets || payloads);
assert bufferedIndex == bufferedFreq;
if (payloads) {
- tvf.writeBytes(payloadData.bytes, payloadData.offset, payloadData.length);
+ tvf.writeBytes(payloadData.bytes(), 0, payloadData.length());
}
if (offsets) {
for (int i = 0; i < bufferedIndex; i++) {
@@ -263,7 +264,7 @@ public final class Lucene40TermVectorsWriter extends TermVectorsWriter {
tvf.writeVInt(delta << 1);
}
if (payloadLength > 0) {
- if (payloadLength + payloadData.length < 0) {
+ if (payloadLength + payloadData.length() < 0) {
// we overflowed the payload buffer, just throw UOE
// having > Integer.MAX_VALUE bytes of payload for a single term in a single doc is nuts.
throw new UnsupportedOperationException("A term cannot have more than Integer.MAX_VALUE bytes of payload data in a single document");
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene42/Lucene42DocValuesProducer.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene42/Lucene42DocValuesProducer.java
index fffb702401c..ef7ed68f213 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene42/Lucene42DocValuesProducer.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene42/Lucene42DocValuesProducer.java
@@ -41,11 +41,12 @@ import org.apache.lucene.index.TermsEnum;
import org.apache.lucene.store.ByteArrayDataInput;
import org.apache.lucene.store.ChecksumIndexInput;
import org.apache.lucene.store.IndexInput;
-import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.IntsRef;
+import org.apache.lucene.util.IntsRefBuilder;
import org.apache.lucene.util.PagedBytes;
import org.apache.lucene.util.RamUsageEstimator;
import org.apache.lucene.util.fst.BytesRefFSTEnum;
@@ -345,12 +346,12 @@ class Lucene42DocValuesProducer extends DocValuesProducer {
final BytesReader in = fst.getBytesReader();
final Arc<Long> firstArc = new Arc<>();
final Arc<Long> scratchArc = new Arc<>();
- final IntsRef scratchInts = new IntsRef();
+ final IntsRefBuilder scratchInts = new IntsRefBuilder();
final BytesRefFSTEnum<Long> fstEnum = new BytesRefFSTEnum<>(fst);
return new SortedDocValues() {
- final BytesRef term = new BytesRef();
+ final BytesRefBuilder term = new BytesRefBuilder();
@Override
public int getOrd(int docID) {
@@ -363,9 +364,8 @@ class Lucene42DocValuesProducer extends DocValuesProducer {
in.setPosition(0);
fst.getFirstArc(firstArc);
IntsRef output = Util.getByOutput(fst, ord, in, firstArc, scratchArc, scratchInts);
- term.bytes = ArrayUtil.grow(term.bytes, output.length);
- term.offset = 0;
- term.length = 0;
+ term.grow(output.length);
+ term.clear();
return Util.toBytesRef(output, term);
} catch (IOException bogus) {
throw new RuntimeException(bogus);
@@ -423,11 +423,11 @@ class Lucene42DocValuesProducer extends DocValuesProducer {
final BytesReader in = fst.getBytesReader();
final Arc<Long> firstArc = new Arc<>();
final Arc<Long> scratchArc = new Arc<>();
- final IntsRef scratchInts = new IntsRef();
+ final IntsRefBuilder scratchInts = new IntsRefBuilder();
final BytesRefFSTEnum<Long> fstEnum = new BytesRefFSTEnum<>(fst);
final ByteArrayDataInput input = new ByteArrayDataInput();
return new SortedSetDocValues() {
- final BytesRef term = new BytesRef();
+ final BytesRefBuilder term = new BytesRefBuilder();
BytesRef ordsRef;
long currentOrd;
@@ -454,9 +454,8 @@ class Lucene42DocValuesProducer extends DocValuesProducer {
in.setPosition(0);
fst.getFirstArc(firstArc);
IntsRef output = Util.getByOutput(fst, ord, in, firstArc, scratchArc, scratchInts);
- term.bytes = ArrayUtil.grow(term.bytes, output.length);
- term.offset = 0;
- term.length = 0;
+ term.grow(output.length);
+ term.clear();
return Util.toBytesRef(output, term);
} catch (IOException bogus) {
throw new RuntimeException(bogus);
@@ -540,8 +539,8 @@ class Lucene42DocValuesProducer extends DocValuesProducer {
final FST.BytesReader bytesReader;
final Arc<Long> firstArc = new Arc<>();
final Arc<Long> scratchArc = new Arc<>();
- final IntsRef scratchInts = new IntsRef();
- final BytesRef scratchBytes = new BytesRef();
+ final IntsRefBuilder scratchInts = new IntsRefBuilder();
+ final BytesRefBuilder scratchBytes = new BytesRefBuilder();
FSTTermsEnum(FST<Long> fst) {
this.fst = fst;
@@ -588,12 +587,11 @@ class Lucene42DocValuesProducer extends DocValuesProducer {
bytesReader.setPosition(0);
fst.getFirstArc(firstArc);
IntsRef output = Util.getByOutput(fst, ord, bytesReader, firstArc, scratchArc, scratchInts);
- scratchBytes.bytes = new byte[output.length];
- scratchBytes.offset = 0;
- scratchBytes.length = 0;
+ BytesRefBuilder scratchBytes = new BytesRefBuilder();
+ scratchBytes.clear();
Util.toBytesRef(output, scratchBytes);
// TODO: we could do this lazily, better to try to push into FSTEnum though?
- in.seekExact(scratchBytes);
+ in.seekExact(scratchBytes.get());
}
@Override
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene45/Lucene45DocValuesConsumer.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene45/Lucene45DocValuesConsumer.java
index 9b526da0794..54e0af83012 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene45/Lucene45DocValuesConsumer.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene45/Lucene45DocValuesConsumer.java
@@ -31,6 +31,7 @@ import org.apache.lucene.index.FieldInfo.DocValuesType;
import org.apache.lucene.store.IndexOutput;
import org.apache.lucene.store.RAMOutputStream;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.MathUtil;
import org.apache.lucene.util.StringHelper;
@@ -309,17 +310,17 @@ class Lucene45DocValuesConsumer extends DocValuesConsumer implements Closeable {
// we could avoid this, but its not much and less overall RAM than the previous approach!
RAMOutputStream addressBuffer = new RAMOutputStream();
MonotonicBlockPackedWriter termAddresses = new MonotonicBlockPackedWriter(addressBuffer, BLOCK_SIZE);
- BytesRef lastTerm = new BytesRef();
+ BytesRefBuilder lastTerm = new BytesRefBuilder();
long count = 0;
for (BytesRef v : values) {
if (count % ADDRESS_INTERVAL == 0) {
termAddresses.add(data.getFilePointer() - startFP);
// force the first term in a block to be abs-encoded
- lastTerm.length = 0;
+ lastTerm.clear();
}
// prefix-code
- int sharedPrefix = StringHelper.bytesDifference(lastTerm, v);
+ int sharedPrefix = StringHelper.bytesDifference(lastTerm.get(), v);
data.writeVInt(sharedPrefix);
data.writeVInt(v.length - sharedPrefix);
data.writeBytes(v.bytes, v.offset + sharedPrefix, v.length - sharedPrefix);
diff --git a/lucene/core/src/java/org/apache/lucene/codecs/lucene49/Lucene49DocValuesConsumer.java b/lucene/core/src/java/org/apache/lucene/codecs/lucene49/Lucene49DocValuesConsumer.java
index 40c0dc54e4e..d1963341d9c 100644
--- a/lucene/core/src/java/org/apache/lucene/codecs/lucene49/Lucene49DocValuesConsumer.java
+++ b/lucene/core/src/java/org/apache/lucene/codecs/lucene49/Lucene49DocValuesConsumer.java
@@ -31,6 +31,7 @@ import org.apache.lucene.index.SegmentWriteState;
import org.apache.lucene.store.IndexOutput;
import org.apache.lucene.store.RAMOutputStream;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.MathUtil;
import org.apache.lucene.util.StringHelper;
@@ -324,17 +325,18 @@ class Lucene49DocValuesConsumer extends DocValuesConsumer implements Closeable {
// we could avoid this, but its not much and less overall RAM than the previous approach!
RAMOutputStream addressBuffer = new RAMOutputStream();
MonotonicBlockPackedWriter termAddresses = new MonotonicBlockPackedWriter(addressBuffer, BLOCK_SIZE);
- BytesRef lastTerm = new BytesRef(Math.max(0, maxLength));
+ BytesRefBuilder lastTerm = new BytesRefBuilder();
+ lastTerm.grow(Math.max(0, maxLength));
long count = 0;
for (BytesRef v : values) {
if (count % ADDRESS_INTERVAL == 0) {
termAddresses.add(data.getFilePointer() - startFP);
// force the first term in a block to be abs-encoded
- lastTerm.length = 0;
+ lastTerm.clear();
}
// prefix-code
- int sharedPrefix = StringHelper.bytesDifference(lastTerm, v);
+ int sharedPrefix = StringHelper.bytesDifference(lastTerm.get(), v);
data.writeVInt(sharedPrefix);
data.writeVInt(v.length - sharedPrefix);
data.writeBytes(v.bytes, v.offset + sharedPrefix, v.length - sharedPrefix);
diff --git a/lucene/core/src/java/org/apache/lucene/document/CompressionTools.java b/lucene/core/src/java/org/apache/lucene/document/CompressionTools.java
index 09dc91faf12..b30a34c5b1b 100644
--- a/lucene/core/src/java/org/apache/lucene/document/CompressionTools.java
+++ b/lucene/core/src/java/org/apache/lucene/document/CompressionTools.java
@@ -23,7 +23,6 @@ import java.util.zip.DataFormatException;
import java.io.ByteArrayOutputStream;
import org.apache.lucene.util.BytesRef;
-import org.apache.lucene.util.CharsRef;
import org.apache.lucene.util.UnicodeUtil;
/** Simple utility class providing static methods to
@@ -87,9 +86,9 @@ public class CompressionTools {
* compressionLevel (constants are defined in
* java.util.zip.Deflater). */
public static byte[] compressString(String value, int compressionLevel) {
- BytesRef result = new BytesRef();
- UnicodeUtil.UTF16toUTF8(value, 0, value.length(), result);
- return compress(result.bytes, 0, result.length, compressionLevel);
+ byte[] b = new byte[UnicodeUtil.MAX_UTF8_BYTES_PER_CHAR * value.length()];
+ final int len = UnicodeUtil.UTF16toUTF8(value, 0, value.length(), b);
+ return compress(b, 0, len, compressionLevel);
}
/** Decompress the byte array previously returned by
@@ -138,9 +137,9 @@ public class CompressionTools {
* compressString back into a String */
public static String decompressString(byte[] value, int offset, int length) throws DataFormatException {
final byte[] bytes = decompress(value, offset, length);
- CharsRef result = new CharsRef(bytes.length);
- UnicodeUtil.UTF8toUTF16(bytes, 0, bytes.length, result);
- return new String(result.chars, 0, result.length);
+ final char[] result = new char[bytes.length];
+ final int len = UnicodeUtil.UTF8toUTF16(bytes, 0, bytes.length, result);
+ return new String(result, 0, len);
}
/** Decompress the byte array (referenced by the provided BytesRef)
diff --git a/lucene/core/src/java/org/apache/lucene/index/AutomatonTermsEnum.java b/lucene/core/src/java/org/apache/lucene/index/AutomatonTermsEnum.java
index dcae44fe055..94044a6c4ce 100644
--- a/lucene/core/src/java/org/apache/lucene/index/AutomatonTermsEnum.java
+++ b/lucene/core/src/java/org/apache/lucene/index/AutomatonTermsEnum.java
@@ -20,11 +20,12 @@ package org.apache.lucene.index;
import java.io.IOException;
import org.apache.lucene.util.BytesRef;
-import org.apache.lucene.util.IntsRef;
+import org.apache.lucene.util.BytesRefBuilder;
+import org.apache.lucene.util.IntsRefBuilder;
import org.apache.lucene.util.StringHelper;
+import org.apache.lucene.util.automaton.Automaton;
import org.apache.lucene.util.automaton.ByteRunAutomaton;
import org.apache.lucene.util.automaton.CompiledAutomaton;
-import org.apache.lucene.util.automaton.Automaton;
import org.apache.lucene.util.automaton.Transition;
/**
@@ -58,7 +59,7 @@ class AutomatonTermsEnum extends FilteredTermsEnum {
private final long[] visited;
private long curGen;
// the reference used for seeking forwards through the term dictionary
- private final BytesRef seekBytesRef = new BytesRef(10);
+ private final BytesRefBuilder seekBytesRef = new BytesRefBuilder();
// true if we are enumerating an infinite portion of the DFA.
// in this case it is faster to drive the query based on the terms dictionary.
// when this is true, linearUpperBound indicate the end of range
@@ -108,10 +109,10 @@ class AutomatonTermsEnum extends FilteredTermsEnum {
protected BytesRef nextSeekTerm(final BytesRef term) throws IOException {
//System.out.println("ATE.nextSeekTerm term=" + term);
if (term == null) {
- assert seekBytesRef.length == 0;
+ assert seekBytesRef.length() == 0;
// return the empty term, as its valid
if (runAutomaton.isAccept(runAutomaton.getInitialState())) {
- return seekBytesRef;
+ return seekBytesRef.get();
}
} else {
seekBytesRef.copyBytes(term);
@@ -119,7 +120,7 @@ class AutomatonTermsEnum extends FilteredTermsEnum {
// seek to the next possible string;
if (nextString()) {
- return seekBytesRef; // reposition
+ return seekBytesRef.get(); // reposition
} else {
return null; // no more possible strings can match
}
@@ -140,15 +141,15 @@ class AutomatonTermsEnum extends FilteredTermsEnum {
int maxInterval = 0xff;
//System.out.println("setLinear pos=" + position + " seekbytesRef=" + seekBytesRef);
for (int i = 0; i < position; i++) {
- state = runAutomaton.step(state, seekBytesRef.bytes[i] & 0xff);
+ state = runAutomaton.step(state, seekBytesRef.byteAt(i) & 0xff);
assert state >= 0: "state=" + state;
}
final int numTransitions = automaton.getNumTransitions(state);
automaton.initTransition(state, transition);
for (int i = 0; i < numTransitions; i++) {
automaton.getNextTransition(transition);
- if (transition.min <= (seekBytesRef.bytes[position] & 0xff) &&
- (seekBytesRef.bytes[position] & 0xff) <= transition.max) {
+ if (transition.min <= (seekBytesRef.byteAt(position) & 0xff) &&
+ (seekBytesRef.byteAt(position) & 0xff) <= transition.max) {
maxInterval = transition.max;
break;
}
@@ -159,14 +160,14 @@ class AutomatonTermsEnum extends FilteredTermsEnum {
int length = position + 1; /* position + maxTransition */
if (linearUpperBound.bytes.length < length)
linearUpperBound.bytes = new byte[length];
- System.arraycopy(seekBytesRef.bytes, 0, linearUpperBound.bytes, 0, position);
+ System.arraycopy(seekBytesRef.bytes(), 0, linearUpperBound.bytes, 0, position);
linearUpperBound.bytes[position] = (byte) maxInterval;
linearUpperBound.length = length;
linear = true;
}
- private final IntsRef savedStates = new IntsRef(10);
+ private final IntsRefBuilder savedStates = new IntsRefBuilder();
/**
* Increments the byte buffer to the next String in binary order after s that will not put
@@ -181,20 +182,19 @@ class AutomatonTermsEnum extends FilteredTermsEnum {
private boolean nextString() {
int state;
int pos = 0;
- savedStates.grow(seekBytesRef.length+1);
- final int[] states = savedStates.ints;
- states[0] = runAutomaton.getInitialState();
+ savedStates.grow(seekBytesRef.length()+1);
+ savedStates.setIntAt(0, runAutomaton.getInitialState());
while (true) {
curGen++;
linear = false;
// walk the automaton until a character is rejected.
- for (state = states[pos]; pos < seekBytesRef.length; pos++) {
+ for (state = savedStates.intAt(pos); pos < seekBytesRef.length(); pos++) {
visited[state] = curGen;
- int nextState = runAutomaton.step(state, seekBytesRef.bytes[pos] & 0xff);
+ int nextState = runAutomaton.step(state, seekBytesRef.byteAt(pos) & 0xff);
if (nextState == -1)
break;
- states[pos+1] = nextState;
+ savedStates.setIntAt(pos+1, nextState);
// we found a loop, record it for faster enumeration
if (!finite && !linear && visited[nextState] == curGen) {
setLinear(pos);
@@ -209,7 +209,7 @@ class AutomatonTermsEnum extends FilteredTermsEnum {
} else { /* no more solutions exist from this useful portion, backtrack */
if ((pos = backtrack(pos)) < 0) /* no more solutions at all */
return false;
- final int newState = runAutomaton.step(states[pos], seekBytesRef.bytes[pos] & 0xff);
+ final int newState = runAutomaton.step(savedStates.intAt(pos), seekBytesRef.byteAt(pos) & 0xff);
if (newState >= 0 && runAutomaton.isAccept(newState))
/* String is good to go as-is */
return true;
@@ -245,8 +245,8 @@ class AutomatonTermsEnum extends FilteredTermsEnum {
* character, if it exists.
*/
int c = 0;
- if (position < seekBytesRef.length) {
- c = seekBytesRef.bytes[position] & 0xff;
+ if (position < seekBytesRef.length()) {
+ c = seekBytesRef.byteAt(position) & 0xff;
// if the next byte is 0xff and is not part of the useful portion,
// then by definition it puts us in a reject state, and therefore this
// path is dead. there cannot be any higher transitions. backtrack.
@@ -254,7 +254,7 @@ class AutomatonTermsEnum extends FilteredTermsEnum {
return false;
}
- seekBytesRef.length = position;
+ seekBytesRef.setLength(position);
visited[state] = curGen;
final int numTransitions = automaton.getNumTransitions(state);
@@ -266,9 +266,8 @@ class AutomatonTermsEnum extends FilteredTermsEnum {
if (transition.max >= c) {
int nextChar = Math.max(c, transition.min);
// append either the next sequential char, or the minimum transition
- seekBytesRef.grow(seekBytesRef.length + 1);
- seekBytesRef.length++;
- seekBytesRef.bytes[seekBytesRef.length - 1] = (byte) nextChar;
+ seekBytesRef.grow(seekBytesRef.length() + 1);
+ seekBytesRef.append((byte) nextChar);
state = transition.dest;
/*
* as long as is possible, continue down the minimal path in
@@ -286,13 +285,12 @@ class AutomatonTermsEnum extends FilteredTermsEnum {
state = transition.dest;
// append the minimum transition
- seekBytesRef.grow(seekBytesRef.length + 1);
- seekBytesRef.length++;
- seekBytesRef.bytes[seekBytesRef.length - 1] = (byte) transition.min;
+ seekBytesRef.grow(seekBytesRef.length() + 1);
+ seekBytesRef.append((byte) transition.min);
// we found a loop, record it for faster enumeration
if (!finite && !linear && visited[state] == curGen) {
- setLinear(seekBytesRef.length-1);
+ setLinear(seekBytesRef.length()-1);
}
}
return true;
@@ -311,12 +309,12 @@ class AutomatonTermsEnum extends FilteredTermsEnum {
*/
private int backtrack(int position) {
while (position-- > 0) {
- int nextChar = seekBytesRef.bytes[position] & 0xff;
+ int nextChar = seekBytesRef.byteAt(position) & 0xff;
// if a character is 0xff its a dead-end too,
// because there is no higher character in binary sort order.
if (nextChar++ != 0xff) {
- seekBytesRef.bytes[position] = (byte) nextChar;
- seekBytesRef.length = position+1;
+ seekBytesRef.setByteAt(position, (byte) nextChar);
+ seekBytesRef.setLength(position+1);
return position;
}
}
diff --git a/lucene/core/src/java/org/apache/lucene/index/BinaryDocValuesFieldUpdates.java b/lucene/core/src/java/org/apache/lucene/index/BinaryDocValuesFieldUpdates.java
index 53bf5a18c86..a7735cf1989 100644
--- a/lucene/core/src/java/org/apache/lucene/index/BinaryDocValuesFieldUpdates.java
+++ b/lucene/core/src/java/org/apache/lucene/index/BinaryDocValuesFieldUpdates.java
@@ -4,6 +4,7 @@ import org.apache.lucene.document.BinaryDocValuesField;
import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.InPlaceMergeSorter;
import org.apache.lucene.util.packed.PackedInts;
import org.apache.lucene.util.packed.PagedGrowableWriter;
@@ -96,7 +97,7 @@ class BinaryDocValuesFieldUpdates extends DocValuesFieldUpdates {
private PagedMutable docs;
private PagedGrowableWriter offsets, lengths;
- private BytesRef values;
+ private BytesRefBuilder values;
private int size;
private final int bitsPerValue;
@@ -106,7 +107,7 @@ class BinaryDocValuesFieldUpdates extends DocValuesFieldUpdates {
docs = new PagedMutable(1, PAGE_SIZE, bitsPerValue, PackedInts.COMPACT);
offsets = new PagedGrowableWriter(1, PAGE_SIZE, 1, PackedInts.FAST);
lengths = new PagedGrowableWriter(1, PAGE_SIZE, 1, PackedInts.FAST);
- values = new BytesRef(16); // start small
+ values = new BytesRefBuilder();
size = 0;
}
@@ -127,7 +128,7 @@ class BinaryDocValuesFieldUpdates extends DocValuesFieldUpdates {
}
docs.set(size, doc);
- offsets.set(size, values.length);
+ offsets.set(size, values.length());
lengths.set(size, val.length);
values.append(val);
++size;
@@ -138,7 +139,7 @@ class BinaryDocValuesFieldUpdates extends DocValuesFieldUpdates {
final PagedMutable docs = this.docs;
final PagedGrowableWriter offsets = this.offsets;
final PagedGrowableWriter lengths = this.lengths;
- final BytesRef values = this.values;
+ final BytesRef values = this.values.get();
new InPlaceMergeSorter() {
@Override
protected void swap(int i, int j) {
@@ -181,16 +182,12 @@ class BinaryDocValuesFieldUpdates extends DocValuesFieldUpdates {
for (int i = 0; i < otherUpdates.size; i++) {
int doc = (int) otherUpdates.docs.get(i);
docs.set(size, doc);
- offsets.set(size, values.length + otherUpdates.offsets.get(i)); // correct relative offset
+ offsets.set(size, values.length() + otherUpdates.offsets.get(i)); // correct relative offset
lengths.set(size, otherUpdates.lengths.get(i));
++size;
}
- int newLen = values.length + otherUpdates.values.length;
- if (values.bytes.length < newLen) {
- values.bytes = ArrayUtil.grow(values.bytes, newLen);
- }
- System.arraycopy(otherUpdates.values.bytes, otherUpdates.values.offset, values.bytes, values.length, otherUpdates.values.length);
- values.length = newLen;
+
+ values.append(otherUpdates.values);
}
@Override
@@ -204,7 +201,7 @@ class BinaryDocValuesFieldUpdates extends DocValuesFieldUpdates {
final int capacity = estimateCapacity(size);
bytesPerDoc += (long) Math.ceil((double) offsets.ramBytesUsed() / capacity); // offsets
bytesPerDoc += (long) Math.ceil((double) lengths.ramBytesUsed() / capacity); // lengths
- bytesPerDoc += (long) Math.ceil((double) values.length / size); // values
+ bytesPerDoc += (long) Math.ceil((double) values.length() / size); // values
return bytesPerDoc;
}
diff --git a/lucene/core/src/java/org/apache/lucene/index/BinaryDocValuesWriter.java b/lucene/core/src/java/org/apache/lucene/index/BinaryDocValuesWriter.java
index f6a4984d2de..30290257561 100644
--- a/lucene/core/src/java/org/apache/lucene/index/BinaryDocValuesWriter.java
+++ b/lucene/core/src/java/org/apache/lucene/index/BinaryDocValuesWriter.java
@@ -26,6 +26,7 @@ import org.apache.lucene.store.DataInput;
import org.apache.lucene.store.DataOutput;
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.Counter;
import org.apache.lucene.util.FixedBitSet;
import org.apache.lucene.util.PagedBytes;
@@ -124,7 +125,7 @@ class BinaryDocValuesWriter extends DocValuesWriter {
// iterates over the values we have in ram
private class BytesIterator implements Iterator<BytesRef> {
- final BytesRef value = new BytesRef();
+ final BytesRefBuilder value = new BytesRefBuilder();
final PackedLongValues.Iterator lengthsIterator;
final DataInput bytesIterator = bytes.getDataInput();
final int size = (int) lengths.size();
@@ -150,15 +151,15 @@ class BinaryDocValuesWriter extends DocValuesWriter {
if (upto < size) {
int length = (int) lengthsIterator.next();
value.grow(length);
- value.length = length;
+ value.setLength(length);
try {
- bytesIterator.readBytes(value.bytes, value.offset, value.length);
+ bytesIterator.readBytes(value.bytes(), 0, value.length());
} catch (IOException ioe) {
// Should never happen!
throw new RuntimeException(ioe);
}
if (docsWithField.get(upto)) {
- v = value;
+ v = value.get();
} else {
v = null;
}
diff --git a/lucene/core/src/java/org/apache/lucene/index/CheckIndex.java b/lucene/core/src/java/org/apache/lucene/index/CheckIndex.java
index f524d21f24b..0eb8da8e25e 100644
--- a/lucene/core/src/java/org/apache/lucene/index/CheckIndex.java
+++ b/lucene/core/src/java/org/apache/lucene/index/CheckIndex.java
@@ -41,6 +41,7 @@ import org.apache.lucene.store.IOContext;
import org.apache.lucene.store.IndexInput;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.CommandLineUtil;
import org.apache.lucene.util.FixedBitSet;
import org.apache.lucene.util.IOUtils;
@@ -852,7 +853,7 @@ public class CheckIndex {
boolean hasOrd = true;
final long termCountStart = status.delTermCount + status.termCount;
- BytesRef lastTerm = null;
+ BytesRefBuilder lastTerm = null;
long sumTotalTermFreq = 0;
long sumDocFreq = 0;
@@ -870,9 +871,10 @@ public class CheckIndex {
// make sure terms arrive in order according to
// the comp
if (lastTerm == null) {
- lastTerm = BytesRef.deepCopyOf(term);
+ lastTerm = new BytesRefBuilder();
+ lastTerm.copyBytes(term);
} else {
- if (lastTerm.compareTo(term) >= 0) {
+ if (lastTerm.get().compareTo(term) >= 0) {
throw new RuntimeException("terms out of order: lastTerm=" + lastTerm + " term=" + term);
}
lastTerm.copyBytes(term);
@@ -1184,7 +1186,7 @@ public class CheckIndex {
// Test seek to last term:
if (lastTerm != null) {
- if (termsEnum.seekCeil(lastTerm) != TermsEnum.SeekStatus.FOUND) {
+ if (termsEnum.seekCeil(lastTerm.get()) != TermsEnum.SeekStatus.FOUND) {
throw new RuntimeException("seek to last term " + lastTerm + " failed");
}
diff --git a/lucene/core/src/java/org/apache/lucene/index/FreqProxFields.java b/lucene/core/src/java/org/apache/lucene/index/FreqProxFields.java
index 795afd339dc..5d017540fbd 100644
--- a/lucene/core/src/java/org/apache/lucene/index/FreqProxFields.java
+++ b/lucene/core/src/java/org/apache/lucene/index/FreqProxFields.java
@@ -28,6 +28,7 @@ import org.apache.lucene.index.FreqProxTermsWriterPerField.FreqProxPostingsArray
import org.apache.lucene.util.AttributeSource; // javadocs
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
/** Implements limited (iterators only, no stats) {@link
* Fields} interface over the in-RAM buffered
@@ -405,7 +406,7 @@ class FreqProxFields extends Fields {
int termID;
boolean ended;
boolean hasPayload;
- BytesRef payload = new BytesRef();
+ BytesRefBuilder payload = new BytesRefBuilder();
public FreqProxDocsAndPositionsEnum(FreqProxTermsWriterPerField terms, FreqProxPostingsArray postingsArray) {
this.terms = terms;
@@ -485,11 +486,9 @@ class FreqProxFields extends Fields {
if ((code & 1) != 0) {
hasPayload = true;
// has a payload
- payload.length = posReader.readVInt();
- if (payload.bytes.length < payload.length) {
- payload.grow(payload.length);
- }
- posReader.readBytes(payload.bytes, 0, payload.length);
+ payload.setLength(posReader.readVInt());
+ payload.grow(payload.length());
+ posReader.readBytes(payload.bytes(), 0, payload.length());
} else {
hasPayload = false;
}
@@ -521,7 +520,7 @@ class FreqProxFields extends Fields {
@Override
public BytesRef getPayload() {
if (hasPayload) {
- return payload;
+ return payload.get();
} else {
return null;
}
diff --git a/lucene/core/src/java/org/apache/lucene/index/MultiTermsEnum.java b/lucene/core/src/java/org/apache/lucene/index/MultiTermsEnum.java
index 9e2abdd5706..6ae2c7c1d8e 100644
--- a/lucene/core/src/java/org/apache/lucene/index/MultiTermsEnum.java
+++ b/lucene/core/src/java/org/apache/lucene/index/MultiTermsEnum.java
@@ -17,6 +17,7 @@ package org.apache.lucene.index;
* limitations under the License.
*/
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.PriorityQueue;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.Bits;
@@ -41,7 +42,7 @@ public final class MultiTermsEnum extends TermsEnum {
private BytesRef lastSeek;
private boolean lastSeekExact;
- private final BytesRef lastSeekScratch = new BytesRef();
+ private final BytesRefBuilder lastSeekScratch = new BytesRefBuilder();
private int numTop;
private int numSubs;
@@ -186,7 +187,7 @@ public final class MultiTermsEnum extends TermsEnum {
}
lastSeekScratch.copyBytes(term);
- lastSeek = lastSeekScratch;
+ lastSeek = lastSeekScratch.get();
for(int i=0;i<numSubs;i++) {
final SeekStatus status;
diff --git a/lucene/core/src/java/org/apache/lucene/index/PrefixCodedTerms.java b/lucene/core/src/java/org/apache/lucene/index/PrefixCodedTerms.java
index 694d596f9e0..1740333baef 100644
--- a/lucene/core/src/java/org/apache/lucene/index/PrefixCodedTerms.java
+++ b/lucene/core/src/java/org/apache/lucene/index/PrefixCodedTerms.java
@@ -26,6 +26,7 @@ import org.apache.lucene.store.RAMInputStream;
import org.apache.lucene.store.RAMOutputStream;
import org.apache.lucene.util.Accountable;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
/**
* Prefix codes term instances (prefixes are shared)
@@ -52,8 +53,8 @@ class PrefixCodedTerms implements Iterable<Term>, Accountable {
class PrefixCodedTermsIterator implements Iterator<Term> {
final IndexInput input;
String field = "";
- BytesRef bytes = new BytesRef();
- Term term = new Term(field, bytes);
+ BytesRefBuilder bytes = new BytesRefBuilder();
+ Term term = new Term(field, bytes.get());
PrefixCodedTermsIterator() {
try {
@@ -80,9 +81,9 @@ class PrefixCodedTerms implements Iterable<Term>, Accountable {
int prefix = code >>> 1;
int suffix = input.readVInt();
bytes.grow(prefix + suffix);
- input.readBytes(bytes.bytes, prefix, suffix);
- bytes.length = prefix + suffix;
- term.set(field, bytes);
+ input.readBytes(bytes.bytes(), prefix, suffix);
+ bytes.setLength(prefix + suffix);
+ term.set(field, bytes.get());
return term;
} catch (IOException e) {
throw new RuntimeException(e);
@@ -100,6 +101,7 @@ class PrefixCodedTerms implements Iterable<Term>, Accountable {
private RAMFile buffer = new RAMFile();
private RAMOutputStream output = new RAMOutputStream(buffer, false);
private Term lastTerm = new Term("");
+ private BytesRefBuilder lastTermBytes = new BytesRefBuilder();
/** add a term */
public void add(Term term) {
@@ -116,7 +118,8 @@ class PrefixCodedTerms implements Iterable<Term>, Accountable {
}
output.writeVInt(suffix);
output.writeBytes(term.bytes.bytes, term.bytes.offset + prefix, suffix);
- lastTerm.bytes.copyBytes(term.bytes);
+ lastTermBytes.copyBytes(term.bytes);
+ lastTerm.bytes = lastTermBytes.get();
lastTerm.field = term.field;
} catch (IOException e) {
throw new RuntimeException(e);
diff --git a/lucene/core/src/java/org/apache/lucene/index/SortedDocValuesTermsEnum.java b/lucene/core/src/java/org/apache/lucene/index/SortedDocValuesTermsEnum.java
index 3c91dd6943f..16427cc9fee 100644
--- a/lucene/core/src/java/org/apache/lucene/index/SortedDocValuesTermsEnum.java
+++ b/lucene/core/src/java/org/apache/lucene/index/SortedDocValuesTermsEnum.java
@@ -21,6 +21,7 @@ import java.io.IOException;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
/** Implements a {@link TermsEnum} wrapping a provided
* {@link SortedDocValues}. */
@@ -29,12 +30,12 @@ class SortedDocValuesTermsEnum extends TermsEnum {
private final SortedDocValues values;
private int currentOrd = -1;
private BytesRef term;
- private final BytesRef scratch;
+ private final BytesRefBuilder scratch;
/** Creates a new TermsEnum over the provided values */
public SortedDocValuesTermsEnum(SortedDocValues values) {
this.values = values;
- scratch = new BytesRef();
+ scratch = new BytesRefBuilder();
}
@Override
@@ -43,7 +44,7 @@ class SortedDocValuesTermsEnum extends TermsEnum {
if (ord >= 0) {
currentOrd = ord;
scratch.copyBytes(text);
- term = scratch;
+ term = scratch.get();
return SeekStatus.FOUND;
} else {
currentOrd = -ord-1;
@@ -63,7 +64,7 @@ class SortedDocValuesTermsEnum extends TermsEnum {
if (ord >= 0) {
currentOrd = ord;
scratch.copyBytes(text);
- term = scratch;
+ term = scratch.get();
return true;
} else {
return false;
diff --git a/lucene/core/src/java/org/apache/lucene/index/SortedSetDocValuesTermsEnum.java b/lucene/core/src/java/org/apache/lucene/index/SortedSetDocValuesTermsEnum.java
index 68d935da70d..64dba957bc2 100644
--- a/lucene/core/src/java/org/apache/lucene/index/SortedSetDocValuesTermsEnum.java
+++ b/lucene/core/src/java/org/apache/lucene/index/SortedSetDocValuesTermsEnum.java
@@ -21,6 +21,7 @@ import java.io.IOException;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
/** Implements a {@link TermsEnum} wrapping a provided
* {@link SortedSetDocValues}. */
@@ -29,12 +30,12 @@ class SortedSetDocValuesTermsEnum extends TermsEnum {
private final SortedSetDocValues values;
private long currentOrd = -1;
private BytesRef term;
- private final BytesRef scratch;
+ private final BytesRefBuilder scratch;
/** Creates a new TermsEnum over the provided values */
public SortedSetDocValuesTermsEnum(SortedSetDocValues values) {
this.values = values;
- scratch = new BytesRef();
+ scratch = new BytesRefBuilder();
}
@Override
@@ -43,7 +44,7 @@ class SortedSetDocValuesTermsEnum extends TermsEnum {
if (ord >= 0) {
currentOrd = ord;
scratch.copyBytes(text);
- term = scratch;
+ term = scratch.get();
return SeekStatus.FOUND;
} else {
currentOrd = -ord-1;
@@ -63,7 +64,7 @@ class SortedSetDocValuesTermsEnum extends TermsEnum {
if (ord >= 0) {
currentOrd = ord;
scratch.copyBytes(text);
- term = scratch;
+ term = scratch.get();
return true;
} else {
return false;
diff --git a/lucene/core/src/java/org/apache/lucene/index/Terms.java b/lucene/core/src/java/org/apache/lucene/index/Terms.java
index f2b88cc904c..419a6f70568 100644
--- a/lucene/core/src/java/org/apache/lucene/index/Terms.java
+++ b/lucene/core/src/java/org/apache/lucene/index/Terms.java
@@ -20,6 +20,7 @@ package org.apache.lucene.index;
import java.io.IOException;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.automaton.CompiledAutomaton;
/**
@@ -156,9 +157,8 @@ public abstract class Terms {
return v;
}
- BytesRef scratch = new BytesRef(1);
-
- scratch.length = 1;
+ BytesRefBuilder scratch = new BytesRefBuilder();
+ scratch.append((byte) 0);
// Iterates over digits:
while (true) {
@@ -170,12 +170,12 @@ public abstract class Terms {
// digit before END:
while (low != high) {
int mid = (low+high) >>> 1;
- scratch.bytes[scratch.length-1] = (byte) mid;
- if (iterator.seekCeil(scratch) == TermsEnum.SeekStatus.END) {
+ scratch.setByteAt(scratch.length()-1, (byte) mid);
+ if (iterator.seekCeil(scratch.get()) == TermsEnum.SeekStatus.END) {
// Scratch was too high
if (mid == 0) {
- scratch.length--;
- return scratch;
+ scratch.setLength(scratch.length() - 1);
+ return scratch.get();
}
high = mid;
} else {
@@ -189,8 +189,8 @@ public abstract class Terms {
}
// Recurse to next digit:
- scratch.length++;
- scratch.grow(scratch.length);
+ scratch.setLength(scratch.length() + 1);
+ scratch.grow(scratch.length());
}
}
}
diff --git a/lucene/core/src/java/org/apache/lucene/search/FieldComparator.java b/lucene/core/src/java/org/apache/lucene/search/FieldComparator.java
index 4c655a56abc..67f0fd49fcc 100644
--- a/lucene/core/src/java/org/apache/lucene/search/FieldComparator.java
+++ b/lucene/core/src/java/org/apache/lucene/search/FieldComparator.java
@@ -27,6 +27,7 @@ import org.apache.lucene.index.NumericDocValues;
import org.apache.lucene.index.SortedDocValues;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
/**
* Expert: a FieldComparator compares hits so as to determine their
@@ -687,7 +688,7 @@ public abstract class FieldComparator<T> {
/* Values for each slot.
@lucene.internal */
final BytesRef[] values;
- private final BytesRef[] tempBRs;
+ private final BytesRefBuilder[] tempBRs;
/* Which reader last copied a value into the slot. When
we compare two slots, we just compare-by-ord if the
@@ -748,7 +749,7 @@ public abstract class FieldComparator<T> {
public TermOrdValComparator(int numHits, String field, boolean sortMissingLast) {
ords = new int[numHits];
values = new BytesRef[numHits];
- tempBRs = new BytesRef[numHits];
+ tempBRs = new BytesRefBuilder[numHits];
readerGen = new int[numHits];
this.field = field;
if (sortMissingLast) {
@@ -808,10 +809,10 @@ public abstract class FieldComparator<T> {
} else {
assert ord >= 0;
if (tempBRs[slot] == null) {
- tempBRs[slot] = new BytesRef();
+ tempBRs[slot] = new BytesRefBuilder();
}
- values[slot] = tempBRs[slot];
- values[slot].copyBytes(termsIndex.lookupOrd(ord));
+ tempBRs[slot].copyBytes(termsIndex.lookupOrd(ord));
+ values[slot] = tempBRs[slot].get();
}
ords[slot] = ord;
readerGen[slot] = currentReaderGen;
@@ -938,7 +939,7 @@ public abstract class FieldComparator<T> {
public static class TermValComparator extends FieldComparator<BytesRef> {
private final BytesRef[] values;
- private final BytesRef[] tempBRs;
+ private final BytesRefBuilder[] tempBRs;
private BinaryDocValues docTerms;
private Bits docsWithField;
private final String field;
@@ -949,7 +950,7 @@ public abstract class FieldComparator<T> {
/** Sole constructor. */
public TermValComparator(int numHits, String field, boolean sortMissingLast) {
values = new BytesRef[numHits];
- tempBRs = new BytesRef[numHits];
+ tempBRs = new BytesRefBuilder[numHits];
this.field = field;
missingSortCmp = sortMissingLast ? 1 : -1;
}
@@ -974,10 +975,10 @@ public abstract class FieldComparator<T> {
values[slot] = null;
} else {
if (tempBRs[slot] == null) {
- tempBRs[slot] = new BytesRef();
+ tempBRs[slot] = new BytesRefBuilder();
}
- values[slot] = tempBRs[slot];
- values[slot].copyBytes(comparableBytes);
+ tempBRs[slot].copyBytes(comparableBytes);
+ values[slot] = tempBRs[slot].get();
}
}
diff --git a/lucene/core/src/java/org/apache/lucene/search/FuzzyTermsEnum.java b/lucene/core/src/java/org/apache/lucene/search/FuzzyTermsEnum.java
index 7aeb52058d8..319996645b8 100644
--- a/lucene/core/src/java/org/apache/lucene/search/FuzzyTermsEnum.java
+++ b/lucene/core/src/java/org/apache/lucene/search/FuzzyTermsEnum.java
@@ -34,6 +34,7 @@ import org.apache.lucene.util.AttributeImpl;
import org.apache.lucene.util.AttributeSource;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.UnicodeUtil;
import org.apache.lucene.util.automaton.Automaton;
import org.apache.lucene.util.automaton.ByteRunAutomaton;
@@ -152,7 +153,7 @@ public class FuzzyTermsEnum extends TermsEnum {
if (editDistance < runAutomata.size()) {
//System.out.println("FuzzyTE.getAEnum: ed=" + editDistance + " lastTerm=" + (lastTerm==null ? "null" : lastTerm.utf8ToString()));
final CompiledAutomaton compiled = runAutomata.get(editDistance);
- return new AutomatonFuzzyTermsEnum(terms.intersect(compiled, lastTerm == null ? null : compiled.floor(lastTerm, new BytesRef())),
+ return new AutomatonFuzzyTermsEnum(terms.intersect(compiled, lastTerm == null ? null : compiled.floor(lastTerm, new BytesRefBuilder())),
runAutomata.subList(0, editDistance + 1).toArray(new CompiledAutomaton[editDistance + 1]));
} else {
return null;
diff --git a/lucene/core/src/java/org/apache/lucene/search/TopTermsRewrite.java b/lucene/core/src/java/org/apache/lucene/search/TopTermsRewrite.java
index 9cefcc033d5..95e2b73f599 100644
--- a/lucene/core/src/java/org/apache/lucene/search/TopTermsRewrite.java
+++ b/lucene/core/src/java/org/apache/lucene/search/TopTermsRewrite.java
@@ -30,6 +30,7 @@ import org.apache.lucene.index.TermState;
import org.apache.lucene.index.TermsEnum;
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
/**
* Base rewrite method for collecting only the top terms
@@ -86,14 +87,15 @@ public abstract class TopTermsRewrite<Q extends Query> extends TermCollectingRew
}
// for assert:
- private BytesRef lastTerm;
+ private BytesRefBuilder lastTerm;
private boolean compareToLastTerm(BytesRef t) {
if (lastTerm == null && t != null) {
- lastTerm = BytesRef.deepCopyOf(t);
+ lastTerm = new BytesRefBuilder();
+ lastTerm.append(t);
} else if (t == null) {
lastTerm = null;
} else {
- assert lastTerm.compareTo(t) < 0: "lastTerm=" + lastTerm + " t=" + t;
+ assert lastTerm.get().compareTo(t) < 0: "lastTerm=" + lastTerm + " t=" + t;
lastTerm.copyBytes(t);
}
return true;
@@ -113,7 +115,7 @@ public abstract class TopTermsRewrite<Q extends Query> extends TermCollectingRew
final ScoreTerm t = stQueue.peek();
if (boost < t.boost)
return true;
- if (boost == t.boost && bytes.compareTo(t.bytes) > 0)
+ if (boost == t.boost && bytes.compareTo(t.bytes.get()) > 0)
return true;
}
ScoreTerm t = visitedTerms.get(bytes);
@@ -127,14 +129,14 @@ public abstract class TopTermsRewrite<Q extends Query> extends TermCollectingRew
// add new entry in PQ, we must clone the term, else it may get overwritten!
st.bytes.copyBytes(bytes);
st.boost = boost;
- visitedTerms.put(st.bytes, st);
+ visitedTerms.put(st.bytes.get(), st);
assert st.termState.docFreq() == 0;
st.termState.register(state, readerContext.ord, termsEnum.docFreq(), termsEnum.totalTermFreq());
stQueue.offer(st);
// possibly drop entries from queue
if (stQueue.size() > maxSize) {
st = stQueue.poll();
- visitedTerms.remove(st.bytes);
+ visitedTerms.remove(st.bytes.get());
st.termState.clear(); // reset the termstate!
} else {
st = new ScoreTerm(new TermContext(topReaderContext));
@@ -144,7 +146,7 @@ public abstract class TopTermsRewrite<Q extends Query> extends TermCollectingRew
if (stQueue.size() == maxSize) {
t = stQueue.peek();
maxBoostAtt.setMaxNonCompetitiveBoost(t.boost);
- maxBoostAtt.setCompetitiveTerm(t.bytes);
+ maxBoostAtt.setCompetitiveTerm(t.bytes.get());
}
}
@@ -157,7 +159,7 @@ public abstract class TopTermsRewrite<Q extends Query> extends TermCollectingRew
ArrayUtil.timSort(scoreTerms, scoreTermSortByTermComp);
for (final ScoreTerm st : scoreTerms) {
- final Term term = new Term(query.field, st.bytes);
+ final Term term = new Term(query.field, st.bytes.toBytesRef());
assert reader.docFreq(term) == st.termState.docFreq() : "reader DF is " + reader.docFreq(term) + " vs " + st.termState.docFreq() + " term=" + term;
addClause(q, term, st.termState.docFreq(), query.getBoost() * st.boost, st.termState); // add to query
}
@@ -183,12 +185,12 @@ public abstract class TopTermsRewrite<Q extends Query> extends TermCollectingRew
new Comparator<ScoreTerm>() {
@Override
public int compare(ScoreTerm st1, ScoreTerm st2) {
- return st1.bytes.compareTo(st2.bytes);
+ return st1.bytes.get().compareTo(st2.bytes.get());
}
};
static final class ScoreTerm implements Comparable<ScoreTerm> {
- public final BytesRef bytes = new BytesRef();
+ public final BytesRefBuilder bytes = new BytesRefBuilder();
public float boost;
public final TermContext termState;
public ScoreTerm(TermContext termState) {
@@ -198,7 +200,7 @@ public abstract class TopTermsRewrite<Q extends Query> extends TermCollectingRew
@Override
public int compareTo(ScoreTerm other) {
if (this.boost == other.boost)
- return other.bytes.compareTo(this.bytes);
+ return other.bytes.get().compareTo(this.bytes.get());
else
return Float.compare(this.boost, other.boost);
}
diff --git a/lucene/core/src/java/org/apache/lucene/store/DataOutput.java b/lucene/core/src/java/org/apache/lucene/store/DataOutput.java
index 3dc93750f3f..724e5869e26 100644
--- a/lucene/core/src/java/org/apache/lucene/store/DataOutput.java
+++ b/lucene/core/src/java/org/apache/lucene/store/DataOutput.java
@@ -257,10 +257,9 @@ public abstract class DataOutput {
* @see DataInput#readString()
*/
public void writeString(String s) throws IOException {
- final BytesRef utf8Result = new BytesRef(10);
- UnicodeUtil.UTF16toUTF8(s, 0, s.length(), utf8Result);
+ final BytesRef utf8Result = new BytesRef(s);
writeVInt(utf8Result.length);
- writeBytes(utf8Result.bytes, 0, utf8Result.length);
+ writeBytes(utf8Result.bytes, utf8Result.offset, utf8Result.length);
}
private static int COPY_BUFFER_SIZE = 16384;
diff --git a/lucene/core/src/java/org/apache/lucene/util/BytesRef.java b/lucene/core/src/java/org/apache/lucene/util/BytesRef.java
index 0556a47d07b..a114f5ebe05 100644
--- a/lucene/core/src/java/org/apache/lucene/util/BytesRef.java
+++ b/lucene/core/src/java/org/apache/lucene/util/BytesRef.java
@@ -17,6 +17,7 @@ package org.apache.lucene.util;
* limitations under the License.
*/
+import java.util.Arrays;
import java.util.Comparator;
/** Represents byte[], as a slice (offset + length) into an
@@ -80,19 +81,8 @@ public final class BytesRef implements Comparable<BytesRef>,Cloneable {
* unicode text, with no unpaired surrogates.
*/
public BytesRef(CharSequence text) {
- this();
- copyChars(text);
- }
-
- /**
- * Copies the UTF8 bytes for this string.
- *
- * @param text Must be well-formed unicode text, with no
- * unpaired surrogates or invalid UTF16 code units.
- */
- public void copyChars(CharSequence text) {
- assert offset == 0; // TODO broken if offset != 0
- UnicodeUtil.UTF16toUTF8(text, 0, text.length(), this);
+ this(new byte[UnicodeUtil.MAX_UTF8_BYTES_PER_CHAR * text.length()]);
+ length = UnicodeUtil.UTF16toUTF8(text, 0, text.length(), bytes);
}
/**
@@ -155,9 +145,9 @@ public final class BytesRef implements Comparable<BytesRef>,Cloneable {
/** Interprets stored bytes as UTF8 bytes, returning the
* resulting string */
public String utf8ToString() {
- final CharsRef ref = new CharsRef(length);
- UnicodeUtil.UTF8toUTF16(bytes, offset, length, ref);
- return ref.toString();
+ final char[] ref = new char[length];
+ final int len = UnicodeUtil.UTF8toUTF16(bytes, offset, length, ref);
+ return new String(ref, 0, len);
}
/** Returns hex encoded bytes, eg [0x6c 0x75 0x63 0x65 0x6e 0x65] */
@@ -176,49 +166,6 @@ public final class BytesRef implements Comparable<BytesRef>,Cloneable {
return sb.toString();
}
- /**
- * Copies the bytes from the given {@link BytesRef}
- * <p>
- * NOTE: if this would exceed the array size, this method creates a
- * new reference array.
- */
- public void copyBytes(BytesRef other) {
- if (bytes.length - offset < other.length) {
- bytes = new byte[other.length];
- offset = 0;
- }
- System.arraycopy(other.bytes, other.offset, bytes, offset, other.length);
- length = other.length;
- }
-
- /**
- * Appends the bytes from the given {@link BytesRef}
- * <p>
- * NOTE: if this would exceed the array size, this method creates a
- * new reference array.
- */
- public void append(BytesRef other) {
- int newLen = length + other.length;
- if (bytes.length - offset < newLen) {
- byte[] newBytes = new byte[newLen];
- System.arraycopy(bytes, offset, newBytes, 0, length);
- offset = 0;
- bytes = newBytes;
- }
- System.arraycopy(other.bytes, other.offset, bytes, length+offset, other.length);
- length = newLen;
- }
-
- /**
- * Used to grow the reference array.
- *
- * In general this should not be used as it does not take the offset into account.
- * @lucene.internal */
- public void grow(int newLength) {
- assert offset == 0; // NOTE: senseless if offset != 0
- bytes = ArrayUtil.grow(bytes, newLength);
- }
-
/** Unsigned byte order comparison */
@Override
public int compareTo(BytesRef other) {
@@ -331,7 +278,9 @@ public final class BytesRef implements Comparable<BytesRef>,Cloneable {
*/
public static BytesRef deepCopyOf(BytesRef other) {
BytesRef copy = new BytesRef();
- copy.copyBytes(other);
+ copy.bytes = Arrays.copyOfRange(other.bytes, other.offset, other.offset + other.length);
+ copy.offset = 0;
+ copy.length = other.length;
return copy;
}
diff --git a/lucene/core/src/java/org/apache/lucene/util/BytesRefArray.java b/lucene/core/src/java/org/apache/lucene/util/BytesRefArray.java
index eb0aa1a808e..13d2ddea98f 100644
--- a/lucene/core/src/java/org/apache/lucene/util/BytesRefArray.java
+++ b/lucene/core/src/java/org/apache/lucene/util/BytesRefArray.java
@@ -99,16 +99,15 @@ public final class BytesRefArray {
* @param index the elements index to retrieve
* @return the <i>n'th</i> element of this {@link BytesRefArray}
*/
- public BytesRef get(BytesRef spare, int index) {
+ public BytesRef get(BytesRefBuilder spare, int index) {
if (lastElement > index) {
int offset = offsets[index];
int length = index == lastElement - 1 ? currentOffset - offset
: offsets[index + 1] - offset;
- assert spare.offset == 0;
spare.grow(length);
- spare.length = length;
- pool.readBytes(offset, spare.bytes, spare.offset, spare.length);
- return spare;
+ spare.setLength(length);
+ pool.readBytes(offset, spare.bytes(), 0, spare.length());
+ return spare.get();
}
throw new IndexOutOfBoundsException("index " + index
+ " must be less than the size: " + lastElement);
@@ -137,7 +136,7 @@ public final class BytesRefArray {
@Override
protected void setPivot(int i) {
final int index = orderedEntries[i];
- get(pivot, index);
+ pivot = get(pivotBuilder, index);
}
@Override
@@ -145,9 +144,11 @@ public final class BytesRefArray {
final int index = orderedEntries[j];
return comp.compare(pivot, get(scratch2, index));
}
-
- private final BytesRef pivot = new BytesRef(), scratch1 = new BytesRef(),
- scratch2 = new BytesRef();
+
+ private BytesRef pivot;
+ private final BytesRefBuilder pivotBuilder = new BytesRefBuilder(),
+ scratch1 = new BytesRefBuilder(),
+ scratch2 = new BytesRefBuilder();
}.sort(0, size());
return orderedEntries;
}
@@ -174,7 +175,7 @@ public final class BytesRefArray {
* </p>
*/
public BytesRefIterator iterator(final Comparator<BytesRef> comp) {
- final BytesRef spare = new BytesRef();
+ final BytesRefBuilder spare = new BytesRefBuilder();
final int size = size();
final int[] indices = comp == null ? null : sort(comp);
return new BytesRefIterator() {
diff --git a/lucene/core/src/java/org/apache/lucene/util/BytesRefBuilder.java b/lucene/core/src/java/org/apache/lucene/util/BytesRefBuilder.java
new file mode 100644
index 00000000000..205425ab6c9
--- /dev/null
+++ b/lucene/core/src/java/org/apache/lucene/util/BytesRefBuilder.java
@@ -0,0 +1,185 @@
+package org.apache.lucene.util;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import java.util.Arrays;
+
+/**
+ * A builder for {@link BytesRef} instances.
+ * @lucene.internal
+ */
+public class BytesRefBuilder {
+
+ private final BytesRef ref;
+
+ /** Sole constructor. */
+ public BytesRefBuilder() {
+ ref = new BytesRef();
+ }
+
+ /** Return a reference to the bytes of this builder. */
+ public byte[] bytes() {
+ return ref.bytes;
+ }
+
+ /** Return the number of bytes in this buffer. */
+ public int length() {
+ return ref.length;
+ }
+
+ /** Set the length. */
+ public void setLength(int length) {
+ this.ref.length = length;
+ }
+
+ /** Return the byte at the given offset. */
+ public byte byteAt(int offset) {
+ return ref.bytes[offset];
+ }
+
+ /** Set a byte. */
+ public void setByteAt(int offset, byte b) {
+ ref.bytes[offset] = b;
+ }
+
+ /**
+ * Ensure that this builder can hold at least <code>capacity</code> bytes
+ * without resizing.
+ */
+ public void grow(int capacity) {
+ ref.bytes = ArrayUtil.grow(ref.bytes, capacity);
+ }
+
+ /**
+ * Append a single byte to this builder.
+ */
+ public void append(byte b) {
+ grow(ref.length + 1);
+ ref.bytes[ref.length++] = b;
+ }
+
+ /**
+ * Append the provided bytes to this builder.
+ */
+ public void append(byte[] b, int off, int len) {
+ grow(ref.length + len);
+ System.arraycopy(b, off, ref.bytes, ref.length, len);
+ ref.length += len;
+ }
+
+ /**
+ * Append the provided bytes to this builder.
+ */
+ public void append(BytesRef ref) {
+ append(ref.bytes, ref.offset, ref.length);
+ }
+
+ /**
+ * Append the provided bytes to this builder.
+ */
+ public void append(BytesRefBuilder builder) {
+ append(builder.get());
+ }
+
+ /**
+ * Reset this builder to the empty state.
+ */
+ public void clear() {
+ setLength(0);
+ }
+
+ /**
+ * Replace the content of this builder with the provided bytes. Equivalent to
+ * calling {@link #clear()} and then {@link #append(byte[], int, int)}.
+ */
+ public void copyBytes(byte[] b, int off, int len) {
+ clear();
+ append(b, off, len);
+ }
+
+ /**
+ * Replace the content of this builder with the provided bytes. Equivalent to
+ * calling {@link #clear()} and then {@link #append(BytesRef)}.
+ */
+ public void copyBytes(BytesRef ref) {
+ clear();
+ append(ref);
+ }
+
+ /**
+ * Replace the content of this builder with the provided bytes. Equivalent to
+ * calling {@link #clear()} and then {@link #append(BytesRefBuilder)}.
+ */
+ public void copyBytes(BytesRefBuilder builder) {
+ clear();
+ append(builder);
+ }
+
+ /**
+ * Replace the content of this buffer with UTF-8 encoded bytes that would
+ * represent the provided text.
+ */
+ public void copyChars(CharSequence text) {
+ copyChars(text, 0, text.length());
+ }
+
+ /**
+ * Replace the content of this buffer with UTF-8 encoded bytes that would
+ * represent the provided text.
+ */
+ public void copyChars(CharSequence text, int off, int len) {
+ grow(len * UnicodeUtil.MAX_UTF8_BYTES_PER_CHAR);
+ ref.length = UnicodeUtil.UTF16toUTF8(text, off, len, ref.bytes);
+ }
+
+ /**
+ * Replace the content of this buffer with UTF-8 encoded bytes that would
+ * represent the provided text.
+ */
+ public void copyChars(char[] text, int off, int len) {
+ grow(len * UnicodeUtil.MAX_UTF8_BYTES_PER_CHAR);
+ ref.length = UnicodeUtil.UTF16toUTF8(text, off, len, ref.bytes);
+ }
+
+ /**
+ * Return a {@link BytesRef} that points to the internal content of this
+ * builder. Any update to the content of this builder might invalidate
+ * the provided <code>ref</code> and vice-versa.
+ */
+ public BytesRef get() {
+ assert ref.offset == 0 : "Modifying the offset of the returned ref is illegal";
+ return ref;
+ }
+
+ /**
+ * Build a new {@link BytesRef} that has the same content as this buffer.
+ */
+ public BytesRef toBytesRef() {
+ return new BytesRef(Arrays.copyOf(ref.bytes, ref.length));
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public int hashCode() {
+ throw new UnsupportedOperationException();
+ }
+}
diff --git a/lucene/core/src/java/org/apache/lucene/util/CharsRef.java b/lucene/core/src/java/org/apache/lucene/util/CharsRef.java
index 4eb6646a53e..a10581576f9 100644
--- a/lucene/core/src/java/org/apache/lucene/util/CharsRef.java
+++ b/lucene/core/src/java/org/apache/lucene/util/CharsRef.java
@@ -17,6 +17,7 @@ package org.apache.lucene.util;
* limitations under the License.
*/
+import java.util.Arrays;
import java.util.Comparator;
/**
@@ -147,55 +148,6 @@ public final class CharsRef implements Comparable<CharsRef>, CharSequence, Clone
// One is a prefix of the other, or, they are equal:
return this.length - other.length;
}
-
- /**
- * Copies the given {@link CharsRef} referenced content into this instance.
- *
- * @param other
- * the {@link CharsRef} to copy
- */
- public void copyChars(CharsRef other) {
- copyChars(other.chars, other.offset, other.length);
- }
-
- /**
- * Used to grow the reference array.
- *
- * In general this should not be used as it does not take the offset into account.
- * @lucene.internal */
- public void grow(int newLength) {
- assert offset == 0;
- if (chars.length < newLength) {
- chars = ArrayUtil.grow(chars, newLength);
- }
- }
-
- /**
- * Copies the given array into this CharsRef.
- */
- public void copyChars(char[] otherChars, int otherOffset, int otherLength) {
- if (chars.length - offset < otherLength) {
- chars = new char[otherLength];
- offset = 0;
- }
- System.arraycopy(otherChars, otherOffset, chars, offset, otherLength);
- length = otherLength;
- }
-
- /**
- * Appends the given array to this CharsRef
- */
- public void append(char[] otherChars, int otherOffset, int otherLength) {
- int newLen = length + otherLength;
- if (chars.length - offset < newLen) {
- char[] newChars = new char[newLen];
- System.arraycopy(chars, offset, newChars, 0, length);
- offset = 0;
- chars = newChars;
- }
- System.arraycopy(otherChars, otherOffset, chars, length+offset, otherLength);
- length = newLen;
- }
@Override
public String toString() {
@@ -292,9 +244,7 @@ public final class CharsRef implements Comparable<CharsRef>, CharSequence, Clone
* and an offset of zero.
*/
public static CharsRef deepCopyOf(CharsRef other) {
- CharsRef clone = new CharsRef();
- clone.copyChars(other);
- return clone;
+ return new CharsRef(Arrays.copyOfRange(other.chars, other.offset, other.offset + other.length), 0, other.length);
}
/**
diff --git a/lucene/core/src/java/org/apache/lucene/util/CharsRefBuilder.java b/lucene/core/src/java/org/apache/lucene/util/CharsRefBuilder.java
new file mode 100644
index 00000000000..eaebd51ad2d
--- /dev/null
+++ b/lucene/core/src/java/org/apache/lucene/util/CharsRefBuilder.java
@@ -0,0 +1,144 @@
+package org.apache.lucene.util;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import java.util.Arrays;
+
+/**
+ * A builder for {@link CharsRef} instances.
+ * @lucene.internal
+ */
+public class CharsRefBuilder {
+
+ private final CharsRef ref;
+
+ /** Sole constructor. */
+ public CharsRefBuilder() {
+ ref = new CharsRef();
+ }
+
+ /** Return a reference to the chars of this builder. */
+ public char[] chars() {
+ return ref.chars;
+ }
+
+ /** Return the number of chars in this buffer. */
+ public int length() {
+ return ref.length;
+ }
+
+ /** Set the length. */
+ public void setLength(int length) {
+ this.ref.length = length;
+ }
+
+ /** Return the char at the given offset. */
+ public char charAt(int offset) {
+ return ref.chars[offset];
+ }
+
+ /** Set a char. */
+ public void setCharAt(int offset, char b) {
+ ref.chars[offset] = b;
+ }
+
+ /**
+ * Reset this builder to the empty state.
+ */
+ public void clear() {
+ ref.length = 0;
+ }
+
+ /**
+ * Copies the given {@link CharsRef} referenced content into this instance.
+ */
+ public void copyChars(CharsRef other) {
+ copyChars(other.chars, other.offset, other.length);
+ }
+
+ /**
+ * Used to grow the reference array.
+ */
+ public void grow(int newLength) {
+ ref.chars = ArrayUtil.grow(ref.chars, newLength);
+ }
+
+ /**
+ * Copy the provided bytes, interpreted as UTF-8 bytes.
+ */
+ public void copyUTF8Bytes(byte[] bytes, int offset, int length) {
+ grow(length);
+ ref.length = UnicodeUtil.UTF8toUTF16(bytes, offset, length, ref.chars);
+ }
+
+ /**
+ * Copy the provided bytes, interpreted as UTF-8 bytes.
+ */
+ public void copyUTF8Bytes(BytesRef bytes) {
+ copyUTF8Bytes(bytes.bytes, bytes.offset, bytes.length);
+ }
+
+ /**
+ * Copies the given array into this instance.
+ */
+ public void copyChars(char[] otherChars, int otherOffset, int otherLength) {
+ grow(otherLength);
+ System.arraycopy(otherChars, otherOffset, ref.chars, 0, otherLength);
+ ref.length = otherLength;
+ }
+
+ /**
+ * Appends the given array to this CharsRef
+ */
+ public void append(char[] otherChars, int otherOffset, int otherLength) {
+ int newLen = ref.length + otherLength;
+ grow(newLen);
+ System.arraycopy(otherChars, otherOffset, ref.chars, ref.length, otherLength);
+ ref.length = newLen;
+ }
+
+ /**
+ * Return a {@link CharsRef} that points to the internal content of this
+ * builder. Any update to the content of this builder might invalidate
+ * the provided <code>ref</code> and vice-versa.
+ */
+ public CharsRef get() {
+ assert ref.offset == 0 : "Modifying the offset of the returned ref is illegal";
+ return ref;
+ }
+
+ /** Build a new {@link CharsRef} that has the same content as this builder. */
+ public CharsRef toCharsRef() {
+ return new CharsRef(Arrays.copyOf(ref.chars, ref.length), 0, ref.length);
+ }
+
+ @Override
+ public String toString() {
+ return get().toString();
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public int hashCode() {
+ throw new UnsupportedOperationException();
+ }
+}
diff --git a/lucene/core/src/java/org/apache/lucene/util/IntsRef.java b/lucene/core/src/java/org/apache/lucene/util/IntsRef.java
index f69e10521cd..c696a214118 100644
--- a/lucene/core/src/java/org/apache/lucene/util/IntsRef.java
+++ b/lucene/core/src/java/org/apache/lucene/util/IntsRef.java
@@ -1,5 +1,7 @@
package org.apache.lucene.util;
+import java.util.Arrays;
+
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
@@ -132,27 +134,6 @@ public final class IntsRef implements Comparable<IntsRef>, Cloneable {
return this.length - other.length;
}
- public void copyInts(IntsRef other) {
- if (ints.length - offset < other.length) {
- ints = new int[other.length];
- offset = 0;
- }
- System.arraycopy(other.ints, other.offset, ints, offset, other.length);
- length = other.length;
- }
-
- /**
- * Used to grow the reference array.
- *
- * In general this should not be used as it does not take the offset into account.
- * @lucene.internal */
- public void grow(int newLength) {
- assert offset == 0;
- if (ints.length < newLength) {
- ints = ArrayUtil.grow(ints, newLength);
- }
- }
-
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
@@ -176,9 +157,7 @@ public final class IntsRef implements Comparable<IntsRef>, Cloneable {
* and an offset of zero.
*/
public static IntsRef deepCopyOf(IntsRef other) {
- IntsRef clone = new IntsRef();
- clone.copyInts(other);
- return clone;
+ return new IntsRef(Arrays.copyOfRange(other.ints, other.offset, other.offset + other.length), 0, other.length);
}
/**
diff --git a/lucene/core/src/java/org/apache/lucene/util/IntsRefBuilder.java b/lucene/core/src/java/org/apache/lucene/util/IntsRefBuilder.java
new file mode 100644
index 00000000000..17c20d3d8b2
--- /dev/null
+++ b/lucene/core/src/java/org/apache/lucene/util/IntsRefBuilder.java
@@ -0,0 +1,127 @@
+package org.apache.lucene.util;
+
+/*
+ * 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.
+ */
+
+/**
+ * A builder for {@link IntsRef} instances.
+ * @lucene.internal
+ */
+public class IntsRefBuilder {
+
+ private final IntsRef ref;
+
+ /** Sole constructor. */
+ public IntsRefBuilder() {
+ ref = new IntsRef();
+ }
+
+ /** Return a reference to the ints of this builder. */
+ public int[] ints() {
+ return ref.ints;
+ }
+
+ /** Return the number of ints in this buffer. */
+ public int length() {
+ return ref.length;
+ }
+
+ /** Set the length. */
+ public void setLength(int length) {
+ this.ref.length = length;
+ }
+
+ /** Empty this builder. */
+ public void clear() {
+ setLength(0);
+ }
+
+ /** Return the int at the given offset. */
+ public int intAt(int offset) {
+ return ref.ints[offset];
+ }
+
+ /** Set an int. */
+ public void setIntAt(int offset, int b) {
+ ref.ints[offset] = b;
+ }
+
+ /** Append the provided int to this buffer. */
+ public void append(int i) {
+ grow(ref.length + 1);
+ ref.ints[ref.length++] = i;
+ }
+
+ /**
+ * Used to grow the reference array.
+ *
+ * In general this should not be used as it does not take the offset into account.
+ * @lucene.internal */
+ public void grow(int newLength) {
+ ref.ints = ArrayUtil.grow(ref.ints, newLength);
+ }
+
+ /**
+ * Copies the given array into this instance.
+ */
+ public void copyInts(int[] otherInts, int otherOffset, int otherLength) {
+ grow(otherLength);
+ System.arraycopy(otherInts, otherOffset, ref.ints, 0, otherLength);
+ ref.length = otherLength;
+ }
+
+ /**
+ * Copies the given array into this instance.
+ */
+ public void copyInts(IntsRef ints) {
+ copyInts(ints.ints, ints.offset, ints.length);
+ }
+
+ /**
+ * Copy the given UTF-8 bytes into this builder. Works as if the bytes were
+ * first converted from UTF-8 to UTF-32 and then copied into this builder.
+ */
+ public void copyUTF8Bytes(BytesRef bytes) {
+ grow(bytes.length);
+ ref.length = UnicodeUtil.UTF8toUTF32(bytes, ref.ints);
+ }
+
+ /**
+ * Return a {@link IntsRef} that points to the internal content of this
+ * builder. Any update to the content of this builder might invalidate
+ * the provided <code>ref</code> and vice-versa.
+ */
+ public IntsRef get() {
+ assert ref.offset == 0 : "Modifying the offset of the returned ref is illegal";
+ return ref;
+ }
+
+ /** Build a new {@link CharsRef} that has the same content as this builder. */
+ public IntsRef toIntsRef() {
+ return IntsRef.deepCopyOf(get());
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public int hashCode() {
+ throw new UnsupportedOperationException();
+ }
+}
diff --git a/lucene/core/src/java/org/apache/lucene/util/LongsRef.java b/lucene/core/src/java/org/apache/lucene/util/LongsRef.java
index 52ad1f106b5..5446bc83f2a 100644
--- a/lucene/core/src/java/org/apache/lucene/util/LongsRef.java
+++ b/lucene/core/src/java/org/apache/lucene/util/LongsRef.java
@@ -1,5 +1,7 @@
package org.apache.lucene.util;
+import java.util.Arrays;
+
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
@@ -131,27 +133,6 @@ public final class LongsRef implements Comparable<LongsRef>, Cloneable {
return this.length - other.length;
}
- public void copyLongs(LongsRef other) {
- if (longs.length - offset < other.length) {
- longs = new long[other.length];
- offset = 0;
- }
- System.arraycopy(other.longs, other.offset, longs, offset, other.length);
- length = other.length;
- }
-
- /**
- * Used to grow the reference array.
- *
- * In general this should not be used as it does not take the offset into account.
- * @lucene.internal */
- public void grow(int newLength) {
- assert offset == 0;
- if (longs.length < newLength) {
- longs = ArrayUtil.grow(longs, newLength);
- }
- }
-
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
@@ -168,16 +149,14 @@ public final class LongsRef implements Comparable<LongsRef>, Cloneable {
}
/**
- * Creates a new IntsRef that points to a copy of the longs from
+ * Creates a new LongsRef that points to a copy of the longs from
* <code>other</code>
* <p>
* The returned IntsRef will have a length of other.length
* and an offset of zero.
*/
public static LongsRef deepCopyOf(LongsRef other) {
- LongsRef clone = new LongsRef();
- clone.copyLongs(other);
- return clone;
+ return new LongsRef(Arrays.copyOfRange(other.longs, other.offset, other.offset + other.length), 0, other.length);
}
/**
diff --git a/lucene/core/src/java/org/apache/lucene/util/NumericUtils.java b/lucene/core/src/java/org/apache/lucene/util/NumericUtils.java
index 995eb8cbf10..4380e36f2e6 100644
--- a/lucene/core/src/java/org/apache/lucene/util/NumericUtils.java
+++ b/lucene/core/src/java/org/apache/lucene/util/NumericUtils.java
@@ -118,7 +118,7 @@ public final class NumericUtils {
* @param shift how many bits to strip from the right
* @param bytes will contain the encoded value
*/
- public static void longToPrefixCoded(final long val, final int shift, final BytesRef bytes) {
+ public static void longToPrefixCoded(final long val, final int shift, final BytesRefBuilder bytes) {
longToPrefixCodedBytes(val, shift, bytes);
}
@@ -130,7 +130,7 @@ public final class NumericUtils {
* @param shift how many bits to strip from the right
* @param bytes will contain the encoded value
*/
- public static void intToPrefixCoded(final int val, final int shift, final BytesRef bytes) {
+ public static void intToPrefixCoded(final int val, final int shift, final BytesRefBuilder bytes) {
intToPrefixCodedBytes(val, shift, bytes);
}
@@ -142,22 +142,19 @@ public final class NumericUtils {
* @param shift how many bits to strip from the right
* @param bytes will contain the encoded value
*/
- public static void longToPrefixCodedBytes(final long val, final int shift, final BytesRef bytes) {
+ public static void longToPrefixCodedBytes(final long val, final int shift, final BytesRefBuilder bytes) {
if ((shift & ~0x3f) != 0) // ensure shift is 0..63
throw new IllegalArgumentException("Illegal shift value, must be 0..63");
int nChars = (((63-shift)*37)>>8) + 1; // i/7 is the same as (i*37)>>8 for i in 0..63
- bytes.offset = 0;
- bytes.length = nChars+1; // one extra for the byte that contains the shift info
- if (bytes.bytes.length < bytes.length) {
- bytes.bytes = new byte[NumericUtils.BUF_SIZE_LONG]; // use the max
- }
- bytes.bytes[0] = (byte)(SHIFT_START_LONG + shift);
+ bytes.setLength(nChars+1); // one extra for the byte that contains the shift info
+ bytes.grow(BUF_SIZE_LONG);
+ bytes.setByteAt(0, (byte)(SHIFT_START_LONG + shift));
long sortableBits = val ^ 0x8000000000000000L;
sortableBits >>>= shift;
while (nChars > 0) {
// Store 7 bits per byte for compatibility
// with UTF-8 encoding of terms
- bytes.bytes[nChars--] = (byte)(sortableBits & 0x7f);
+ bytes.setByteAt(nChars--, (byte)(sortableBits & 0x7f));
sortableBits >>>= 7;
}
}
@@ -171,22 +168,19 @@ public final class NumericUtils {
* @param shift how many bits to strip from the right
* @param bytes will contain the encoded value
*/
- public static void intToPrefixCodedBytes(final int val, final int shift, final BytesRef bytes) {
+ public static void intToPrefixCodedBytes(final int val, final int shift, final BytesRefBuilder bytes) {
if ((shift & ~0x1f) != 0) // ensure shift is 0..31
throw new IllegalArgumentException("Illegal shift value, must be 0..31");
int nChars = (((31-shift)*37)>>8) + 1; // i/7 is the same as (i*37)>>8 for i in 0..63
- bytes.offset = 0;
- bytes.length = nChars+1; // one extra for the byte that contains the shift info
- if (bytes.bytes.length < bytes.length) {
- bytes.bytes = new byte[NumericUtils.BUF_SIZE_LONG]; // use the max
- }
- bytes.bytes[0] = (byte)(SHIFT_START_INT + shift);
+ bytes.setLength(nChars+1); // one extra for the byte that contains the shift info
+ bytes.grow(NumericUtils.BUF_SIZE_LONG); // use the max
+ bytes.setByteAt(0, (byte)(SHIFT_START_INT + shift));
int sortableBits = val ^ 0x80000000;
sortableBits >>>= shift;
while (nChars > 0) {
// Store 7 bits per byte for compatibility
// with UTF-8 encoding of terms
- bytes.bytes[nChars--] = (byte)(sortableBits & 0x7f);
+ bytes.setByteAt(nChars--, (byte)(sortableBits & 0x7f));
sortableBits >>>= 7;
}
}
@@ -430,10 +424,10 @@ public final class NumericUtils {
* You can use this for e.g. debugging purposes (print out range bounds).
*/
public void addRange(final long min, final long max, final int shift) {
- final BytesRef minBytes = new BytesRef(BUF_SIZE_LONG), maxBytes = new BytesRef(BUF_SIZE_LONG);
+ final BytesRefBuilder minBytes = new BytesRefBuilder(), maxBytes = new BytesRefBuilder();
longToPrefixCodedBytes(min, shift, minBytes);
longToPrefixCodedBytes(max, shift, maxBytes);
- addRange(minBytes, maxBytes);
+ addRange(minBytes.get(), maxBytes.get());
}
}
@@ -459,10 +453,10 @@ public final class NumericUtils {
* You can use this for e.g. debugging purposes (print out range bounds).
*/
public void addRange(final int min, final int max, final int shift) {
- final BytesRef minBytes = new BytesRef(BUF_SIZE_INT), maxBytes = new BytesRef(BUF_SIZE_INT);
+ final BytesRefBuilder minBytes = new BytesRefBuilder(), maxBytes = new BytesRefBuilder();
intToPrefixCodedBytes(min, shift, minBytes);
intToPrefixCodedBytes(max, shift, maxBytes);
- addRange(minBytes, maxBytes);
+ addRange(minBytes.get(), maxBytes.get());
}
}
diff --git a/lucene/core/src/java/org/apache/lucene/util/OfflineSorter.java b/lucene/core/src/java/org/apache/lucene/util/OfflineSorter.java
index 305b98556d7..30a82b2b21b 100644
--- a/lucene/core/src/java/org/apache/lucene/util/OfflineSorter.java
+++ b/lucene/core/src/java/org/apache/lucene/util/OfflineSorter.java
@@ -359,7 +359,7 @@ public final class OfflineSorter {
PriorityQueue<FileAndTop> queue = new PriorityQueue<FileAndTop>(merges.size()) {
@Override
protected boolean lessThan(FileAndTop a, FileAndTop b) {
- return comparator.compare(a.current, b.current) < 0;
+ return comparator.compare(a.current.get(), b.current.get()) < 0;
}
};
@@ -380,7 +380,7 @@ public final class OfflineSorter {
// so it shouldn't make much of a difference (didn't check).
FileAndTop top;
while ((top = queue.top()) != null) {
- out.write(top.current);
+ out.write(top.current.bytes(), 0, top.current.length());
if (!streams[top.fd].read(top.current)) {
queue.pop();
} else {
@@ -420,11 +420,12 @@ public final class OfflineSorter {
static class FileAndTop {
final int fd;
- final BytesRef current;
+ final BytesRefBuilder current;
- FileAndTop(int fd, byte [] firstLine) {
+ FileAndTop(int fd, byte[] firstLine) {
this.fd = fd;
- this.current = new BytesRef(firstLine);
+ this.current = new BytesRefBuilder();
+ this.current.copyBytes(firstLine, 0, firstLine.length);
}
}
@@ -519,7 +520,7 @@ public final class OfflineSorter {
* the header of the next sequence. Returns <code>true</code> otherwise.
* @throws EOFException if the file ends before the full sequence is read.
*/
- public boolean read(BytesRef ref) throws IOException {
+ public boolean read(BytesRefBuilder ref) throws IOException {
short length;
try {
length = is.readShort();
@@ -528,16 +529,15 @@ public final class OfflineSorter {
}
ref.grow(length);
- ref.offset = 0;
- ref.length = length;
- is.readFully(ref.bytes, 0, length);
+ ref.setLength(length);
+ is.readFully(ref.bytes(), 0, length);
return true;
}
/**
* Reads the next entry and returns it if successful.
*
- * @see #read(BytesRef)
+ * @see #read(BytesRefBuilder)
*
* @return Returns <code>null</code> if EOF occurred before the next entry
* could be read.
diff --git a/lucene/core/src/java/org/apache/lucene/util/UnicodeUtil.java b/lucene/core/src/java/org/apache/lucene/util/UnicodeUtil.java
index 7ebddeabded..c2eb809a59f 100644
--- a/lucene/core/src/java/org/apache/lucene/util/UnicodeUtil.java
+++ b/lucene/core/src/java/org/apache/lucene/util/UnicodeUtil.java
@@ -1,6 +1,5 @@
package org.apache.lucene.util;
-import java.nio.charset.StandardCharsets;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
@@ -123,21 +122,18 @@ public final class UnicodeUtil {
Character.MIN_SUPPLEMENTARY_CODE_POINT -
(UNI_SUR_HIGH_START << HALF_SHIFT) - UNI_SUR_LOW_START;
+ /** Maximum number of UTF8 bytes per UTF16 character. */
+ public static final int MAX_UTF8_BYTES_PER_CHAR = 4;
+
/** Encode characters from a char[] source, starting at
- * offset for length chars. After encoding, result.offset will always be 0.
+ * offset for length chars. It is the responsibility of the
+ * caller to make sure that the destination array is large enough.
*/
- // TODO: broken if incoming result.offset != 0
- public static void UTF16toUTF8(final char[] source, final int offset, final int length, BytesRef result) {
+ public static int UTF16toUTF8(final char[] source, final int offset, final int length, byte[] out) {
int upto = 0;
int i = offset;
final int end = offset + length;
- byte[] out = result.bytes;
- // Pre-allocate for worst case 4-for-1
- final int maxLen = length * 4;
- if (out.length < maxLen)
- out = result.bytes = new byte[maxLen];
- result.offset = 0;
while(i < end) {
@@ -176,23 +172,17 @@ public final class UnicodeUtil {
}
}
//assert matches(source, offset, length, out, upto);
- result.length = upto;
+ return upto;
}
/** Encode characters from this String, starting at offset
- * for length characters. After encoding, result.offset will always be 0.
+ * for length characters. It is the responsibility of the
+ * caller to make sure that the destination array is large enough.
*/
// TODO: broken if incoming result.offset != 0
- public static void UTF16toUTF8(final CharSequence s, final int offset, final int length, BytesRef result) {
+ public static int UTF16toUTF8(final CharSequence s, final int offset, final int length, byte[] out) {
final int end = offset + length;
- byte[] out = result.bytes;
- result.offset = 0;
- // Pre-allocate for worst case 4-for-1
- final int maxLen = length * 4;
- if (out.length < maxLen)
- out = result.bytes = new byte[maxLen];
-
int upto = 0;
for(int i=offset;i<end;i++) {
final int code = (int) s.charAt(i);
@@ -230,7 +220,7 @@ public final class UnicodeUtil {
}
}
//assert matches(s, offset, length, out, upto);
- result.length = upto;
+ return upto;
}
// Only called from assert
@@ -405,21 +395,16 @@ public final class UnicodeUtil {
* <p>This method assumes valid UTF8 input. This method
* <strong>does not perform</strong> full UTF8 validation, it will check only the
* first byte of each codepoint (for multi-byte sequences any bytes after
- * the head are skipped).
+ * the head are skipped). It is the responsibility of the caller to make sure
+ * that the destination array is large enough.
*
* @throws IllegalArgumentException If invalid codepoint header byte occurs or the
* content is prematurely truncated.
*/
- public static void UTF8toUTF32(final BytesRef utf8, final IntsRef utf32) {
- // TODO: broken if incoming result.offset != 0
- // pre-alloc for worst case
+ public static int UTF8toUTF32(final BytesRef utf8, final int[] ints) {
// TODO: ints cannot be null, should be an assert
- if (utf32.ints == null || utf32.ints.length < utf8.length) {
- utf32.ints = new int[utf8.length];
- }
int utf32Count = 0;
int utf8Upto = utf8.offset;
- final int[] ints = utf32.ints;
final byte[] bytes = utf8.bytes;
final int utf8Limit = utf8.offset + utf8.length;
while(utf8Upto < utf8Limit) {
@@ -453,8 +438,7 @@ public final class UnicodeUtil {
ints[utf32Count++] = v;
}
- utf32.offset = 0;
- utf32.length = utf32Count;
+ return utf32Count;
}
/** Shift value for lead surrogate to form a supplementary character. */
@@ -545,17 +529,16 @@ public final class UnicodeUtil {
}
/**
- * Interprets the given byte array as UTF-8 and converts to UTF-16. The {@link CharsRef} will be extended if
- * it doesn't provide enough space to hold the worst case of each byte becoming a UTF-16 codepoint.
+ * Interprets the given byte array as UTF-8 and converts to UTF-16. It is the
+ * responsibility of the caller to make sure that the destination array is large enough.
* <p>
* NOTE: Full characters are read, even if this reads past the length passed (and
* can result in an ArrayOutOfBoundsException if invalid UTF-8 is passed).
* Explicit checks for valid UTF-8 are not performed.
*/
// TODO: broken if chars.offset != 0
- public static void UTF8toUTF16(byte[] utf8, int offset, int length, CharsRef chars) {
- int out_offset = chars.offset = 0;
- final char[] out = chars.chars = ArrayUtil.grow(chars.chars, length);
+ public static int UTF8toUTF16(byte[] utf8, int offset, int length, char[] out) {
+ int out_offset = 0;
final int limit = offset + length;
while (offset < limit) {
int b = utf8[offset++]&0xff;
@@ -580,15 +563,15 @@ public final class UnicodeUtil {
}
}
}
- chars.length = out_offset - chars.offset;
+ return out_offset;
}
/**
- * Utility method for {@link #UTF8toUTF16(byte[], int, int, CharsRef)}
- * @see #UTF8toUTF16(byte[], int, int, CharsRef)
+ * Utility method for {@link #UTF8toUTF16(byte[], int, int, char[])}
+ * @see #UTF8toUTF16(byte[], int, int, char[])
*/
- public static void UTF8toUTF16(BytesRef bytesRef, CharsRef chars) {
- UTF8toUTF16(bytesRef.bytes, bytesRef.offset, bytesRef.length, chars);
+ public static int UTF8toUTF16(BytesRef bytesRef, char[] chars) {
+ return UTF8toUTF16(bytesRef.bytes, bytesRef.offset, bytesRef.length, chars);
}
}
diff --git a/lucene/core/src/java/org/apache/lucene/util/automaton/CompiledAutomaton.java b/lucene/core/src/java/org/apache/lucene/util/automaton/CompiledAutomaton.java
index ab2358a0988..df683240972 100644
--- a/lucene/core/src/java/org/apache/lucene/util/automaton/CompiledAutomaton.java
+++ b/lucene/core/src/java/org/apache/lucene/util/automaton/CompiledAutomaton.java
@@ -26,6 +26,7 @@ import org.apache.lucene.index.TermsEnum;
import org.apache.lucene.search.PrefixTermsEnum;
import org.apache.lucene.index.SingleTermsEnum;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
/**
* Immutable class holding compiled details for a given
@@ -195,7 +196,7 @@ public class CompiledAutomaton {
//private static final boolean DEBUG = BlockTreeTermsWriter.DEBUG;
- private BytesRef addTail(int state, BytesRef term, int idx, int leadLabel) {
+ private BytesRef addTail(int state, BytesRefBuilder term, int idx, int leadLabel) {
//System.out.println("addTail state=" + state + " term=" + term.utf8ToString() + " idx=" + idx + " leadLabel=" + (char) leadLabel);
//System.out.println(automaton.toDot());
// Find biggest transition that's < label
@@ -225,11 +226,9 @@ public class CompiledAutomaton {
floorLabel = transition.max;
}
//System.out.println(" floorLabel=" + (char) floorLabel);
- if (idx >= term.bytes.length) {
- term.grow(1+idx);
- }
+ term.grow(1+idx);
//if (DEBUG) System.out.println(" add floorLabel=" + (char) floorLabel + " idx=" + idx);
- term.bytes[idx] = (byte) floorLabel;
+ term.setByteAt(idx, (byte) floorLabel);
state = transition.dest;
//System.out.println(" dest: " + state);
@@ -241,20 +240,18 @@ public class CompiledAutomaton {
if (numTransitions == 0) {
//System.out.println("state=" + state + " 0 trans");
assert runAutomaton.isAccept(state);
- term.length = idx;
+ term.setLength(idx);
//if (DEBUG) System.out.println(" return " + term.utf8ToString());
- return term;
+ return term.get();
} else {
// We are pushing "top" -- so get last label of
// last transition:
//System.out.println("get state=" + state + " numTrans=" + numTransitions);
automaton.getTransition(state, numTransitions-1, transition);
- if (idx >= term.bytes.length) {
- term.grow(1+idx);
- }
+ term.grow(1+idx);
//if (DEBUG) System.out.println(" push maxLabel=" + (char) lastTransition.max + " idx=" + idx);
//System.out.println(" add trans dest=" + scratch.dest + " label=" + (char) scratch.max);
- term.bytes[idx] = (byte) transition.max;
+ term.setByteAt(idx, (byte) transition.max);
state = transition.dest;
idx++;
}
@@ -289,13 +286,12 @@ public class CompiledAutomaton {
/** Finds largest term accepted by this Automaton, that's
* <= the provided input term. The result is placed in
* output; it's fine for output and input to point to
- * the same BytesRef. The returned result is either the
+ * the same bytes. The returned result is either the
* provided output, or null if there is no floor term
* (ie, the provided input term is before the first term
* accepted by this Automaton). */
- public BytesRef floor(BytesRef input, BytesRef output) {
+ public BytesRef floor(BytesRef input, BytesRefBuilder output) {
- output.offset = 0;
//if (DEBUG) System.out.println("CA.floor input=" + input.utf8ToString());
int state = runAutomaton.getInitialState();
@@ -303,8 +299,8 @@ public class CompiledAutomaton {
// Special case empty string:
if (input.length == 0) {
if (runAutomaton.isAccept(state)) {
- output.length = 0;
- return output;
+ output.clear();
+ return output.get();
} else {
return null;
}
@@ -321,13 +317,11 @@ public class CompiledAutomaton {
if (idx == input.length-1) {
if (nextState != -1 && runAutomaton.isAccept(nextState)) {
// Input string is accepted
- if (idx >= output.bytes.length) {
- output.grow(1+idx);
- }
- output.bytes[idx] = (byte) label;
- output.length = input.length;
+ output.grow(1+idx);
+ output.setByteAt(idx, (byte) label);
+ output.setLength(input.length);
//if (DEBUG) System.out.println(" input is accepted; return term=" + output.utf8ToString());
- return output;
+ return output.get();
} else {
nextState = -1;
}
@@ -341,18 +335,18 @@ public class CompiledAutomaton {
int numTransitions = automaton.getNumTransitions(state);
if (numTransitions == 0) {
assert runAutomaton.isAccept(state);
- output.length = idx;
+ output.setLength(idx);
//if (DEBUG) System.out.println(" return " + output.utf8ToString());
- return output;
+ return output.get();
} else {
automaton.getTransition(state, 0, transition);
if (label-1 < transition.min) {
if (runAutomaton.isAccept(state)) {
- output.length = idx;
+ output.setLength(idx);
//if (DEBUG) System.out.println(" return " + output.utf8ToString());
- return output;
+ return output.get();
}
// pop
if (stack.size() == 0) {
@@ -376,10 +370,8 @@ public class CompiledAutomaton {
return addTail(state, output, idx, label);
} else {
- if (idx >= output.bytes.length) {
- output.grow(1+idx);
- }
- output.bytes[idx] = (byte) label;
+ output.grow(1+idx);
+ output.setByteAt(idx, (byte) label);
stack.add(state);
state = nextState;
idx++;
diff --git a/lucene/core/src/java/org/apache/lucene/util/automaton/DaciukMihovAutomatonBuilder.java b/lucene/core/src/java/org/apache/lucene/util/automaton/DaciukMihovAutomatonBuilder.java
index f96b837b893..2cbdf001327 100644
--- a/lucene/core/src/java/org/apache/lucene/util/automaton/DaciukMihovAutomatonBuilder.java
+++ b/lucene/core/src/java/org/apache/lucene/util/automaton/DaciukMihovAutomatonBuilder.java
@@ -19,8 +19,10 @@ package org.apache.lucene.util.automaton;
import java.util.*;
+import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.CharsRef;
+import org.apache.lucene.util.RamUsageEstimator;
import org.apache.lucene.util.UnicodeUtil;
/**
@@ -277,10 +279,14 @@ final class DaciukMihovAutomatonBuilder {
public static Automaton build(Collection<BytesRef> input) {
final DaciukMihovAutomatonBuilder builder = new DaciukMihovAutomatonBuilder();
- CharsRef scratch = new CharsRef();
+ char[] chars = new char[0];
+ CharsRef ref = new CharsRef();
for (BytesRef b : input) {
- UnicodeUtil.UTF8toUTF16(b, scratch);
- builder.add(scratch);
+ chars = ArrayUtil.grow(chars, b.length);
+ final int len = UnicodeUtil.UTF8toUTF16(b, chars);
+ ref.chars = chars;
+ ref.length = len;
+ builder.add(ref);
}
Automaton.Builder a = new Automaton.Builder();
diff --git a/lucene/core/src/java/org/apache/lucene/util/automaton/Operations.java b/lucene/core/src/java/org/apache/lucene/util/automaton/Operations.java
index 02e84c220b5..e07bbcc4cc6 100644
--- a/lucene/core/src/java/org/apache/lucene/util/automaton/Operations.java
+++ b/lucene/core/src/java/org/apache/lucene/util/automaton/Operations.java
@@ -42,7 +42,9 @@ import java.util.Set;
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.IntsRef;
+import org.apache.lucene.util.IntsRefBuilder;
import org.apache.lucene.util.RamUsageEstimator;
/**
@@ -1073,7 +1075,7 @@ final public class Operations {
* @return common prefix
*/
public static BytesRef getCommonPrefixBytesRef(Automaton a) {
- BytesRef ref = new BytesRef(10);
+ BytesRefBuilder builder = new BytesRefBuilder();
HashSet<Integer> visited = new HashSet<>();
int s = 0;
boolean done;
@@ -1084,15 +1086,14 @@ final public class Operations {
if (a.isAccept(s) == false && a.getNumTransitions(s) == 1) {
a.getTransition(s, 0, t);
if (t.min == t.max && !visited.contains(t.dest)) {
- ref.grow(++ref.length);
- ref.bytes[ref.length - 1] = (byte) t.min;
+ builder.append((byte) t.min);
s = t.dest;
done = false;
}
}
} while (!done);
- return ref;
+ return builder.get();
}
/**
@@ -1271,23 +1272,23 @@ final public class Operations {
PathNode root = getNode(nodes, 0);
root.resetState(a, 0);
- IntsRef string = new IntsRef(1);
- string.length = 1;
+ IntsRefBuilder string = new IntsRefBuilder();
+ string.append(0);
- while (string.length > 0) {
+ while (string.length() > 0) {
- PathNode node = nodes[string.length-1];
+ PathNode node = nodes[string.length()-1];
// Get next label leaving the current node:
int label = node.nextLabel(a);
if (label != -1) {
- string.ints[string.length-1] = label;
+ string.setIntAt(string.length()-1, label);
if (a.isAccept(node.to)) {
// This transition leads to an accept state,
// so we save the current string:
- results.add(IntsRef.deepCopyOf(string));
+ results.add(string.toIntsRef());
if (results.size() == limit) {
break;
}
@@ -1302,21 +1303,21 @@ final public class Operations {
pathStates.set(node.to);
// Push node onto stack:
- if (nodes.length == string.length) {
+ if (nodes.length == string.length()) {
PathNode[] newNodes = new PathNode[ArrayUtil.oversize(nodes.length+1, RamUsageEstimator.NUM_BYTES_OBJECT_REF)];
System.arraycopy(nodes, 0, newNodes, 0, nodes.length);
nodes = newNodes;
}
- getNode(nodes, string.length).resetState(a, node.to);
- string.length++;
- string.grow(string.length);
+ getNode(nodes, string.length()).resetState(a, node.to);
+ string.setLength(string.length() + 1);
+ string.grow(string.length());
}
} else {
// No more transitions leaving this state,
// pop/return back to previous state:
assert pathStates.get(node.state);
pathStates.clear(node.state);
- string.length--;
+ string.setLength(string.length() - 1);
}
}
}
diff --git a/lucene/core/src/java/org/apache/lucene/util/fst/Builder.java b/lucene/core/src/java/org/apache/lucene/util/fst/Builder.java
index 0d8fc642969..3c5bfaa219f 100644
--- a/lucene/core/src/java/org/apache/lucene/util/fst/Builder.java
+++ b/lucene/core/src/java/org/apache/lucene/util/fst/Builder.java
@@ -21,6 +21,7 @@ import java.io.IOException;
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.IntsRef;
+import org.apache.lucene.util.IntsRefBuilder;
import org.apache.lucene.util.RamUsageEstimator;
import org.apache.lucene.util.fst.FST.INPUT_TYPE; // javadoc
import org.apache.lucene.util.packed.PackedInts;
@@ -68,7 +69,7 @@ public class Builder<T> {
private final boolean doShareNonSingletonNodes;
private final int shareMaxTailLength;
- private final IntsRef lastInput = new IntsRef();
+ private final IntsRefBuilder lastInput = new IntsRefBuilder();
// for packing
private final boolean doPackFST;
@@ -202,7 +203,7 @@ public class Builder<T> {
private void freezeTail(int prefixLenPlus1) throws IOException {
//System.out.println(" compileTail " + prefixLenPlus1);
final int downTo = Math.max(1, prefixLenPlus1);
- for(int idx=lastInput.length; idx >= downTo; idx--) {
+ for(int idx=lastInput.length(); idx >= downTo; idx--) {
boolean doPrune = false;
boolean doCompile = false;
@@ -254,11 +255,11 @@ public class Builder<T> {
if (doPrune) {
// this node doesn't make it -- deref it
node.clear();
- parent.deleteLast(lastInput.ints[lastInput.offset+idx-1], node);
+ parent.deleteLast(lastInput.intAt(idx-1), node);
} else {
if (minSuffixCount2 != 0) {
- compileAllTargets(node, lastInput.length-idx);
+ compileAllTargets(node, lastInput.length()-idx);
}
final T nextFinalOutput = node.output;
@@ -273,14 +274,14 @@ public class Builder<T> {
// this node makes it and we now compile it. first,
// compile any targets that were previously
// undecided:
- parent.replaceLast(lastInput.ints[lastInput.offset + idx-1],
- compileNode(node, 1+lastInput.length-idx),
+ parent.replaceLast(lastInput.intAt(idx-1),
+ compileNode(node, 1+lastInput.length()-idx),
nextFinalOutput,
isFinal);
} else {
// replaceLast just to install
// nextFinalOutput/isFinal onto the arc
- parent.replaceLast(lastInput.ints[lastInput.offset + idx-1],
+ parent.replaceLast(lastInput.intAt(idx-1),
node,
nextFinalOutput,
isFinal);
@@ -334,7 +335,7 @@ public class Builder<T> {
output = NO_OUTPUT;
}
- assert lastInput.length == 0 || input.compareTo(lastInput) >= 0: "inputs are added out of order lastInput=" + lastInput + " vs input=" + input;
+ assert lastInput.length() == 0 || input.compareTo(lastInput.get()) >= 0: "inputs are added out of order lastInput=" + lastInput.get() + " vs input=" + input;
assert validOutput(output);
//System.out.println("\nadd: " + input);
@@ -353,11 +354,11 @@ public class Builder<T> {
// compare shared prefix length
int pos1 = 0;
int pos2 = input.offset;
- final int pos1Stop = Math.min(lastInput.length, input.length);
+ final int pos1Stop = Math.min(lastInput.length(), input.length);
while(true) {
frontier[pos1].inputCount++;
//System.out.println(" incr " + pos1 + " ct=" + frontier[pos1].inputCount + " n=" + frontier[pos1]);
- if (pos1 >= pos1Stop || lastInput.ints[pos1] != input.ints[pos2]) {
+ if (pos1 >= pos1Stop || lastInput.intAt(pos1) != input.ints[pos2]) {
break;
}
pos1++;
@@ -387,7 +388,7 @@ public class Builder<T> {
}
final UnCompiledNode<T> lastNode = frontier[input.length];
- if (lastInput.length != input.length || prefixLenPlus1 != input.length + 1) {
+ if (lastInput.length() != input.length || prefixLenPlus1 != input.length + 1) {
lastNode.isFinal = true;
lastNode.output = NO_OUTPUT;
}
@@ -419,7 +420,7 @@ public class Builder<T> {
assert validOutput(output);
}
- if (lastInput.length == input.length && prefixLenPlus1 == 1+input.length) {
+ if (lastInput.length() == input.length && prefixLenPlus1 == 1+input.length) {
// same input more than 1 time in a row, mapping to
// multiple outputs
lastNode.output = fst.outputs.merge(lastNode.output, output);
@@ -456,11 +457,11 @@ public class Builder<T> {
}
} else {
if (minSuffixCount2 != 0) {
- compileAllTargets(root, lastInput.length);
+ compileAllTargets(root, lastInput.length());
}
}
//if (DEBUG) System.out.println(" builder.finish root.isFinal=" + root.isFinal + " root.output=" + root.output);
- fst.finish(compileNode(root, lastInput.length).node);
+ fst.finish(compileNode(root, lastInput.length()).node);
if (doPackFST) {
return fst.pack(3, Math.max(10, (int) (fst.getNodeCount()/4)), acceptableOverheadRatio);
diff --git a/lucene/core/src/java/org/apache/lucene/util/fst/Util.java b/lucene/core/src/java/org/apache/lucene/util/fst/Util.java
index 3ff8ff23828..0033eaf8616 100644
--- a/lucene/core/src/java/org/apache/lucene/util/fst/Util.java
+++ b/lucene/core/src/java/org/apache/lucene/util/fst/Util.java
@@ -18,7 +18,9 @@ package org.apache.lucene.util.fst;
*/
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.IntsRef;
+import org.apache.lucene.util.IntsRefBuilder;
import org.apache.lucene.util.fst.FST.Arc;
import org.apache.lucene.util.fst.FST.BytesReader;
@@ -112,8 +114,7 @@ public final class Util {
FST.Arc<Long> scratchArc = new FST.Arc<>();
- final IntsRef result = new IntsRef();
-
+ final IntsRefBuilder result = new IntsRefBuilder();
return getByOutput(fst, targetOutput, in, arc, scratchArc, result);
}
@@ -121,7 +122,7 @@ public final class Util {
* Expert: like {@link Util#getByOutput(FST, long)} except reusing
* BytesReader, initial and scratch Arc, and result.
*/
- public static IntsRef getByOutput(FST<Long> fst, long targetOutput, BytesReader in, Arc<Long> arc, Arc<Long> scratchArc, IntsRef result) throws IOException {
+ public static IntsRef getByOutput(FST<Long> fst, long targetOutput, BytesReader in, Arc<Long> arc, Arc<Long> scratchArc, IntsRefBuilder result) throws IOException {
long output = arc.output;
int upto = 0;
@@ -133,9 +134,9 @@ public final class Util {
final long finalOutput = output + arc.nextFinalOutput;
//System.out.println(" isFinal finalOutput=" + finalOutput);
if (finalOutput == targetOutput) {
- result.length = upto;
+ result.setLength(upto);
//System.out.println(" found!");
- return result;
+ return result.get();
} else if (finalOutput > targetOutput) {
//System.out.println(" not found!");
return null;
@@ -144,9 +145,7 @@ public final class Util {
if (FST.targetHasArcs(arc)) {
//System.out.println(" targetHasArcs");
- if (result.ints.length == upto) {
- result.grow(1+upto);
- }
+ result.grow(1+upto);
fst.readFirstRealTargetArc(arc.target, arc, in);
@@ -190,7 +189,7 @@ public final class Util {
}
fst.readNextRealArc(arc, in);
- result.ints[upto++] = arc.label;
+ result.setIntAt(upto++, arc.label);
output += arc.output;
} else {
@@ -208,7 +207,7 @@ public final class Util {
// Recurse on this arc:
//System.out.println(" match! break");
output = minArcOutput;
- result.ints[upto++] = arc.label;
+ result.setIntAt(upto++, arc.label);
break;
} else if (minArcOutput > targetOutput) {
if (prevArc == null) {
@@ -217,7 +216,7 @@ public final class Util {
} else {
// Recurse on previous arc:
arc.copyFrom(prevArc);
- result.ints[upto++] = arc.label;
+ result.setIntAt(upto++, arc.label);
output += arc.output;
//System.out.println(" recurse prev label=" + (char) arc.label + " output=" + output);
break;
@@ -226,7 +225,7 @@ public final class Util {
// Recurse on this arc:
output = minArcOutput;
//System.out.println(" recurse last label=" + (char) arc.label + " output=" + output);
- result.ints[upto++] = arc.label;
+ result.setIntAt(upto++, arc.label);
break;
} else {
// Read next arc in this node:
@@ -251,10 +250,10 @@ public final class Util {
public static class FSTPath<T> {
public FST.Arc<T> arc;
public T cost;
- public final IntsRef input;
+ public final IntsRefBuilder input;
/** Sole constructor */
- public FSTPath(T cost, FST.Arc<T> arc, IntsRef input) {
+ public FSTPath(T cost, FST.Arc<T> arc, IntsRefBuilder input) {
this.arc = new FST.Arc<T>().copyFrom(arc);
this.cost = cost;
this.input = input;
@@ -278,7 +277,7 @@ public final class Util {
public int compare(FSTPath<T> a, FSTPath<T> b) {
int cmp = comparator.compare(a.cost, b.cost);
if (cmp == 0) {
- return a.input.compareTo(b.input);
+ return a.input.get().compareTo(b.input.get());
} else {
return cmp;
}
@@ -333,10 +332,9 @@ public final class Util {
return;
} else if (comp == 0) {
// Tie break by alpha sort on the input:
- path.input.grow(path.input.length+1);
- path.input.ints[path.input.length++] = path.arc.label;
- final int cmp = bottom.input.compareTo(path.input);
- path.input.length--;
+ path.input.append(path.arc.label);
+ final int cmp = bottom.input.get().compareTo(path.input.get());
+ path.input.setLength(path.input.length() - 1);
// We should never see dups:
assert cmp != 0;
@@ -353,10 +351,9 @@ public final class Util {
// copy over the current input to the new input
// and add the arc.label to the end
- IntsRef newInput = new IntsRef(path.input.length+1);
- System.arraycopy(path.input.ints, 0, newInput.ints, 0, path.input.length);
- newInput.ints[path.input.length] = path.arc.label;
- newInput.length = path.input.length+1;
+ IntsRefBuilder newInput = new IntsRefBuilder();
+ newInput.copyInts(path.input.get());
+ newInput.append(path.arc.label);
final FSTPath<T> newPath = new FSTPath<>(cost, path.arc, newInput);
queue.add(newPath);
@@ -368,7 +365,7 @@ public final class Util {
/** Adds all leaving arcs, including 'finished' arc, if
* the node is final, from this node into the queue. */
- public void addStartPaths(FST.Arc<T> node, T startOutput, boolean allowEmptyString, IntsRef input) throws IOException {
+ public void addStartPaths(FST.Arc<T> node, T startOutput, boolean allowEmptyString, IntsRefBuilder input) throws IOException {
// De-dup NO_OUTPUT since it must be a singleton:
if (startOutput.equals(fst.outputs.getNoOutput())) {
@@ -434,8 +431,8 @@ public final class Util {
if (path.arc.label == FST.END_LABEL) {
//System.out.println(" empty string! cost=" + path.cost);
// Empty string!
- path.input.length--;
- results.add(new Result<>(path.input, path.cost));
+ path.input.setLength(path.input.length() - 1);
+ results.add(new Result<>(path.input.get(), path.cost));
continue;
}
@@ -497,17 +494,15 @@ public final class Util {
// Add final output:
//System.out.println(" done!: " + path);
T finalOutput = fst.outputs.add(path.cost, path.arc.output);
- if (acceptResult(path.input, finalOutput)) {
+ if (acceptResult(path.input.get(), finalOutput)) {
//System.out.println(" add result: " + path);
- results.add(new Result<>(path.input, finalOutput));
+ results.add(new Result<>(path.input.get(), finalOutput));
} else {
rejectCount++;
}
break;
} else {
- path.input.grow(1+path.input.length);
- path.input.ints[path.input.length] = path.arc.label;
- path.input.length++;
+ path.input.append(path.arc.label);
path.cost = fst.outputs.add(path.cost, path.arc.output);
}
}
@@ -571,7 +566,7 @@ public final class Util {
// since this search is initialized with a single start node
// it is okay to start with an empty input path here
- searcher.addStartPaths(fromNode, startOutput, allowEmptyString, new IntsRef());
+ searcher.addStartPaths(fromNode, startOutput, allowEmptyString, new IntsRefBuilder());
return searcher.search();
}
@@ -817,76 +812,74 @@ public final class Util {
/** Just maps each UTF16 unit (char) to the ints in an
* IntsRef. */
- public static IntsRef toUTF16(CharSequence s, IntsRef scratch) {
+ public static IntsRef toUTF16(CharSequence s, IntsRefBuilder scratch) {
final int charLimit = s.length();
- scratch.offset = 0;
- scratch.length = charLimit;
+ scratch.setLength(charLimit);
scratch.grow(charLimit);
for (int idx = 0; idx < charLimit; idx++) {
- scratch.ints[idx] = (int) s.charAt(idx);
+ scratch.setIntAt(idx, (int) s.charAt(idx));
}
- return scratch;
+ return scratch.get();
}
/** Decodes the Unicode codepoints from the provided
* CharSequence and places them in the provided scratch
* IntsRef, which must not be null, returning it. */
- public static IntsRef toUTF32(CharSequence s, IntsRef scratch) {
+ public static IntsRef toUTF32(CharSequence s, IntsRefBuilder scratch) {
int charIdx = 0;
int intIdx = 0;
final int charLimit = s.length();
while(charIdx < charLimit) {
scratch.grow(intIdx+1);
final int utf32 = Character.codePointAt(s, charIdx);
- scratch.ints[intIdx] = utf32;
+ scratch.setIntAt(intIdx, utf32);
charIdx += Character.charCount(utf32);
intIdx++;
}
- scratch.length = intIdx;
- return scratch;
+ scratch.setLength(intIdx);
+ return scratch.get();
}
/** Decodes the Unicode codepoints from the provided
* char[] and places them in the provided scratch
* IntsRef, which must not be null, returning it. */
- public static IntsRef toUTF32(char[] s, int offset, int length, IntsRef scratch) {
+ public static IntsRef toUTF32(char[] s, int offset, int length, IntsRefBuilder scratch) {
int charIdx = offset;
int intIdx = 0;
final int charLimit = offset + length;
while(charIdx < charLimit) {
scratch.grow(intIdx+1);
final int utf32 = Character.codePointAt(s, charIdx, charLimit);
- scratch.ints[intIdx] = utf32;
+ scratch.setIntAt(intIdx, utf32);
charIdx += Character.charCount(utf32);
intIdx++;
}
- scratch.length = intIdx;
- return scratch;
+ scratch.setLength(intIdx);
+ return scratch.get();
}
/** Just takes unsigned byte values from the BytesRef and
* converts into an IntsRef. */
- public static IntsRef toIntsRef(BytesRef input, IntsRef scratch) {
- scratch.grow(input.length);
+ public static IntsRef toIntsRef(BytesRef input, IntsRefBuilder scratch) {
+ scratch.clear();
for(int i=0;i<input.length;i++) {
- scratch.ints[i] = input.bytes[i+input.offset] & 0xFF;
+ scratch.append(input.bytes[i+input.offset] & 0xFF);
}
- scratch.length = input.length;
- return scratch;
+ return scratch.get();
}
/** Just converts IntsRef to BytesRef; you must ensure the
* int values fit into a byte. */
- public static BytesRef toBytesRef(IntsRef input, BytesRef scratch) {
+ public static BytesRef toBytesRef(IntsRef input, BytesRefBuilder scratch) {
scratch.grow(input.length);
for(int i=0;i<input.length;i++) {
int value = input.ints[i+input.offset];
// NOTE: we allow -128 to 255
assert value >= Byte.MIN_VALUE && value <= 255: "value " + value + " doesn't fit into byte";
- scratch.bytes[i] = (byte) value;
+ scratch.setByteAt(i, (byte) value);
}
- scratch.length = input.length;
- return scratch;
+ scratch.setLength(input.length);
+ return scratch.get();
}
// Uncomment for debugging:
diff --git a/lucene/core/src/java/org/apache/lucene/util/mutable/MutableValueStr.java b/lucene/core/src/java/org/apache/lucene/util/mutable/MutableValueStr.java
index f6df35b7287..cace9881403 100644
--- a/lucene/core/src/java/org/apache/lucene/util/mutable/MutableValueStr.java
+++ b/lucene/core/src/java/org/apache/lucene/util/mutable/MutableValueStr.java
@@ -17,6 +17,7 @@
package org.apache.lucene.util.mutable;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
/**
* {@link MutableValue} implementation of type {@link String}.
@@ -25,12 +26,12 @@ import org.apache.lucene.util.BytesRef;
* have a <code>value</code> with a length set to 0.
*/
public class MutableValueStr extends MutableValue {
- public BytesRef value = new BytesRef();
+ public BytesRefBuilder value = new BytesRefBuilder();
@Override
public Object toObject() {
- assert exists || 0 == value.length;
- return exists ? value.utf8ToString() : null;
+ assert exists || 0 == value.length();
+ return exists ? value.get().utf8ToString() : null;
}
@Override
@@ -50,16 +51,16 @@ public class MutableValueStr extends MutableValue {
@Override
public boolean equalsSameType(Object other) {
- assert exists || 0 == value.length;
+ assert exists || 0 == value.length();
MutableValueStr b = (MutableValueStr)other;
- return value.equals(b.value) && exists == b.exists;
+ return value.get().equals(b.value.get()) && exists == b.exists;
}
@Override
public int compareSameType(Object other) {
- assert exists || 0 == value.length;
+ assert exists || 0 == value.length();
MutableValueStr b = (MutableValueStr)other;
- int c = value.compareTo(b.value);
+ int c = value.get().compareTo(b.value.get());
if (c != 0) return c;
if (exists == b.exists) return 0;
return exists ? 1 : -1;
@@ -68,7 +69,7 @@ public class MutableValueStr extends MutableValue {
@Override
public int hashCode() {
- assert exists || 0 == value.length;
- return value.hashCode();
+ assert exists || 0 == value.length();
+ return value.get().hashCode();
}
}
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestDocumentsWriterDeleteQueue.java b/lucene/core/src/test/org/apache/lucene/index/TestDocumentsWriterDeleteQueue.java
index dcc6119deee..1191bc0d6f4 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestDocumentsWriterDeleteQueue.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestDocumentsWriterDeleteQueue.java
@@ -26,6 +26,7 @@ import java.util.concurrent.locks.ReentrantLock;
import org.apache.lucene.index.DocumentsWriterDeleteQueue.DeleteSlice;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.LuceneTestCase;
import org.apache.lucene.util.ThreadInterruptedException;
@@ -73,10 +74,10 @@ public class TestDocumentsWriterDeleteQueue extends LuceneTestCase {
assertEquals(uniqueValues, bd1.terms.keySet());
assertEquals(uniqueValues, bd2.terms.keySet());
HashSet<Term> frozenSet = new HashSet<>();
+ BytesRefBuilder bytesRef = new BytesRefBuilder();
for (Term t : queue.freezeGlobalBuffer(null).termsIterable()) {
- BytesRef bytesRef = new BytesRef();
bytesRef.copyBytes(t.bytes);
- frozenSet.add(new Term(t.field, bytesRef));
+ frozenSet.add(new Term(t.field, bytesRef.toBytesRef()));
}
assertEquals(uniqueValues, frozenSet);
assertEquals("num deletes must be 0 after freeze", 0, queue
@@ -202,10 +203,10 @@ public class TestDocumentsWriterDeleteQueue extends LuceneTestCase {
}
queue.tryApplyGlobalSlice();
Set<Term> frozenSet = new HashSet<>();
+ BytesRefBuilder builder = new BytesRefBuilder();
for (Term t : queue.freezeGlobalBuffer(null).termsIterable()) {
- BytesRef bytesRef = new BytesRef();
- bytesRef.copyBytes(t.bytes);
- frozenSet.add(new Term(t.field, bytesRef));
+ builder.copyBytes(t.bytes);
+ frozenSet.add(new Term(t.field, builder.toBytesRef()));
}
assertEquals("num deletes must be 0 after freeze", 0, queue
.numGlobalTermDeletes());
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterUnicode.java b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterUnicode.java
index 8c881adaac4..28ba3b4ecdb 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterUnicode.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestIndexWriterUnicode.java
@@ -18,6 +18,7 @@ package org.apache.lucene.index;
*/
import java.io.IOException;
+import java.nio.CharBuffer;
import java.nio.charset.StandardCharsets;
import java.util.HashSet;
import java.util.Iterator;
@@ -29,7 +30,8 @@ import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.BytesRef;
-import org.apache.lucene.util.CharsRef;
+import org.apache.lucene.util.BytesRefBuilder;
+import org.apache.lucene.util.CharsRefBuilder;
import org.apache.lucene.util.LuceneTestCase;
import org.apache.lucene.util.UnicodeUtil;
@@ -136,7 +138,7 @@ public class TestIndexWriterUnicode extends LuceneTestCase {
private void checkTermsOrder(IndexReader r, Set<String> allTerms, boolean isTop) throws IOException {
TermsEnum terms = MultiFields.getFields(r).terms("f").iterator(null);
- BytesRef last = new BytesRef();
+ BytesRefBuilder last = new BytesRefBuilder();
Set<String> seenTerms = new HashSet<>();
@@ -146,7 +148,7 @@ public class TestIndexWriterUnicode extends LuceneTestCase {
break;
}
- assertTrue(last.compareTo(term) < 0);
+ assertTrue(last.get().compareTo(term) < 0);
last.copyBytes(term);
final String s = term.utf8ToString();
@@ -173,14 +175,13 @@ public class TestIndexWriterUnicode extends LuceneTestCase {
char[] buffer = new char[20];
char[] expected = new char[20];
- BytesRef utf8 = new BytesRef(20);
- CharsRef utf16 = new CharsRef(20);
+ CharsRefBuilder utf16 = new CharsRefBuilder();
int num = atLeast(100000);
for (int iter = 0; iter < num; iter++) {
boolean hasIllegal = fillUnicode(buffer, expected, 0, 20);
- UnicodeUtil.UTF16toUTF8(buffer, 0, 20, utf8);
+ BytesRef utf8 = new BytesRef(CharBuffer.wrap(buffer, 0, 20));
if (!hasIllegal) {
byte[] b = new String(buffer, 0, 20).getBytes(StandardCharsets.UTF_8);
assertEquals(b.length, utf8.length);
@@ -188,18 +189,17 @@ public class TestIndexWriterUnicode extends LuceneTestCase {
assertEquals(b[i], utf8.bytes[i]);
}
- UnicodeUtil.UTF8toUTF16(utf8.bytes, 0, utf8.length, utf16);
- assertEquals(utf16.length, 20);
+ utf16.copyUTF8Bytes(utf8.bytes, 0, utf8.length);
+ assertEquals(utf16.length(), 20);
for(int i=0;i<20;i++)
- assertEquals(expected[i], utf16.chars[i]);
+ assertEquals(expected[i], utf16.charAt(i));
}
}
// LUCENE-510
public void testAllUnicodeChars() throws Throwable {
- BytesRef utf8 = new BytesRef(10);
- CharsRef utf16 = new CharsRef(10);
+ CharsRefBuilder utf16 = new CharsRefBuilder();
char[] chars = new char[2];
for(int ch=0;ch<0x0010FFFF;ch++) {
@@ -215,14 +215,14 @@ public class TestIndexWriterUnicode extends LuceneTestCase {
chars[len++] = (char) (((ch-0x0010000) & 0x3FFL) + UnicodeUtil.UNI_SUR_LOW_START);
}
- UnicodeUtil.UTF16toUTF8(chars, 0, len, utf8);
+ BytesRef utf8 = new BytesRef(CharBuffer.wrap(chars, 0, len));
String s1 = new String(chars, 0, len);
String s2 = new String(utf8.bytes, 0, utf8.length, StandardCharsets.UTF_8);
assertEquals("codepoint " + ch, s1, s2);
- UnicodeUtil.UTF8toUTF16(utf8.bytes, 0, utf8.length, utf16);
- assertEquals("codepoint " + ch, s1, new String(utf16.chars, 0, utf16.length));
+ utf16.copyUTF8Bytes(utf8.bytes, 0, utf8.length);
+ assertEquals("codepoint " + ch, s1, utf16.toString());
byte[] b = s1.getBytes(StandardCharsets.UTF_8);
assertEquals(utf8.length, b.length);
diff --git a/lucene/core/src/test/org/apache/lucene/index/TestMultiDocValues.java b/lucene/core/src/test/org/apache/lucene/index/TestMultiDocValues.java
index 623ba15d892..c11eb9138ea 100644
--- a/lucene/core/src/test/org/apache/lucene/index/TestMultiDocValues.java
+++ b/lucene/core/src/test/org/apache/lucene/index/TestMultiDocValues.java
@@ -72,8 +72,7 @@ public class TestMultiDocValues extends LuceneTestCase {
public void testBinary() throws Exception {
Directory dir = newDirectory();
Document doc = new Document();
- BytesRef ref = new BytesRef();
- Field field = new BinaryDocValuesField("bytes", ref);
+ Field field = new BinaryDocValuesField("bytes", new BytesRef());
doc.add(field);
IndexWriterConfig iwc = newIndexWriterConfig(random(), null);
@@ -82,7 +81,8 @@ public class TestMultiDocValues extends LuceneTestCase {
int numDocs = atLeast(500);
for (int i = 0; i < numDocs; i++) {
- ref.copyChars(TestUtil.randomUnicodeString(random()));
+ BytesRef ref = new BytesRef(TestUtil.randomUnicodeString(random()));
+ field.setBytesValue(ref);
iw.addDocument(doc);
if (random().nextInt(17) == 0) {
iw.commit();
@@ -109,8 +109,7 @@ public class TestMultiDocValues extends LuceneTestCase {
public void testSorted() throws Exception {
Directory dir = newDirectory();
Document doc = new Document();
- BytesRef ref = new BytesRef();
- Field field = new SortedDocValuesField("bytes", ref);
+ Field field = new SortedDocValuesField("bytes", new BytesRef());
doc.add(field);
IndexWriterConfig iwc = newIndexWriterConfig(random(), null);
@@ -119,7 +118,8 @@ public class TestMultiDocValues extends LuceneTestCase {
int numDocs = atLeast(500);
for (int i = 0; i < numDocs; i++) {
- ref.copyChars(TestUtil.randomUnicodeString(random()));
+ BytesRef ref = new BytesRef(TestUtil.randomUnicodeString(random()));
+ field.setBytesValue(ref);
if (defaultCodecSupportsDocsWithField() && random().nextInt(7) == 0) {
iw.addDocument(new Document());
}
@@ -154,8 +154,7 @@ public class TestMultiDocValues extends LuceneTestCase {
public void testSortedWithLotsOfDups() throws Exception {
Directory dir = newDirectory();
Document doc = new Document();
- BytesRef ref = new BytesRef();
- Field field = new SortedDocValuesField("bytes", ref);
+ Field field = new SortedDocValuesField("bytes", new BytesRef());
doc.add(field);
IndexWriterConfig iwc = newIndexWriterConfig(random(), null);
@@ -164,7 +163,8 @@ public class TestMultiDocValues extends LuceneTestCase {
int numDocs = atLeast(500);
for (int i = 0; i < numDocs; i++) {
- ref.copyChars(TestUtil.randomSimpleString(random(), 2));
+ BytesRef ref = new BytesRef(TestUtil.randomSimpleString(random(), 2));
+ field.setBytesValue(ref);
iw.addDocument(doc);
if (random().nextInt(17) == 0) {
iw.commit();
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestFieldCacheRangeFilter.java b/lucene/core/src/test/org/apache/lucene/search/TestFieldCacheRangeFilter.java
index 0537a2cda81..667a6164be3 100644
--- a/lucene/core/src/test/org/apache/lucene/search/TestFieldCacheRangeFilter.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestFieldCacheRangeFilter.java
@@ -29,7 +29,7 @@ import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.Term;
import org.apache.lucene.store.Directory;
-import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.NumericUtils;
import org.junit.Test;
@@ -447,9 +447,9 @@ public class TestFieldCacheRangeFilter extends BaseTestRangeFilter {
}
writer.forceMerge(1);
- BytesRef term0 = new BytesRef();
+ BytesRefBuilder term0 = new BytesRefBuilder();
NumericUtils.intToPrefixCoded(0, 0, term0);
- writer.deleteDocuments(new Term("id_int", term0));
+ writer.deleteDocuments(new Term("id_int", term0.get()));
writer.close();
IndexReader reader = DirectoryReader.open(dir);
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestNumericRangeQuery32.java b/lucene/core/src/test/org/apache/lucene/search/TestNumericRangeQuery32.java
index 70a1f1b7e83..55ca52a3e54 100644
--- a/lucene/core/src/test/org/apache/lucene/search/TestNumericRangeQuery32.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestNumericRangeQuery32.java
@@ -34,6 +34,7 @@ import org.apache.lucene.index.Terms;
import org.apache.lucene.index.TermsEnum;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.LuceneTestCase;
import org.apache.lucene.util.NumericUtils;
import org.apache.lucene.util.TestNumericUtils; // NaN arrays
@@ -377,9 +378,12 @@ public class TestNumericRangeQuery32 extends LuceneTestCase {
if (lower>upper) {
int a=lower; lower=upper; upper=a;
}
- final BytesRef lowerBytes = new BytesRef(NumericUtils.BUF_SIZE_INT), upperBytes = new BytesRef(NumericUtils.BUF_SIZE_INT);
- NumericUtils.intToPrefixCodedBytes(lower, 0, lowerBytes);
- NumericUtils.intToPrefixCodedBytes(upper, 0, upperBytes);
+ final BytesRef lowerBytes, upperBytes;
+ BytesRefBuilder b = new BytesRefBuilder();
+ NumericUtils.intToPrefixCodedBytes(lower, 0, b);
+ lowerBytes = b.toBytesRef();
+ NumericUtils.intToPrefixCodedBytes(upper, 0, b);
+ upperBytes = b.toBytesRef();
// test inclusive range
NumericRangeQuery<Integer> tq=NumericRangeQuery.newIntRange(field, precisionStep, lower, upper, true, true);
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestNumericRangeQuery64.java b/lucene/core/src/test/org/apache/lucene/search/TestNumericRangeQuery64.java
index f8cf71cfcf6..c125afceea4 100644
--- a/lucene/core/src/test/org/apache/lucene/search/TestNumericRangeQuery64.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestNumericRangeQuery64.java
@@ -34,6 +34,7 @@ import org.apache.lucene.index.Terms;
import org.apache.lucene.index.TermsEnum;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.LuceneTestCase;
import org.apache.lucene.util.NumericUtils;
import org.apache.lucene.util.TestNumericUtils; // NaN arrays
@@ -404,9 +405,12 @@ public class TestNumericRangeQuery64 extends LuceneTestCase {
if (lower>upper) {
long a=lower; lower=upper; upper=a;
}
- final BytesRef lowerBytes = new BytesRef(NumericUtils.BUF_SIZE_LONG), upperBytes = new BytesRef(NumericUtils.BUF_SIZE_LONG);
- NumericUtils.longToPrefixCodedBytes(lower, 0, lowerBytes);
- NumericUtils.longToPrefixCodedBytes(upper, 0, upperBytes);
+ final BytesRef lowerBytes, upperBytes;
+ BytesRefBuilder b = new BytesRefBuilder();
+ NumericUtils.longToPrefixCodedBytes(lower, 0, b);
+ lowerBytes = b.toBytesRef();
+ NumericUtils.longToPrefixCodedBytes(upper, 0, b);
+ upperBytes = b.toBytesRef();
// test inclusive range
NumericRangeQuery<Long> tq=NumericRangeQuery.newLongRange(field, precisionStep, lower, upper, true, true);
diff --git a/lucene/core/src/test/org/apache/lucene/search/TestRegexpRandom2.java b/lucene/core/src/test/org/apache/lucene/search/TestRegexpRandom2.java
index 55ce34a5308..485b867e444 100644
--- a/lucene/core/src/test/org/apache/lucene/search/TestRegexpRandom2.java
+++ b/lucene/core/src/test/org/apache/lucene/search/TestRegexpRandom2.java
@@ -37,6 +37,7 @@ import org.apache.lucene.store.Directory;
import org.apache.lucene.util.AttributeSource;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.CharsRef;
+import org.apache.lucene.util.CharsRefBuilder;
import org.apache.lucene.util.LuceneTestCase;
import org.apache.lucene.util.TestUtil;
import org.apache.lucene.util.UnicodeUtil;
@@ -118,7 +119,7 @@ public class TestRegexpRandom2 extends LuceneTestCase {
private class SimpleAutomatonTermsEnum extends FilteredTermsEnum {
CharacterRunAutomaton runAutomaton = new CharacterRunAutomaton(automaton);
- CharsRef utf16 = new CharsRef(10);
+ CharsRefBuilder utf16 = new CharsRefBuilder();
private SimpleAutomatonTermsEnum(TermsEnum tenum) {
super(tenum);
@@ -127,8 +128,8 @@ public class TestRegexpRandom2 extends LuceneTestCase {
@Override
protected AcceptStatus accept(BytesRef term) throws IOException {
- UnicodeUtil.UTF8toUTF16(term.bytes, term.offset, term.length, utf16);
- return runAutomaton.run(utf16.chars, 0, utf16.length) ?
+ utf16.copyUTF8Bytes(term.bytes, term.offset, term.length);
+ return runAutomaton.run(utf16.chars(), 0, utf16.length()) ?
AcceptStatus.YES : AcceptStatus.NO;
}
}
diff --git a/lucene/core/src/test/org/apache/lucene/util/TestByteBlockPool.java b/lucene/core/src/test/org/apache/lucene/util/TestByteBlockPool.java
index 3b845bc66cc..d03f066147b 100644
--- a/lucene/core/src/test/org/apache/lucene/util/TestByteBlockPool.java
+++ b/lucene/core/src/test/org/apache/lucene/util/TestByteBlockPool.java
@@ -32,22 +32,22 @@ public class TestByteBlockPool extends LuceneTestCase {
List<BytesRef> list = new ArrayList<>();
int maxLength = atLeast(500);
final int numValues = atLeast(100);
- BytesRef ref = new BytesRef();
+ BytesRefBuilder ref = new BytesRefBuilder();
for (int i = 0; i < numValues; i++) {
final String value = TestUtil.randomRealisticUnicodeString(random(),
maxLength);
list.add(new BytesRef(value));
ref.copyChars(value);
- pool.append(ref);
+ pool.append(ref.get());
}
// verify
long position = 0;
for (BytesRef expected : list) {
ref.grow(expected.length);
- ref.length = expected.length;
- pool.readBytes(position, ref.bytes, ref.offset, ref.length);
- assertEquals(expected, ref);
- position += ref.length;
+ ref.setLength(expected.length);
+ pool.readBytes(position, ref.bytes(), 0, ref.length());
+ assertEquals(expected, ref.get());
+ position += ref.length();
}
pool.reset(random().nextBoolean(), reuseFirst);
if (reuseFirst) {
diff --git a/lucene/core/src/test/org/apache/lucene/util/TestBytesRef.java b/lucene/core/src/test/org/apache/lucene/util/TestBytesRef.java
index 5fe2d25643d..7ba9b0edfb7 100644
--- a/lucene/core/src/test/org/apache/lucene/util/TestBytesRef.java
+++ b/lucene/core/src/test/org/apache/lucene/util/TestBytesRef.java
@@ -48,20 +48,4 @@ public class TestBytesRef extends LuceneTestCase {
// only for 4.x
assertEquals("\uFFFF", new BytesRef("\uFFFF").utf8ToString());
}
-
- // LUCENE-3590, AIOOBE if you append to a bytesref with offset != 0
- public void testAppend() {
- byte bytes[] = new byte[] { (byte)'a', (byte)'b', (byte)'c', (byte)'d' };
- BytesRef b = new BytesRef(bytes, 1, 3); // bcd
- b.append(new BytesRef("e"));
- assertEquals("bcde", b.utf8ToString());
- }
-
- // LUCENE-3590, AIOOBE if you copy to a bytesref with offset != 0
- public void testCopyBytes() {
- byte bytes[] = new byte[] { (byte)'a', (byte)'b', (byte)'c', (byte)'d' };
- BytesRef b = new BytesRef(bytes, 1, 3); // bcd
- b.copyBytes(new BytesRef("bcde"));
- assertEquals("bcde", b.utf8ToString());
- }
}
diff --git a/lucene/core/src/test/org/apache/lucene/util/TestBytesRefArray.java b/lucene/core/src/test/org/apache/lucene/util/TestBytesRefArray.java
index fa691fb5d4c..84b3256a968 100644
--- a/lucene/core/src/test/org/apache/lucene/util/TestBytesRefArray.java
+++ b/lucene/core/src/test/org/apache/lucene/util/TestBytesRefArray.java
@@ -38,19 +38,19 @@ public class TestBytesRefArray extends LuceneTestCase {
stringList.clear();
}
int entries = atLeast(500);
- BytesRef spare = new BytesRef();
+ BytesRefBuilder spare = new BytesRefBuilder();
int initSize = list.size();
for (int i = 0; i < entries; i++) {
String randomRealisticUnicodeString = TestUtil
.randomRealisticUnicodeString(random);
spare.copyChars(randomRealisticUnicodeString);
- assertEquals(i+initSize, list.append(spare));
+ assertEquals(i+initSize, list.append(spare.get()));
stringList.add(randomRealisticUnicodeString);
}
for (int i = 0; i < entries; i++) {
assertNotNull(list.get(spare, i));
assertEquals("entry " + i + " doesn't match", stringList.get(i),
- spare.utf8ToString());
+ spare.get().utf8ToString());
}
// check random
@@ -58,7 +58,7 @@ public class TestBytesRefArray extends LuceneTestCase {
int e = random.nextInt(entries);
assertNotNull(list.get(spare, e));
assertEquals("entry " + i + " doesn't match", stringList.get(e),
- spare.utf8ToString());
+ spare.get().utf8ToString());
}
for (int i = 0; i < 2; i++) {
@@ -81,13 +81,13 @@ public class TestBytesRefArray extends LuceneTestCase {
stringList.clear();
}
int entries = atLeast(500);
- BytesRef spare = new BytesRef();
+ BytesRefBuilder spare = new BytesRefBuilder();
final int initSize = list.size();
for (int i = 0; i < entries; i++) {
String randomRealisticUnicodeString = TestUtil
.randomRealisticUnicodeString(random);
spare.copyChars(randomRealisticUnicodeString);
- assertEquals(initSize + i, list.append(spare));
+ assertEquals(initSize + i, list.append(spare.get()));
stringList.add(randomRealisticUnicodeString);
}
@@ -95,9 +95,10 @@ public class TestBytesRefArray extends LuceneTestCase {
BytesRefIterator iter = list.iterator(BytesRef
.getUTF8SortedAsUTF16Comparator());
int i = 0;
- while ((spare = iter.next()) != null) {
+ BytesRef next;
+ while ((next = iter.next()) != null) {
assertEquals("entry " + i + " doesn't match", stringList.get(i),
- spare.utf8ToString());
+ next.utf8ToString());
i++;
}
assertNull(iter.next());
diff --git a/lucene/core/src/test/org/apache/lucene/util/TestBytesRefHash.java b/lucene/core/src/test/org/apache/lucene/util/TestBytesRefHash.java
index 52fd56891f0..b1b3891e3bb 100644
--- a/lucene/core/src/test/org/apache/lucene/util/TestBytesRefHash.java
+++ b/lucene/core/src/test/org/apache/lucene/util/TestBytesRefHash.java
@@ -59,7 +59,7 @@ public class TestBytesRefHash extends LuceneTestCase {
*/
@Test
public void testSize() {
- BytesRef ref = new BytesRef();
+ BytesRefBuilder ref = new BytesRefBuilder();
int num = atLeast(2);
for (int j = 0; j < num; j++) {
final int mod = 1+random().nextInt(39);
@@ -70,7 +70,7 @@ public class TestBytesRefHash extends LuceneTestCase {
} while (str.length() == 0);
ref.copyChars(str);
int count = hash.size();
- int key = hash.add(ref);
+ int key = hash.add(ref.get());
if (key < 0)
assertEquals(hash.size(), count);
else
@@ -91,7 +91,7 @@ public class TestBytesRefHash extends LuceneTestCase {
*/
@Test
public void testGet() {
- BytesRef ref = new BytesRef();
+ BytesRefBuilder ref = new BytesRefBuilder();
BytesRef scratch = new BytesRef();
int num = atLeast(2);
for (int j = 0; j < num; j++) {
@@ -104,7 +104,7 @@ public class TestBytesRefHash extends LuceneTestCase {
} while (str.length() == 0);
ref.copyChars(str);
int count = hash.size();
- int key = hash.add(ref);
+ int key = hash.add(ref.get());
if (key >= 0) {
assertNull(strings.put(str, Integer.valueOf(key)));
assertEquals(uniqueCount, key);
@@ -117,7 +117,7 @@ public class TestBytesRefHash extends LuceneTestCase {
}
for (Entry<String, Integer> entry : strings.entrySet()) {
ref.copyChars(entry.getKey());
- assertEquals(ref, hash.get(entry.getValue().intValue(), scratch));
+ assertEquals(ref.get(), hash.get(entry.getValue().intValue(), scratch));
}
hash.clear();
assertEquals(0, hash.size());
@@ -130,7 +130,7 @@ public class TestBytesRefHash extends LuceneTestCase {
*/
@Test
public void testCompact() {
- BytesRef ref = new BytesRef();
+ BytesRefBuilder ref = new BytesRefBuilder();
int num = atLeast(2);
for (int j = 0; j < num; j++) {
int numEntries = 0;
@@ -142,7 +142,7 @@ public class TestBytesRefHash extends LuceneTestCase {
str = TestUtil.randomRealisticUnicodeString(random(), 1000);
} while (str.length() == 0);
ref.copyChars(str);
- final int key = hash.add(ref);
+ final int key = hash.add(ref.get());
if (key < 0) {
assertTrue(bits.get((-key)-1));
} else {
@@ -172,7 +172,7 @@ public class TestBytesRefHash extends LuceneTestCase {
*/
@Test
public void testSort() {
- BytesRef ref = new BytesRef();
+ BytesRefBuilder ref = new BytesRefBuilder();
int num = atLeast(2);
for (int j = 0; j < num; j++) {
SortedSet<String> strings = new TreeSet<>();
@@ -182,7 +182,7 @@ public class TestBytesRefHash extends LuceneTestCase {
str = TestUtil.randomRealisticUnicodeString(random(), 1000);
} while (str.length() == 0);
ref.copyChars(str);
- hash.add(ref);
+ hash.add(ref.get());
strings.add(str);
}
// We use the UTF-16 comparator here, because we need to be able to
@@ -193,7 +193,7 @@ public class TestBytesRefHash extends LuceneTestCase {
BytesRef scratch = new BytesRef();
for (String string : strings) {
ref.copyChars(string);
- assertEquals(ref, hash.get(sort[i++], scratch));
+ assertEquals(ref.get(), hash.get(sort[i++], scratch));
}
hash.clear();
assertEquals(0, hash.size());
@@ -209,7 +209,7 @@ public class TestBytesRefHash extends LuceneTestCase {
*/
@Test
public void testAdd() {
- BytesRef ref = new BytesRef();
+ BytesRefBuilder ref = new BytesRefBuilder();
BytesRef scratch = new BytesRef();
int num = atLeast(2);
for (int j = 0; j < num; j++) {
@@ -222,7 +222,7 @@ public class TestBytesRefHash extends LuceneTestCase {
} while (str.length() == 0);
ref.copyChars(str);
int count = hash.size();
- int key = hash.add(ref);
+ int key = hash.add(ref.get());
if (key >=0) {
assertTrue(strings.add(str));
@@ -246,7 +246,7 @@ public class TestBytesRefHash extends LuceneTestCase {
@Test
public void testFind() throws Exception {
- BytesRef ref = new BytesRef();
+ BytesRefBuilder ref = new BytesRefBuilder();
BytesRef scratch = new BytesRef();
int num = atLeast(2);
for (int j = 0; j < num; j++) {
@@ -259,14 +259,14 @@ public class TestBytesRefHash extends LuceneTestCase {
} while (str.length() == 0);
ref.copyChars(str);
int count = hash.size();
- int key = hash.find(ref); //hash.add(ref);
+ int key = hash.find(ref.get()); //hash.add(ref);
if (key >= 0) { // string found in hash
assertFalse(strings.add(str));
assertTrue(key < count);
assertEquals(str, hash.get(key, scratch).utf8ToString());
assertEquals(count, hash.size());
} else {
- key = hash.add(ref);
+ key = hash.add(ref.get());
assertTrue(strings.add(str));
assertEquals(uniqueCount, key);
assertEquals(hash.size(), count + 1);
@@ -308,7 +308,7 @@ public class TestBytesRefHash extends LuceneTestCase {
*/
@Test
public void testAddByPoolOffset() {
- BytesRef ref = new BytesRef();
+ BytesRefBuilder ref = new BytesRefBuilder();
BytesRef scratch = new BytesRef();
BytesRefHash offsetHash = newHash(pool);
int num = atLeast(2);
@@ -322,7 +322,7 @@ public class TestBytesRefHash extends LuceneTestCase {
} while (str.length() == 0);
ref.copyChars(str);
int count = hash.size();
- int key = hash.add(ref);
+ int key = hash.add(ref.get());
if (key >= 0) {
assertTrue(strings.add(str));
@@ -347,9 +347,9 @@ public class TestBytesRefHash extends LuceneTestCase {
assertAllIn(strings, hash);
for (String string : strings) {
ref.copyChars(string);
- int key = hash.add(ref);
+ int key = hash.add(ref.get());
BytesRef bytesRef = offsetHash.get((-key)-1, scratch);
- assertEquals(ref, bytesRef);
+ assertEquals(ref.get(), bytesRef);
}
hash.clear();
@@ -362,12 +362,12 @@ public class TestBytesRefHash extends LuceneTestCase {
}
private void assertAllIn(Set<String> strings, BytesRefHash hash) {
- BytesRef ref = new BytesRef();
+ BytesRefBuilder ref = new BytesRefBuilder();
BytesRef scratch = new BytesRef();
int count = hash.size();
for (String string : strings) {
ref.copyChars(string);
- int key = hash.add(ref); // add again to check duplicates
+ int key = hash.add(ref.get()); // add again to check duplicates
assertEquals(string, hash.get((-key)-1, scratch).utf8ToString());
assertEquals(count, hash.size());
assertTrue("key: " + key + " count: " + count + " string: " + string,
diff --git a/lucene/core/src/test/org/apache/lucene/util/TestCharsRef.java b/lucene/core/src/test/org/apache/lucene/util/TestCharsRef.java
index 3019109b912..2c9f29cee52 100644
--- a/lucene/core/src/test/org/apache/lucene/util/TestCharsRef.java
+++ b/lucene/core/src/test/org/apache/lucene/util/TestCharsRef.java
@@ -40,7 +40,7 @@ public class TestCharsRef extends LuceneTestCase {
}
public void testAppend() {
- CharsRef ref = new CharsRef();
+ CharsRefBuilder ref = new CharsRefBuilder();
StringBuilder builder = new StringBuilder();
int numStrings = atLeast(10);
for (int i = 0; i < numStrings; i++) {
@@ -51,13 +51,13 @@ public class TestCharsRef extends LuceneTestCase {
ref.append(charArray, offset, length);
}
- assertEquals(builder.toString(), ref.toString());
+ assertEquals(builder.toString(), ref.get().toString());
}
public void testCopy() {
int numIters = atLeast(10);
for (int i = 0; i < numIters; i++) {
- CharsRef ref = new CharsRef();
+ CharsRefBuilder ref = new CharsRefBuilder();
char[] charArray = TestUtil.randomRealisticUnicodeString(random(), 1, 100).toCharArray();
int offset = random().nextInt(charArray.length);
int length = charArray.length - offset;
@@ -68,32 +68,6 @@ public class TestCharsRef extends LuceneTestCase {
}
- // LUCENE-3590, AIOOBE if you append to a charsref with offset != 0
- public void testAppendChars() {
- char chars[] = new char[] { 'a', 'b', 'c', 'd' };
- CharsRef c = new CharsRef(chars, 1, 3); // bcd
- c.append(new char[] { 'e' }, 0, 1);
- assertEquals("bcde", c.toString());
- }
-
- // LUCENE-3590, AIOOBE if you copy to a charsref with offset != 0
- public void testCopyChars() {
- char chars[] = new char[] { 'a', 'b', 'c', 'd' };
- CharsRef c = new CharsRef(chars, 1, 3); // bcd
- char otherchars[] = new char[] { 'b', 'c', 'd', 'e' };
- c.copyChars(otherchars, 0, 4);
- assertEquals("bcde", c.toString());
- }
-
- // LUCENE-3590, AIOOBE if you copy to a charsref with offset != 0
- public void testCopyCharsRef() {
- char chars[] = new char[] { 'a', 'b', 'c', 'd' };
- CharsRef c = new CharsRef(chars, 1, 3); // bcd
- char otherchars[] = new char[] { 'b', 'c', 'd', 'e' };
- c.copyChars(new CharsRef(otherchars, 0, 4));
- assertEquals("bcde", c.toString());
- }
-
// LUCENE-3590: fix charsequence to fully obey interface
public void testCharSequenceCharAt() {
CharsRef c = new CharsRef("abc");
diff --git a/lucene/core/src/test/org/apache/lucene/util/TestNumericUtils.java b/lucene/core/src/test/org/apache/lucene/util/TestNumericUtils.java
index f726c1fe12b..1d49b16e1ef 100644
--- a/lucene/core/src/test/org/apache/lucene/util/TestNumericUtils.java
+++ b/lucene/core/src/test/org/apache/lucene/util/TestNumericUtils.java
@@ -26,37 +26,37 @@ public class TestNumericUtils extends LuceneTestCase {
public void testLongConversionAndOrdering() throws Exception {
// generate a series of encoded longs, each numerical one bigger than the one before
- BytesRef last=null, act=new BytesRef(NumericUtils.BUF_SIZE_LONG);
+ BytesRefBuilder last = new BytesRefBuilder();
+ BytesRefBuilder act = new BytesRefBuilder();
for (long l=-100000L; l<100000L; l++) {
NumericUtils.longToPrefixCodedBytes(l, 0, act);
if (last!=null) {
// test if smaller
- assertTrue("actual bigger than last (BytesRef)", last.compareTo(act) < 0 );
- assertTrue("actual bigger than last (as String)", last.utf8ToString().compareTo(act.utf8ToString()) < 0 );
+ assertTrue("actual bigger than last (BytesRef)", last.get().compareTo(act.get()) < 0 );
+ assertTrue("actual bigger than last (as String)", last.get().utf8ToString().compareTo(act.get().utf8ToString()) < 0 );
}
// test is back and forward conversion works
- assertEquals("forward and back conversion should generate same long", l, NumericUtils.prefixCodedToLong(act));
+ assertEquals("forward and back conversion should generate same long", l, NumericUtils.prefixCodedToLong(act.get()));
// next step
- last = act;
- act = new BytesRef(NumericUtils.BUF_SIZE_LONG);
+ last.copyBytes(act);
}
}
public void testIntConversionAndOrdering() throws Exception {
// generate a series of encoded ints, each numerical one bigger than the one before
- BytesRef last=null, act=new BytesRef(NumericUtils.BUF_SIZE_INT);
+ BytesRefBuilder act = new BytesRefBuilder();
+ BytesRefBuilder last = new BytesRefBuilder();
for (int i=-100000; i<100000; i++) {
NumericUtils.intToPrefixCodedBytes(i, 0, act);
if (last!=null) {
// test if smaller
- assertTrue("actual bigger than last (BytesRef)", last.compareTo(act) < 0 );
- assertTrue("actual bigger than last (as String)", last.utf8ToString().compareTo(act.utf8ToString()) < 0 );
+ assertTrue("actual bigger than last (BytesRef)", last.get().compareTo(act.get()) < 0 );
+ assertTrue("actual bigger than last (as String)", last.get().utf8ToString().compareTo(act.get().utf8ToString()) < 0 );
}
// test is back and forward conversion works
- assertEquals("forward and back conversion should generate same int", i, NumericUtils.prefixCodedToInt(act));
+ assertEquals("forward and back conversion should generate same int", i, NumericUtils.prefixCodedToInt(act.get()));
// next step
- last=act;
- act = new BytesRef(NumericUtils.BUF_SIZE_INT);
+ last.copyBytes(act.get());
}
}
@@ -65,18 +65,18 @@ public class TestNumericUtils extends LuceneTestCase {
Long.MIN_VALUE, Long.MIN_VALUE+1, Long.MIN_VALUE+2, -5003400000000L,
-4000L, -3000L, -2000L, -1000L, -1L, 0L, 1L, 10L, 300L, 50006789999999999L, Long.MAX_VALUE-2, Long.MAX_VALUE-1, Long.MAX_VALUE
};
- BytesRef[] prefixVals=new BytesRef[vals.length];
+ BytesRefBuilder[] prefixVals = new BytesRefBuilder[vals.length];
for (int i=0; i<vals.length; i++) {
- prefixVals[i] = new BytesRef(NumericUtils.BUF_SIZE_LONG);
+ prefixVals[i] = new BytesRefBuilder();
NumericUtils.longToPrefixCodedBytes(vals[i], 0, prefixVals[i]);
// check forward and back conversion
- assertEquals( "forward and back conversion should generate same long", vals[i], NumericUtils.prefixCodedToLong(prefixVals[i]) );
+ assertEquals( "forward and back conversion should generate same long", vals[i], NumericUtils.prefixCodedToLong(prefixVals[i].get()) );
// test if decoding values as int fails correctly
try {
- NumericUtils.prefixCodedToInt(prefixVals[i]);
+ NumericUtils.prefixCodedToInt(prefixVals[i].get());
fail("decoding a prefix coded long value as int should fail");
} catch (NumberFormatException e) {
// worked
@@ -85,15 +85,15 @@ public class TestNumericUtils extends LuceneTestCase {
// check sort order (prefixVals should be ascending)
for (int i=1; i<prefixVals.length; i++) {
- assertTrue( "check sort order", prefixVals[i-1].compareTo(prefixVals[i]) < 0 );
+ assertTrue( "check sort order", prefixVals[i-1].get().compareTo(prefixVals[i].get()) < 0 );
}
// check the prefix encoding, lower precision should have the difference to original value equal to the lower removed bits
- final BytesRef ref = new BytesRef(NumericUtils.BUF_SIZE_LONG);
+ final BytesRefBuilder ref = new BytesRefBuilder();
for (int i=0; i<vals.length; i++) {
for (int j=0; j<64; j++) {
NumericUtils.longToPrefixCodedBytes(vals[i], j, ref);
- long prefixVal=NumericUtils.prefixCodedToLong(ref);
+ long prefixVal=NumericUtils.prefixCodedToLong(ref.get());
long mask=(1L << j) - 1L;
assertEquals( "difference between prefix val and original value for "+vals[i]+" with shift="+j, vals[i] & mask, vals[i]-prefixVal );
}
@@ -105,18 +105,18 @@ public class TestNumericUtils extends LuceneTestCase {
Integer.MIN_VALUE, Integer.MIN_VALUE+1, Integer.MIN_VALUE+2, -64765767,
-4000, -3000, -2000, -1000, -1, 0, 1, 10, 300, 765878989, Integer.MAX_VALUE-2, Integer.MAX_VALUE-1, Integer.MAX_VALUE
};
- BytesRef[] prefixVals=new BytesRef[vals.length];
+ BytesRefBuilder[] prefixVals=new BytesRefBuilder[vals.length];
for (int i=0; i<vals.length; i++) {
- prefixVals[i] = new BytesRef(NumericUtils.BUF_SIZE_INT);
+ prefixVals[i] = new BytesRefBuilder();
NumericUtils.intToPrefixCodedBytes(vals[i], 0, prefixVals[i]);
// check forward and back conversion
- assertEquals( "forward and back conversion should generate same int", vals[i], NumericUtils.prefixCodedToInt(prefixVals[i]) );
+ assertEquals( "forward and back conversion should generate same int", vals[i], NumericUtils.prefixCodedToInt(prefixVals[i].get()) );
// test if decoding values as long fails correctly
try {
- NumericUtils.prefixCodedToLong(prefixVals[i]);
+ NumericUtils.prefixCodedToLong(prefixVals[i].get());
fail("decoding a prefix coded int value as long should fail");
} catch (NumberFormatException e) {
// worked
@@ -125,15 +125,15 @@ public class TestNumericUtils extends LuceneTestCase {
// check sort order (prefixVals should be ascending)
for (int i=1; i<prefixVals.length; i++) {
- assertTrue( "check sort order", prefixVals[i-1].compareTo(prefixVals[i]) < 0 );
+ assertTrue( "check sort order", prefixVals[i-1].get().compareTo(prefixVals[i].get()) < 0 );
}
// check the prefix encoding, lower precision should have the difference to original value equal to the lower removed bits
- final BytesRef ref = new BytesRef(NumericUtils.BUF_SIZE_LONG);
+ final BytesRefBuilder ref = new BytesRefBuilder();
for (int i=0; i<vals.length; i++) {
for (int j=0; j<32; j++) {
NumericUtils.intToPrefixCodedBytes(vals[i], j, ref);
- int prefixVal=NumericUtils.prefixCodedToInt(ref);
+ int prefixVal=NumericUtils.prefixCodedToInt(ref.get());
int mask=(1 << j) - 1;
assertEquals( "difference between prefix val and original value for "+vals[i]+" with shift="+j, vals[i] & mask, vals[i]-prefixVal );
}
diff --git a/lucene/core/src/test/org/apache/lucene/util/TestUnicodeUtil.java b/lucene/core/src/test/org/apache/lucene/util/TestUnicodeUtil.java
index 139c2e26d63..c6f5d8b6866 100644
--- a/lucene/core/src/test/org/apache/lucene/util/TestUnicodeUtil.java
+++ b/lucene/core/src/test/org/apache/lucene/util/TestUnicodeUtil.java
@@ -108,13 +108,13 @@ public class TestUnicodeUtil extends LuceneTestCase {
assertEquals(2, UnicodeUtil.codePointCount(new BytesRef(asByteArray('z', 0xf0, 0xa4, 0xad, 0xa2))));
// And do some random stuff.
- BytesRef utf8 = new BytesRef(20);
int num = atLeast(50000);
for (int i = 0; i < num; i++) {
final String s = TestUtil.randomUnicodeString(random());
- UnicodeUtil.UTF16toUTF8(s, 0, s.length(), utf8);
+ final byte[] utf8 = new byte[s.length() * UnicodeUtil.MAX_UTF8_BYTES_PER_CHAR];
+ final int utf8Len = UnicodeUtil.UTF16toUTF8(s, 0, s.length(), utf8);
assertEquals(s.codePointCount(0, s.length()),
- UnicodeUtil.codePointCount(utf8));
+ UnicodeUtil.codePointCount(new BytesRef(utf8, 0, utf8Len)));
}
}
@@ -137,14 +137,15 @@ public class TestUnicodeUtil extends LuceneTestCase {
}
public void testUTF8toUTF32() {
- BytesRef utf8 = new BytesRef(20);
- IntsRef utf32 = new IntsRef(20);
+ int[] utf32 = new int[0];
int[] codePoints = new int[20];
int num = atLeast(50000);
for (int i = 0; i < num; i++) {
final String s = TestUtil.randomUnicodeString(random());
- UnicodeUtil.UTF16toUTF8(s, 0, s.length(), utf8);
- UnicodeUtil.UTF8toUTF32(utf8, utf32);
+ final byte[] utf8 = new byte[s.length() * UnicodeUtil.MAX_UTF8_BYTES_PER_CHAR];
+ final int utf8Len = UnicodeUtil.UTF16toUTF8(s, 0, s.length(), utf8);
+ utf32 = ArrayUtil.grow(utf32, utf8Len);
+ final int utf32Len = UnicodeUtil.UTF8toUTF32(new BytesRef(utf8, 0, utf8Len), utf32);
int charUpto = 0;
int intUpto = 0;
@@ -153,15 +154,15 @@ public class TestUnicodeUtil extends LuceneTestCase {
codePoints[intUpto++] = cp;
charUpto += Character.charCount(cp);
}
- if (!ArrayUtil.equals(codePoints, 0, utf32.ints, utf32.offset, intUpto)) {
+ if (!ArrayUtil.equals(codePoints, 0, utf32, 0, intUpto)) {
System.out.println("FAILED");
for(int j=0;j<s.length();j++) {
System.out.println(" char[" + j + "]=" + Integer.toHexString(s.charAt(j)));
}
System.out.println();
- assertEquals(intUpto, utf32.length);
+ assertEquals(intUpto, utf32Len);
for(int j=0;j<intUpto;j++) {
- System.out.println(" " + Integer.toHexString(utf32.ints[j]) + " vs " + Integer.toHexString(codePoints[j]));
+ System.out.println(" " + Integer.toHexString(utf32[j]) + " vs " + Integer.toHexString(codePoints[j]));
}
fail("mismatch");
}
@@ -210,11 +211,8 @@ public class TestUnicodeUtil extends LuceneTestCase {
for (int i = 0; i < num; i++) {
String unicode = TestUtil.randomRealisticUnicodeString(random());
BytesRef ref = new BytesRef(unicode);
- char[] arr = new char[1 + random().nextInt(100)];
- int offset = random().nextInt(arr.length);
- int len = random().nextInt(arr.length - offset);
- CharsRef cRef = new CharsRef(arr, offset, len);
- UnicodeUtil.UTF8toUTF16(ref, cRef);
+ CharsRefBuilder cRef = new CharsRefBuilder();
+ cRef.copyUTF8Bytes(ref);
assertEquals(cRef.toString(), unicode);
}
}
diff --git a/lucene/core/src/test/org/apache/lucene/util/automaton/TestAutomaton.java b/lucene/core/src/test/org/apache/lucene/util/automaton/TestAutomaton.java
index 706e623b3ee..fd6fbcf72d4 100644
--- a/lucene/core/src/test/org/apache/lucene/util/automaton/TestAutomaton.java
+++ b/lucene/core/src/test/org/apache/lucene/util/automaton/TestAutomaton.java
@@ -27,7 +27,9 @@ import java.util.List;
import java.util.Set;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.IntsRef;
+import org.apache.lucene.util.IntsRefBuilder;
import org.apache.lucene.util.LuceneTestCase;
import org.apache.lucene.util.TestUtil;
import org.apache.lucene.util.UnicodeUtil;
@@ -481,7 +483,7 @@ public class TestAutomaton extends LuceneTestCase {
private void assertMatches(Automaton a, String... strings) {
Set<IntsRef> expected = new HashSet<>();
for(String s : strings) {
- IntsRef ints = new IntsRef();
+ IntsRefBuilder ints = new IntsRefBuilder();
expected.add(Util.toUTF32(s, ints));
}
@@ -679,10 +681,11 @@ public class TestAutomaton extends LuceneTestCase {
}
Set<BytesRef> newTerms = new HashSet<>();
BytesRef prefix = new BytesRef(getRandomString());
+ BytesRefBuilder newTerm = new BytesRefBuilder();
for(BytesRef term : terms) {
- BytesRef newTerm = BytesRef.deepCopyOf(prefix);
+ newTerm.copyBytes(prefix);
newTerm.append(term);
- newTerms.add(newTerm);
+ newTerms.add(newTerm.toBytesRef());
}
terms = newTerms;
boolean wasDeterministic1 = a.isDeterministic();
@@ -699,10 +702,11 @@ public class TestAutomaton extends LuceneTestCase {
System.out.println(" op=concat suffix " + suffix);
}
Set<BytesRef> newTerms = new HashSet<>();
+ BytesRefBuilder newTerm = new BytesRefBuilder();
for(BytesRef term : terms) {
- BytesRef newTerm = BytesRef.deepCopyOf(term);
+ newTerm.copyBytes(term);
newTerm.append(suffix);
- newTerms.add(newTerm);
+ newTerms.add(newTerm.toBytesRef());
}
terms = newTerms;
a = Operations.concatenate(a, Automata.makeString(suffix.utf8ToString()));
@@ -965,11 +969,12 @@ public class TestAutomaton extends LuceneTestCase {
System.out.println(" do suffix");
}
a = Operations.concatenate(a, randomNoOp(a2));
+ BytesRefBuilder newTerm = new BytesRefBuilder();
for(BytesRef term : terms) {
for(BytesRef suffix : addTerms) {
- BytesRef newTerm = BytesRef.deepCopyOf(term);
+ newTerm.copyBytes(term);
newTerm.append(suffix);
- newTerms.add(newTerm);
+ newTerms.add(newTerm.toBytesRef());
}
}
} else {
@@ -978,11 +983,12 @@ public class TestAutomaton extends LuceneTestCase {
System.out.println(" do prefix");
}
a = Operations.concatenate(randomNoOp(a2), a);
+ BytesRefBuilder newTerm = new BytesRefBuilder();
for(BytesRef term : terms) {
for(BytesRef prefix : addTerms) {
- BytesRef newTerm = BytesRef.deepCopyOf(prefix);
+ newTerm.copyBytes(prefix);
newTerm.append(term);
- newTerms.add(newTerm);
+ newTerms.add(newTerm.toBytesRef());
}
}
}
@@ -990,9 +996,11 @@ public class TestAutomaton extends LuceneTestCase {
terms = newTerms;
}
break;
+ default:
+ throw new AssertionError();
}
- // assertSame(terms, a);
+ assertSame(terms, a);
assertEquals(AutomatonTestUtil.isDeterministicSlow(a), a.isDeterministic());
}
@@ -1008,7 +1016,7 @@ public class TestAutomaton extends LuceneTestCase {
Automaton detA = Operations.determinize(a);
// Make sure all terms are accepted:
- IntsRef scratch = new IntsRef();
+ IntsRefBuilder scratch = new IntsRefBuilder();
for(BytesRef term : terms) {
Util.toIntsRef(term, scratch);
assertTrue("failed to accept term=" + term.utf8ToString(), Operations.run(detA, term.utf8ToString()));
@@ -1017,9 +1025,9 @@ public class TestAutomaton extends LuceneTestCase {
// Use getFiniteStrings:
Set<IntsRef> expected = new HashSet<>();
for(BytesRef term : terms) {
- IntsRef intsRef = new IntsRef();
+ IntsRefBuilder intsRef = new IntsRefBuilder();
Util.toUTF32(term.utf8ToString(), intsRef);
- expected.add(intsRef);
+ expected.add(intsRef.toIntsRef());
}
Set<IntsRef> actual = Operations.getFiniteStrings(a, -1);
@@ -1047,9 +1055,9 @@ public class TestAutomaton extends LuceneTestCase {
Set<IntsRef> expected2 = new HashSet<>();
for(BytesRef term : terms) {
- IntsRef intsRef = new IntsRef();
+ IntsRefBuilder intsRef = new IntsRefBuilder();
Util.toIntsRef(term, intsRef);
- expected2.add(intsRef);
+ expected2.add(intsRef.toIntsRef());
}
assertEquals(expected2, Operations.getFiniteStrings(utf8, -1));
} catch (AssertionError ae) {
diff --git a/lucene/core/src/test/org/apache/lucene/util/automaton/TestCompiledAutomaton.java b/lucene/core/src/test/org/apache/lucene/util/automaton/TestCompiledAutomaton.java
index 7370f3476ee..4d22ec26ada 100644
--- a/lucene/core/src/test/org/apache/lucene/util/automaton/TestCompiledAutomaton.java
+++ b/lucene/core/src/test/org/apache/lucene/util/automaton/TestCompiledAutomaton.java
@@ -25,6 +25,7 @@ import java.util.List;
import java.util.Set;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.LuceneTestCase;
import org.apache.lucene.util.TestUtil;
@@ -42,7 +43,7 @@ public class TestCompiledAutomaton extends LuceneTestCase {
private void testFloor(CompiledAutomaton c, String input, String expected) {
final BytesRef b = new BytesRef(input);
- final BytesRef result = c.floor(b, b);
+ final BytesRef result = c.floor(b, new BytesRefBuilder());
if (expected == null) {
assertNull(result);
} else {
diff --git a/lucene/core/src/test/org/apache/lucene/util/automaton/TestOperations.java b/lucene/core/src/test/org/apache/lucene/util/automaton/TestOperations.java
index 7b2db1f0080..d23cd09ed8a 100644
--- a/lucene/core/src/test/org/apache/lucene/util/automaton/TestOperations.java
+++ b/lucene/core/src/test/org/apache/lucene/util/automaton/TestOperations.java
@@ -21,6 +21,7 @@ import java.util.*;
import org.apache.lucene.util.*;
import org.apache.lucene.util.fst.Util;
+
import com.carrotsearch.randomizedtesting.generators.RandomInts;
public class TestOperations extends LuceneTestCase {
@@ -139,12 +140,12 @@ public class TestOperations extends LuceneTestCase {
a = MinimizationOperations.minimize(a);
Set<IntsRef> strings = getFiniteStrings(a, -1, true);
assertEquals(2, strings.size());
- IntsRef dog = new IntsRef();
+ IntsRefBuilder dog = new IntsRefBuilder();
Util.toIntsRef(new BytesRef("dog"), dog);
- assertTrue(strings.contains(dog));
- IntsRef duck = new IntsRef();
+ assertTrue(strings.contains(dog.get()));
+ IntsRefBuilder duck = new IntsRefBuilder();
Util.toIntsRef(new BytesRef("duck"), duck);
- assertTrue(strings.contains(duck));
+ assertTrue(strings.contains(duck.get()));
}
public void testFiniteStringsEatsStack() {
@@ -156,11 +157,11 @@ public class TestOperations extends LuceneTestCase {
Automaton a = Operations.union(Automata.makeString(bigString1), Automata.makeString(bigString2));
Set<IntsRef> strings = getFiniteStrings(a, -1, false);
assertEquals(2, strings.size());
- IntsRef scratch = new IntsRef();
+ IntsRefBuilder scratch = new IntsRefBuilder();
Util.toUTF32(bigString1.toCharArray(), 0, bigString1.length(), scratch);
- assertTrue(strings.contains(scratch));
+ assertTrue(strings.contains(scratch.get()));
Util.toUTF32(bigString2.toCharArray(), 0, bigString2.length(), scratch);
- assertTrue(strings.contains(scratch));
+ assertTrue(strings.contains(scratch.get()));
}
public void testRandomFiniteStrings1() {
@@ -172,12 +173,12 @@ public class TestOperations extends LuceneTestCase {
Set<IntsRef> strings = new HashSet<IntsRef>();
List<Automaton> automata = new ArrayList<>();
+ IntsRefBuilder scratch = new IntsRefBuilder();
for(int i=0;i<numStrings;i++) {
String s = TestUtil.randomSimpleString(random(), 1, 200);
automata.add(Automata.makeString(s));
- IntsRef scratch = new IntsRef();
Util.toUTF32(s.toCharArray(), 0, s.length(), scratch);
- strings.add(scratch);
+ strings.add(scratch.toIntsRef());
if (VERBOSE) {
System.out.println(" add string=" + s);
}
@@ -281,16 +282,16 @@ public class TestOperations extends LuceneTestCase {
public void testSingletonNoLimit() {
Set<IntsRef> result = Operations.getFiniteStrings(Automata.makeString("foobar"), -1);
assertEquals(1, result.size());
- IntsRef scratch = new IntsRef();
+ IntsRefBuilder scratch = new IntsRefBuilder();
Util.toUTF32("foobar".toCharArray(), 0, 6, scratch);
- assertTrue(result.contains(scratch));
+ assertTrue(result.contains(scratch.get()));
}
public void testSingletonLimit1() {
Set<IntsRef> result = Operations.getFiniteStrings(Automata.makeString("foobar"), 1);
assertEquals(1, result.size());
- IntsRef scratch = new IntsRef();
+ IntsRefBuilder scratch = new IntsRefBuilder();
Util.toUTF32("foobar".toCharArray(), 0, 6, scratch);
- assertTrue(result.contains(scratch));
+ assertTrue(result.contains(scratch.get()));
}
}
diff --git a/lucene/core/src/test/org/apache/lucene/util/automaton/TestUTF32ToUTF8.java b/lucene/core/src/test/org/apache/lucene/util/automaton/TestUTF32ToUTF8.java
index 95b19e04956..d1c35119d04 100644
--- a/lucene/core/src/test/org/apache/lucene/util/automaton/TestUTF32ToUTF8.java
+++ b/lucene/core/src/test/org/apache/lucene/util/automaton/TestUTF32ToUTF8.java
@@ -24,6 +24,7 @@ import java.util.Set;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.IntsRef;
+import org.apache.lucene.util.IntsRefBuilder;
import org.apache.lucene.util.LuceneTestCase;
import org.apache.lucene.util.TestUtil;
import org.apache.lucene.util.UnicodeUtil;
@@ -38,12 +39,11 @@ public class TestUTF32ToUTF8 extends LuceneTestCase {
private static final int MAX_UNICODE = 0x10FFFF;
- final BytesRef b = new BytesRef(4);
-
private boolean matches(ByteRunAutomaton a, int code) {
char[] chars = Character.toChars(code);
- UnicodeUtil.UTF16toUTF8(chars, 0, chars.length, b);
- return a.run(b.bytes, 0, b.length);
+ byte[] b = new byte[UnicodeUtil.MAX_UTF8_BYTES_PER_CHAR * chars.length];
+ final int len = UnicodeUtil.UTF16toUTF8(chars, 0, chars.length, b);
+ return a.run(b, 0, len);
}
private void testOne(Random r, ByteRunAutomaton a, int startCode, int endCode, int iters) {
@@ -214,10 +214,10 @@ public class TestUTF32ToUTF8 extends LuceneTestCase {
String s = TestUtil.randomRealisticUnicodeString(random());
Automaton a = Automata.makeString(s);
Automaton utf8 = new UTF32ToUTF8().convert(a);
- IntsRef ints = new IntsRef();
+ IntsRefBuilder ints = new IntsRefBuilder();
Util.toIntsRef(new BytesRef(s), ints);
Set<IntsRef> set = new HashSet<>();
- set.add(ints);
+ set.add(ints.get());
assertEquals(set, Operations.getFiniteStrings(utf8, -1));
}
}
diff --git a/lucene/core/src/test/org/apache/lucene/util/fst/TestFSTs.java b/lucene/core/src/test/org/apache/lucene/util/fst/TestFSTs.java
index fb8183ea259..219cf47496e 100644
--- a/lucene/core/src/test/org/apache/lucene/util/fst/TestFSTs.java
+++ b/lucene/core/src/test/org/apache/lucene/util/fst/TestFSTs.java
@@ -62,7 +62,9 @@ import org.apache.lucene.store.IndexInput;
import org.apache.lucene.store.IndexOutput;
import org.apache.lucene.store.MockDirectoryWrapper;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.IntsRef;
+import org.apache.lucene.util.IntsRefBuilder;
import org.apache.lucene.util.LineFileDocs;
import org.apache.lucene.util.LuceneTestCase.Slow;
import org.apache.lucene.util.LuceneTestCase.SuppressCodecs;
@@ -338,7 +340,7 @@ public class TestFSTs extends LuceneTestCase {
}
Terms terms = MultiFields.getTerms(r, "body");
if (terms != null) {
- final IntsRef scratchIntsRef = new IntsRef();
+ final IntsRefBuilder scratchIntsRef = new IntsRefBuilder();
final TermsEnum termsEnum = terms.iterator(null);
if (VERBOSE) {
System.out.println("TEST: got termsEnum=" + termsEnum);
@@ -477,7 +479,7 @@ public class TestFSTs extends LuceneTestCase {
public void run(int limit, boolean verify, boolean verifyByOutput) throws IOException {
BufferedReader is = new BufferedReader(new InputStreamReader(new FileInputStream(wordsFileIn), StandardCharsets.UTF_8), 65536);
try {
- final IntsRef intsRef = new IntsRef(10);
+ final IntsRefBuilder intsRef = new IntsRefBuilder();
long tStart = System.currentTimeMillis();
int ord = 0;
while(true) {
@@ -486,8 +488,8 @@ public class TestFSTs extends LuceneTestCase {
break;
}
toIntsRef(w, inputMode, intsRef);
- builder.add(intsRef,
- getOutput(intsRef, ord));
+ builder.add(intsRef.get(),
+ getOutput(intsRef.get(), ord));
ord++;
if (ord % 500000 == 0) {
@@ -556,8 +558,8 @@ public class TestFSTs extends LuceneTestCase {
}
toIntsRef(w, inputMode, intsRef);
if (iter == 0) {
- T expected = getOutput(intsRef, ord);
- T actual = Util.get(fst, intsRef);
+ T expected = getOutput(intsRef.get(), ord);
+ T actual = Util.get(fst, intsRef.get());
if (actual == null) {
throw new RuntimeException("unexpected null output on input=" + w);
}
@@ -566,7 +568,7 @@ public class TestFSTs extends LuceneTestCase {
}
} else {
// Get by output
- final Long output = (Long) getOutput(intsRef, ord);
+ final Long output = (Long) getOutput(intsRef.get(), ord);
@SuppressWarnings("unchecked") final IntsRef actual = Util.getByOutput((FST<Long>) fst, output.longValue());
if (actual == null) {
throw new RuntimeException("unexpected null input from output=" + output);
@@ -721,7 +723,7 @@ public class TestFSTs extends LuceneTestCase {
public void testSingleString() throws Exception {
final Outputs<Object> outputs = NoOutputs.getSingleton();
final Builder<Object> b = new Builder<>(FST.INPUT_TYPE.BYTE1, outputs);
- b.add(Util.toIntsRef(new BytesRef("foobar"), new IntsRef()), outputs.getNoOutput());
+ b.add(Util.toIntsRef(new BytesRef("foobar"), new IntsRefBuilder()), outputs.getNoOutput());
final BytesRefFSTEnum<Object> fstEnum = new BytesRefFSTEnum<>(b.finish());
assertNull(fstEnum.seekFloor(new BytesRef("foo")));
assertNull(fstEnum.seekCeil(new BytesRef("foobaz")));
@@ -732,7 +734,7 @@ public class TestFSTs extends LuceneTestCase {
String str = "foobar";
final Outputs<Object> outputs = NoOutputs.getSingleton();
final Builder<Object> b = new Builder<>(FST.INPUT_TYPE.BYTE1, outputs);
- IntsRef ints = new IntsRef();
+ IntsRefBuilder ints = new IntsRefBuilder();
for(int i=0; i<10; i++) {
b.add(Util.toIntsRef(new BytesRef(str), ints), outputs.getNoOutput());
}
@@ -806,9 +808,9 @@ public class TestFSTs extends LuceneTestCase {
final BytesRef b = new BytesRef("b");
final BytesRef c = new BytesRef("c");
- builder.add(Util.toIntsRef(a, new IntsRef()), 17L);
- builder.add(Util.toIntsRef(b, new IntsRef()), 42L);
- builder.add(Util.toIntsRef(c, new IntsRef()), 13824324872317238L);
+ builder.add(Util.toIntsRef(a, new IntsRefBuilder()), 17L);
+ builder.add(Util.toIntsRef(b, new IntsRefBuilder()), 42L);
+ builder.add(Util.toIntsRef(c, new IntsRefBuilder()), 13824324872317238L);
final FST<Long> fst = builder.finish();
@@ -833,12 +835,12 @@ public class TestFSTs extends LuceneTestCase {
assertEquals(b, seekResult.input);
assertEquals(42, (long) seekResult.output);
- assertEquals(Util.toIntsRef(new BytesRef("c"), new IntsRef()),
+ assertEquals(Util.toIntsRef(new BytesRef("c"), new IntsRefBuilder()),
Util.getByOutput(fst, 13824324872317238L));
assertNull(Util.getByOutput(fst, 47));
- assertEquals(Util.toIntsRef(new BytesRef("b"), new IntsRef()),
+ assertEquals(Util.toIntsRef(new BytesRef("b"), new IntsRefBuilder()),
Util.getByOutput(fst, 42));
- assertEquals(Util.toIntsRef(new BytesRef("a"), new IntsRef()),
+ assertEquals(Util.toIntsRef(new BytesRef("a"), new IntsRefBuilder()),
Util.getByOutput(fst, 17));
}
@@ -1041,15 +1043,15 @@ public class TestFSTs extends LuceneTestCase {
final Builder<Object> b = new Builder<>(FST.INPUT_TYPE.BYTE1, outputs);
int line = 0;
- final BytesRef term = new BytesRef();
- final IntsRef scratchIntsRef = new IntsRef();
+ final BytesRefBuilder term = new BytesRefBuilder();
+ final IntsRefBuilder scratchIntsRef = new IntsRefBuilder();
while (line < lines.length) {
String w = lines[line++];
if (w == null) {
break;
}
term.copyChars(w);
- b.add(Util.toIntsRef(term, scratchIntsRef), nothing);
+ b.add(Util.toIntsRef(term.get(), scratchIntsRef), nothing);
}
return b.finish();
@@ -1114,8 +1116,8 @@ public class TestFSTs extends LuceneTestCase {
final PositiveIntOutputs outputs = PositiveIntOutputs.getSingleton();
final Builder<Long> builder = new Builder<>(FST.INPUT_TYPE.BYTE4, 2, 0, true, true, Integer.MAX_VALUE, outputs, random().nextBoolean(), PackedInts.DEFAULT, true, 15);
- builder.add(Util.toUTF32("stat", new IntsRef()), 17L);
- builder.add(Util.toUTF32("station", new IntsRef()), 10L);
+ builder.add(Util.toUTF32("stat", new IntsRefBuilder()), 17L);
+ builder.add(Util.toUTF32("station", new IntsRefBuilder()), 10L);
final FST<Long> fst = builder.finish();
//Writer w = new OutputStreamWriter(new FileOutputStream("/x/tmp3/out.dot"));
StringWriter w = new StringWriter();
@@ -1129,8 +1131,8 @@ public class TestFSTs extends LuceneTestCase {
final PositiveIntOutputs outputs = PositiveIntOutputs.getSingleton();
final boolean willRewrite = random().nextBoolean();
final Builder<Long> builder = new Builder<>(FST.INPUT_TYPE.BYTE1, 0, 0, true, true, Integer.MAX_VALUE, outputs, willRewrite, PackedInts.DEFAULT, true, 15);
- builder.add(Util.toIntsRef(new BytesRef("stat"), new IntsRef()), outputs.getNoOutput());
- builder.add(Util.toIntsRef(new BytesRef("station"), new IntsRef()), outputs.getNoOutput());
+ builder.add(Util.toIntsRef(new BytesRef("stat"), new IntsRefBuilder()), outputs.getNoOutput());
+ builder.add(Util.toIntsRef(new BytesRef("station"), new IntsRefBuilder()), outputs.getNoOutput());
final FST<Long> fst = builder.finish();
StringWriter w = new StringWriter();
//Writer w = new OutputStreamWriter(new FileOutputStream("/x/tmp/out.dot"));
@@ -1230,7 +1232,7 @@ public class TestFSTs extends LuceneTestCase {
final PositiveIntOutputs outputs = PositiveIntOutputs.getSingleton();
final Builder<Long> builder = new Builder<>(FST.INPUT_TYPE.BYTE1, outputs);
- final IntsRef scratch = new IntsRef();
+ final IntsRefBuilder scratch = new IntsRefBuilder();
builder.add(Util.toIntsRef(new BytesRef("aab"), scratch), 22L);
builder.add(Util.toIntsRef(new BytesRef("aac"), scratch), 7L);
builder.add(Util.toIntsRef(new BytesRef("ax"), scratch), 17L);
@@ -1261,7 +1263,7 @@ public class TestFSTs extends LuceneTestCase {
final PositiveIntOutputs outputs = PositiveIntOutputs.getSingleton();
final Builder<Long> builder = new Builder<Long>(FST.INPUT_TYPE.BYTE1, outputs);
- final IntsRef scratch = new IntsRef();
+ final IntsRefBuilder scratch = new IntsRefBuilder();
builder.add(Util.toIntsRef(new BytesRef("aab"), scratch), 22L);
builder.add(Util.toIntsRef(new BytesRef("aac"), scratch), 7L);
builder.add(Util.toIntsRef(new BytesRef("adcd"), scratch), 17L);
@@ -1281,7 +1283,7 @@ public class TestFSTs extends LuceneTestCase {
}
};
- searcher.addStartPaths(fst.getFirstArc(new FST.Arc<Long>()), outputs.getNoOutput(), true, new IntsRef());
+ searcher.addStartPaths(fst.getFirstArc(new FST.Arc<Long>()), outputs.getNoOutput(), true, new IntsRefBuilder());
Util.TopResults<Long> res = searcher.search();
assertEquals(rejectCount.get(), 4);
assertTrue(res.isComplete); // rejected(4) + topN(2) <= maxQueueSize(6)
@@ -1301,7 +1303,7 @@ public class TestFSTs extends LuceneTestCase {
}
};
- searcher.addStartPaths(fst.getFirstArc(new FST.Arc<Long>()), outputs.getNoOutput(), true, new IntsRef());
+ searcher.addStartPaths(fst.getFirstArc(new FST.Arc<Long>()), outputs.getNoOutput(), true, new IntsRefBuilder());
res = searcher.search();
assertEquals(rejectCount.get(), 4);
assertFalse(res.isComplete); // rejected(4) + topN(2) > maxQueueSize(5)
@@ -1325,7 +1327,7 @@ public class TestFSTs extends LuceneTestCase {
final Builder<Pair<Long,Long>> builder = new Builder<>(FST.INPUT_TYPE.BYTE1, outputs);
- final IntsRef scratch = new IntsRef();
+ final IntsRefBuilder scratch = new IntsRefBuilder();
builder.add(Util.toIntsRef(new BytesRef("aab"), scratch), outputs.newPair(22L, 57L));
builder.add(Util.toIntsRef(new BytesRef("aac"), scratch), outputs.newPair(7L, 36L));
builder.add(Util.toIntsRef(new BytesRef("ax"), scratch), outputs.newPair(17L, 85L));
@@ -1365,7 +1367,7 @@ public class TestFSTs extends LuceneTestCase {
final PositiveIntOutputs outputs = PositiveIntOutputs.getSingleton();
final Builder<Long> builder = new Builder<>(FST.INPUT_TYPE.BYTE1, outputs);
- final IntsRef scratch = new IntsRef();
+ final IntsRefBuilder scratch = new IntsRefBuilder();
for (int i = 0; i < numWords; i++) {
String s;
@@ -1422,7 +1424,7 @@ public class TestFSTs extends LuceneTestCase {
for (Map.Entry<String,Long> e : slowCompletor.entrySet()) {
if (e.getKey().startsWith(prefix)) {
//System.out.println(" consider " + e.getKey());
- matches.add(new Result<>(Util.toIntsRef(new BytesRef(e.getKey().substring(prefix.length())), new IntsRef()),
+ matches.add(new Result<>(Util.toIntsRef(new BytesRef(e.getKey().substring(prefix.length())), new IntsRefBuilder()),
e.getValue() - prefixOutput));
}
}
@@ -1483,7 +1485,7 @@ public class TestFSTs extends LuceneTestCase {
PositiveIntOutputs.getSingleton() // output
);
final Builder<Pair<Long,Long>> builder = new Builder<>(FST.INPUT_TYPE.BYTE1, outputs);
- final IntsRef scratch = new IntsRef();
+ final IntsRefBuilder scratch = new IntsRefBuilder();
Random random = random();
for (int i = 0; i < numWords; i++) {
@@ -1543,7 +1545,7 @@ public class TestFSTs extends LuceneTestCase {
for (Map.Entry<String,TwoLongs> e : slowCompletor.entrySet()) {
if (e.getKey().startsWith(prefix)) {
//System.out.println(" consider " + e.getKey());
- matches.add(new Result<>(Util.toIntsRef(new BytesRef(e.getKey().substring(prefix.length())), new IntsRef()),
+ matches.add(new Result<>(Util.toIntsRef(new BytesRef(e.getKey().substring(prefix.length())), new IntsRefBuilder()),
outputs.newPair(e.getValue().a - prefixOutput.output1, e.getValue().b - prefixOutput.output2)));
}
}
@@ -1569,20 +1571,19 @@ public class TestFSTs extends LuceneTestCase {
final Builder<BytesRef> builder = new Builder<>(FST.INPUT_TYPE.BYTE1, outputs);
final byte[] bytes = new byte[300];
- final IntsRef input = new IntsRef();
- input.grow(1);
- input.length = 1;
+ final IntsRefBuilder input = new IntsRefBuilder();
+ input.append(0);
final BytesRef output = new BytesRef(bytes);
for(int arc=0;arc<6;arc++) {
- input.ints[0] = arc;
+ input.setIntAt(0, arc);
output.bytes[0] = (byte) arc;
- builder.add(input, BytesRef.deepCopyOf(output));
+ builder.add(input.get(), BytesRef.deepCopyOf(output));
}
final FST<BytesRef> fst = builder.finish();
for(int arc=0;arc<6;arc++) {
- input.ints[0] = arc;
- final BytesRef result = Util.get(fst, input);
+ input.setIntAt(0, arc);
+ final BytesRef result = Util.get(fst, input.get());
assertNotNull(result);
assertEquals(300, result.length);
assertEquals(result.bytes[result.offset], arc);
diff --git a/lucene/core/src/test/org/apache/lucene/util/mutable/TestMutableValues.java b/lucene/core/src/test/org/apache/lucene/util/mutable/TestMutableValues.java
index a9b57edbf20..e669b3249d5 100644
--- a/lucene/core/src/test/org/apache/lucene/util/mutable/TestMutableValues.java
+++ b/lucene/core/src/test/org/apache/lucene/util/mutable/TestMutableValues.java
@@ -26,7 +26,7 @@ public class TestMutableValues extends LuceneTestCase {
public void testStr() {
MutableValueStr xxx = new MutableValueStr();
- assert xxx.value.equals(new BytesRef()) : "defaults have changed, test utility may not longer be as high";
+ assert xxx.value.get().equals(new BytesRef()) : "defaults have changed, test utility may not longer be as high";
assert xxx.exists : "defaults have changed, test utility may not longer be as high";
assertSanity(xxx);
MutableValueStr yyy = new MutableValueStr();
@@ -42,14 +42,14 @@ public class TestMutableValues extends LuceneTestCase {
yyy.exists = false;
assertEquality(xxx, yyy);
- xxx.value.length = 0;
+ xxx.value.clear();
xxx.value.copyChars("zzz");
xxx.exists = true;
assertSanity(xxx);
assertInEquality(xxx,yyy);
- yyy.value.length = 0;
+ yyy.value.clear();
yyy.value.copyChars("aaa");
yyy.exists = true;
assertSanity(yyy);
@@ -65,11 +65,11 @@ public class TestMutableValues extends LuceneTestCase {
// special BytesRef considerations...
xxx.exists = false;
- xxx.value.length = 0; // but leave bytes alone
+ xxx.value.clear(); // but leave bytes alone
assertInEquality(xxx,yyy);
yyy.exists = false;
- yyy.value.length = 0; // but leave bytes alone
+ yyy.value.clear(); // but leave bytes alone
assertEquality(xxx, yyy);
}
diff --git a/lucene/facet/src/java/org/apache/lucene/facet/FacetsConfig.java b/lucene/facet/src/java/org/apache/lucene/facet/FacetsConfig.java
index f41156f49ca..345544bad5c 100644
--- a/lucene/facet/src/java/org/apache/lucene/facet/FacetsConfig.java
+++ b/lucene/facet/src/java/org/apache/lucene/facet/FacetsConfig.java
@@ -43,6 +43,7 @@ import org.apache.lucene.index.IndexableField;
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.IntsRef;
+import org.apache.lucene.util.IntsRefBuilder;
/** Records per-dimension configuration. By default a
* dimension is flat, single valued and does
@@ -308,7 +309,7 @@ public class FacetsConfig {
String indexFieldName = ent.getKey();
//System.out.println(" indexFieldName=" + indexFieldName + " fields=" + ent.getValue());
- IntsRef ordinals = new IntsRef(32);
+ IntsRefBuilder ordinals = new IntsRefBuilder();
for(FacetField facetField : ent.getValue()) {
FacetsConfig.DimConfig ft = getDimConfig(facetField.dim);
@@ -320,10 +321,7 @@ public class FacetsConfig {
checkTaxoWriter(taxoWriter);
int ordinal = taxoWriter.addCategory(cp);
- if (ordinals.length == ordinals.ints.length) {
- ordinals.grow(ordinals.length+1);
- }
- ordinals.ints[ordinals.length++] = ordinal;
+ ordinals.append(ordinal);
//System.out.println("ords[" + (ordinals.length-1) + "]=" + ordinal);
//System.out.println(" add cp=" + cp);
@@ -332,16 +330,13 @@ public class FacetsConfig {
// Add all parents too:
int parent = taxoWriter.getParent(ordinal);
while (parent > 0) {
- if (ordinals.ints.length == ordinals.length) {
- ordinals.grow(ordinals.length+1);
- }
- ordinals.ints[ordinals.length++] = parent;
+ ordinals.append(parent);
parent = taxoWriter.getParent(parent);
}
if (ft.requireDimCount == false) {
// Remove last (dimension) ord:
- ordinals.length--;
+ ordinals.setLength(ordinals.length() - 1);
}
}
@@ -353,7 +348,7 @@ public class FacetsConfig {
// Facet counts:
// DocValues are considered stored fields:
- doc.add(new BinaryDocValuesField(indexFieldName, dedupAndEncode(ordinals)));
+ doc.add(new BinaryDocValuesField(indexFieldName, dedupAndEncode(ordinals.get())));
}
}
diff --git a/lucene/grouping/src/java/org/apache/lucene/search/grouping/term/TermAllGroupHeadsCollector.java b/lucene/grouping/src/java/org/apache/lucene/search/grouping/term/TermAllGroupHeadsCollector.java
index 6d97160c0ae..1994aa59fe2 100644
--- a/lucene/grouping/src/java/org/apache/lucene/search/grouping/term/TermAllGroupHeadsCollector.java
+++ b/lucene/grouping/src/java/org/apache/lucene/search/grouping/term/TermAllGroupHeadsCollector.java
@@ -26,6 +26,7 @@ import org.apache.lucene.search.Sort;
import org.apache.lucene.search.SortField;
import org.apache.lucene.search.grouping.AbstractAllGroupHeadsCollector;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.SentinelIntSet;
import java.io.IOException;
@@ -303,7 +304,7 @@ public abstract class TermAllGroupHeadsCollector<GH extends AbstractAllGroupHead
if (collectedGroup.sortValues[i] == null) {
sortOrd = -1;
} else {
- sortOrd = sortsIndex[i].lookupTerm(collectedGroup.sortValues[i]);
+ sortOrd = sortsIndex[i].lookupTerm(collectedGroup.sortValues[i].get());
}
collectedGroup.sortOrds[i] = sortOrd;
}
@@ -313,13 +314,13 @@ public abstract class TermAllGroupHeadsCollector<GH extends AbstractAllGroupHead
class GroupHead extends AbstractAllGroupHeadsCollector.GroupHead<BytesRef> {
- BytesRef[] sortValues;
+ BytesRefBuilder[] sortValues;
int[] sortOrds;
float[] scores;
private GroupHead(int doc, BytesRef groupValue) throws IOException {
super(groupValue, doc + readerContext.docBase);
- sortValues = new BytesRef[sortsIndex.length];
+ sortValues = new BytesRefBuilder[sortsIndex.length];
sortOrds = new int[sortsIndex.length];
scores = new float[sortsIndex.length];
for (int i = 0; i < sortsIndex.length; i++) {
@@ -327,7 +328,7 @@ public abstract class TermAllGroupHeadsCollector<GH extends AbstractAllGroupHead
scores[i] = scorer.score();
} else {
sortOrds[i] = sortsIndex[i].getOrd(doc);
- sortValues[i] = new BytesRef();
+ sortValues[i] = new BytesRefBuilder();
if (sortOrds[i] != -1) {
sortValues[i].copyBytes(sortsIndex[i].get(doc));
}
@@ -349,7 +350,7 @@ public abstract class TermAllGroupHeadsCollector<GH extends AbstractAllGroupHead
if (sortOrds[compIDX] < 0) {
// The current segment doesn't contain the sort value we encountered before. Therefore the ord is negative.
final BytesRef term = sortsIndex[compIDX].get(doc);
- return sortValues[compIDX].compareTo(term);
+ return sortValues[compIDX].get().compareTo(term);
} else {
return sortOrds[compIDX] - sortsIndex[compIDX].getOrd(doc);
}
@@ -455,7 +456,7 @@ public abstract class TermAllGroupHeadsCollector<GH extends AbstractAllGroupHead
if (collectedGroup.sortOrds[i] == -1) {
sortOrd = -1;
} else {
- sortOrd = sortsIndex[i].lookupTerm(collectedGroup.sortValues[i]);
+ sortOrd = sortsIndex[i].lookupTerm(collectedGroup.sortValues[i].get());
}
collectedGroup.sortOrds[i] = sortOrd;
}
@@ -465,16 +466,16 @@ public abstract class TermAllGroupHeadsCollector<GH extends AbstractAllGroupHead
class GroupHead extends AbstractAllGroupHeadsCollector.GroupHead<BytesRef> {
- BytesRef[] sortValues;
+ BytesRefBuilder[] sortValues;
int[] sortOrds;
private GroupHead(int doc, BytesRef groupValue) {
super(groupValue, doc + readerContext.docBase);
- sortValues = new BytesRef[sortsIndex.length];
+ sortValues = new BytesRefBuilder[sortsIndex.length];
sortOrds = new int[sortsIndex.length];
for (int i = 0; i < sortsIndex.length; i++) {
sortOrds[i] = sortsIndex[i].getOrd(doc);
- sortValues[i] = new BytesRef();
+ sortValues[i] = new BytesRefBuilder();
sortValues[i].copyBytes(sortsIndex[i].get(doc));
}
}
@@ -484,7 +485,7 @@ public abstract class TermAllGroupHeadsCollector<GH extends AbstractAllGroupHead
if (sortOrds[compIDX] < 0) {
// The current segment doesn't contain the sort value we encountered before. Therefore the ord is negative.
final BytesRef term = sortsIndex[compIDX].get(doc);
- return sortValues[compIDX].compareTo(term);
+ return sortValues[compIDX].get().compareTo(term);
} else {
return sortOrds[compIDX] - sortsIndex[compIDX].getOrd(doc);
}
diff --git a/lucene/grouping/src/java/org/apache/lucene/search/grouping/term/TermFirstPassGroupingCollector.java b/lucene/grouping/src/java/org/apache/lucene/search/grouping/term/TermFirstPassGroupingCollector.java
index 8e7217c5a52..b394fb95946 100644
--- a/lucene/grouping/src/java/org/apache/lucene/search/grouping/term/TermFirstPassGroupingCollector.java
+++ b/lucene/grouping/src/java/org/apache/lucene/search/grouping/term/TermFirstPassGroupingCollector.java
@@ -24,6 +24,7 @@ import org.apache.lucene.index.DocValues;
import org.apache.lucene.index.SortedDocValues;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.grouping.AbstractFirstPassGroupingCollector;
+import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.BytesRef;
/**
@@ -75,7 +76,10 @@ public class TermFirstPassGroupingCollector extends AbstractFirstPassGroupingCol
if (groupValue == null) {
return null;
} else if (reuse != null) {
- reuse.copyBytes(groupValue);
+ reuse.bytes = ArrayUtil.grow(reuse.bytes, groupValue.length);
+ reuse.offset = 0;
+ reuse.length = groupValue.length;
+ System.arraycopy(groupValue.bytes, groupValue.offset, reuse.bytes, 0, groupValue.length);
return reuse;
} else {
return BytesRef.deepCopyOf(groupValue);
diff --git a/lucene/grouping/src/java/org/apache/lucene/search/grouping/term/TermGroupFacetCollector.java b/lucene/grouping/src/java/org/apache/lucene/search/grouping/term/TermGroupFacetCollector.java
index c5dedc87faa..97c96bc5302 100644
--- a/lucene/grouping/src/java/org/apache/lucene/search/grouping/term/TermGroupFacetCollector.java
+++ b/lucene/grouping/src/java/org/apache/lucene/search/grouping/term/TermGroupFacetCollector.java
@@ -22,9 +22,9 @@ import org.apache.lucene.index.DocValues;
import org.apache.lucene.index.SortedDocValues;
import org.apache.lucene.index.SortedSetDocValues;
import org.apache.lucene.index.TermsEnum;
-import org.apache.lucene.search.LeafCollector;
import org.apache.lucene.search.grouping.AbstractGroupFacetCollector;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.SentinelIntSet;
import org.apache.lucene.util.UnicodeUtil;
@@ -155,9 +155,10 @@ public abstract class TermGroupFacetCollector extends AbstractGroupFacetCollecto
// Points to the ord one higher than facetPrefix
startFacetOrd = -startFacetOrd - 1;
}
- BytesRef facetEndPrefix = BytesRef.deepCopyOf(facetPrefix);
+ BytesRefBuilder facetEndPrefix = new BytesRefBuilder();
+ facetEndPrefix.append(facetPrefix);
facetEndPrefix.append(UnicodeUtil.BIG_TERM);
- endFacetOrd = facetFieldTermsIndex.lookupTerm(facetEndPrefix);
+ endFacetOrd = facetFieldTermsIndex.lookupTerm(facetEndPrefix.get());
assert endFacetOrd < 0;
endFacetOrd = -endFacetOrd - 1; // Points to the ord one higher than facetEndPrefix
} else {
@@ -199,7 +200,6 @@ public abstract class TermGroupFacetCollector extends AbstractGroupFacetCollecto
private SortedSetDocValues facetFieldDocTermOrds;
private TermsEnum facetOrdTermsEnum;
private int facetFieldNumTerms;
- private final BytesRef scratch = new BytesRef();
MV(String groupField, String facetField, BytesRef facetPrefix, int initialSize) {
super(groupField, facetField, facetPrefix, initialSize);
@@ -328,9 +328,10 @@ public abstract class TermGroupFacetCollector extends AbstractGroupFacetCollecto
return;
}
- BytesRef facetEndPrefix = BytesRef.deepCopyOf(facetPrefix);
+ BytesRefBuilder facetEndPrefix = new BytesRefBuilder();
+ facetEndPrefix.append(facetPrefix);
facetEndPrefix.append(UnicodeUtil.BIG_TERM);
- seekStatus = facetOrdTermsEnum.seekCeil(facetEndPrefix);
+ seekStatus = facetOrdTermsEnum.seekCeil(facetEndPrefix.get());
if (seekStatus != TermsEnum.SeekStatus.END) {
endFacetOrd = (int) facetOrdTermsEnum.ord();
} else {
diff --git a/lucene/grouping/src/java/org/apache/lucene/search/grouping/term/TermSecondPassGroupingCollector.java b/lucene/grouping/src/java/org/apache/lucene/search/grouping/term/TermSecondPassGroupingCollector.java
index c9203477df3..043bd5f285d 100644
--- a/lucene/grouping/src/java/org/apache/lucene/search/grouping/term/TermSecondPassGroupingCollector.java
+++ b/lucene/grouping/src/java/org/apache/lucene/search/grouping/term/TermSecondPassGroupingCollector.java
@@ -23,7 +23,6 @@ import java.util.Collection;
import org.apache.lucene.index.AtomicReaderContext;
import org.apache.lucene.index.DocValues;
import org.apache.lucene.index.SortedDocValues;
-import org.apache.lucene.search.LeafCollector;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.grouping.AbstractSecondPassGroupingCollector;
import org.apache.lucene.search.grouping.SearchGroup;
@@ -43,7 +42,7 @@ public class TermSecondPassGroupingCollector extends AbstractSecondPassGroupingC
private SortedDocValues index;
private final String groupField;
- @SuppressWarnings({"unchecked", "rawtypes"})
+ @SuppressWarnings({"unchecked"})
public TermSecondPassGroupingCollector(String groupField, Collection<SearchGroup<BytesRef>> groups, Sort groupSort, Sort withinGroupSort,
int maxDocsPerGroup, boolean getScores, boolean getMaxScores, boolean fillSortFields)
throws IOException {
diff --git a/lucene/grouping/src/test/org/apache/lucene/search/grouping/DistinctValuesCollectorTest.java b/lucene/grouping/src/test/org/apache/lucene/search/grouping/DistinctValuesCollectorTest.java
index adea0dd9953..1579751edb9 100644
--- a/lucene/grouping/src/test/org/apache/lucene/search/grouping/DistinctValuesCollectorTest.java
+++ b/lucene/grouping/src/test/org/apache/lucene/search/grouping/DistinctValuesCollectorTest.java
@@ -323,7 +323,7 @@ public class DistinctValuesCollectorTest extends AbstractGroupingTestCase {
assertEquals(Long.parseLong(expected), groupValue);
} else if (MutableValue.class.isAssignableFrom(groupValue.getClass())) {
MutableValueStr mutableValue = new MutableValueStr();
- mutableValue.value = new BytesRef(expected);
+ mutableValue.value.copyChars(expected);
assertEquals(mutableValue, groupValue);
} else {
fail();
diff --git a/lucene/grouping/src/test/org/apache/lucene/search/grouping/GroupingSearchTest.java b/lucene/grouping/src/test/org/apache/lucene/search/grouping/GroupingSearchTest.java
index 4283490cc09..d289c80315b 100644
--- a/lucene/grouping/src/test/org/apache/lucene/search/grouping/GroupingSearchTest.java
+++ b/lucene/grouping/src/test/org/apache/lucene/search/grouping/GroupingSearchTest.java
@@ -195,7 +195,7 @@ public class GroupingSearchTest extends LuceneTestCase {
assertEquals(new BytesRef(expected), group.groupValue);
} else if (group.groupValue.getClass().isAssignableFrom(MutableValueStr.class)) {
MutableValueStr v = new MutableValueStr();
- v.value = new BytesRef(expected);
+ v.value.copyChars(expected);
assertEquals(v, group.groupValue);
} else {
fail();
diff --git a/lucene/grouping/src/test/org/apache/lucene/search/grouping/TestGrouping.java b/lucene/grouping/src/test/org/apache/lucene/search/grouping/TestGrouping.java
index 77fc360d597..06691f7b47a 100644
--- a/lucene/grouping/src/test/org/apache/lucene/search/grouping/TestGrouping.java
+++ b/lucene/grouping/src/test/org/apache/lucene/search/grouping/TestGrouping.java
@@ -238,9 +238,8 @@ public class TestGrouping extends LuceneTestCase {
SearchGroup<MutableValue> sg = new SearchGroup<>();
MutableValueStr groupValue = new MutableValueStr();
if (mergedTopGroup.groupValue != null) {
- groupValue.value = mergedTopGroup.groupValue;
+ groupValue.value.copyBytes(mergedTopGroup.groupValue);
} else {
- groupValue.value = new BytesRef();
groupValue.exists = false;
}
sg.groupValue = groupValue;
@@ -278,7 +277,7 @@ public class TestGrouping extends LuceneTestCase {
assertEquals(new BytesRef(expected), group.groupValue);
} else if (group.groupValue.getClass().isAssignableFrom(MutableValueStr.class)) {
MutableValueStr v = new MutableValueStr();
- v.value = new BytesRef(expected);
+ v.value.copyChars(expected);
assertEquals(v, group.groupValue);
} else {
fail();
@@ -297,7 +296,7 @@ public class TestGrouping extends LuceneTestCase {
List<SearchGroup<BytesRef>> groups = new ArrayList<>(mutableValueGroups.size());
for (SearchGroup<MutableValue> mutableValueGroup : mutableValueGroups) {
SearchGroup<BytesRef> sg = new SearchGroup<>();
- sg.groupValue = mutableValueGroup.groupValue.exists() ? ((MutableValueStr) mutableValueGroup.groupValue).value : null;
+ sg.groupValue = mutableValueGroup.groupValue.exists() ? ((MutableValueStr) mutableValueGroup.groupValue).value.get() : null;
sg.sortValues = mutableValueGroup.sortValues;
groups.add(sg);
}
@@ -315,7 +314,7 @@ public class TestGrouping extends LuceneTestCase {
TopGroups<MutableValue> mvalTopGroups = ((FunctionSecondPassGroupingCollector) c).getTopGroups(withinGroupOffset);
List<GroupDocs<BytesRef>> groups = new ArrayList<>(mvalTopGroups.groups.length);
for (GroupDocs<MutableValue> mvalGd : mvalTopGroups.groups) {
- BytesRef groupValue = mvalGd.groupValue.exists() ? ((MutableValueStr) mvalGd.groupValue).value : null;
+ BytesRef groupValue = mvalGd.groupValue.exists() ? ((MutableValueStr) mvalGd.groupValue).value.get() : null;
groups.add(new GroupDocs<>(Float.NaN, mvalGd.maxScore, mvalGd.totalHits, mvalGd.scoreDocs, groupValue, mvalGd.groupSortValues));
}
return new TopGroups<>(mvalTopGroups.groupSort, mvalTopGroups.withinGroupSort, mvalTopGroups.totalHitCount, mvalTopGroups.totalGroupedHitCount, groups.toArray(new GroupDocs[groups.size()]), Float.NaN);
diff --git a/lucene/highlighter/src/java/org/apache/lucene/search/vectorhighlight/FieldTermStack.java b/lucene/highlighter/src/java/org/apache/lucene/search/vectorhighlight/FieldTermStack.java
index 04a1336968a..18774fea2d1 100644
--- a/lucene/highlighter/src/java/org/apache/lucene/search/vectorhighlight/FieldTermStack.java
+++ b/lucene/highlighter/src/java/org/apache/lucene/search/vectorhighlight/FieldTermStack.java
@@ -29,8 +29,7 @@ import org.apache.lucene.index.Term;
import org.apache.lucene.index.Terms;
import org.apache.lucene.index.TermsEnum;
import org.apache.lucene.util.BytesRef;
-import org.apache.lucene.util.CharsRef;
-import org.apache.lucene.util.UnicodeUtil;
+import org.apache.lucene.util.CharsRefBuilder;
/**
* <code>FieldTermStack</code> is a stack that keeps query terms in the specified field
@@ -92,7 +91,7 @@ public class FieldTermStack {
return;
}
- final CharsRef spare = new CharsRef();
+ final CharsRefBuilder spare = new CharsRefBuilder();
final TermsEnum termsEnum = vector.iterator(null);
DocsAndPositionsEnum dpEnum = null;
BytesRef text;
@@ -100,7 +99,7 @@ public class FieldTermStack {
int numDocs = reader.maxDoc();
while ((text = termsEnum.next()) != null) {
- UnicodeUtil.UTF8toUTF16(text, spare);
+ spare.copyUTF8Bytes(text);
final String term = spare.toString();
if (!termSet.contains(term)) {
continue;
diff --git a/lucene/join/src/test/org/apache/lucene/search/join/TestBlockJoin.java b/lucene/join/src/test/org/apache/lucene/search/join/TestBlockJoin.java
index 68d68565576..2bd6e28b50e 100644
--- a/lucene/join/src/test/org/apache/lucene/search/join/TestBlockJoin.java
+++ b/lucene/join/src/test/org/apache/lucene/search/join/TestBlockJoin.java
@@ -603,14 +603,14 @@ public class TestBlockJoin extends LuceneTestCase {
}
}
+ BytesRefBuilder term = new BytesRefBuilder();
for(int deleteID : toDelete) {
if (VERBOSE) {
System.out.println("DELETE parentID=" + deleteID);
}
- BytesRef term = new BytesRef();
NumericUtils.intToPrefixCodedBytes(deleteID, 0, term);
- w.deleteDocuments(new Term("blockID", term));
- joinW.deleteDocuments(new Term("blockID", term));
+ w.deleteDocuments(new Term("blockID", term.toBytesRef()));
+ joinW.deleteDocuments(new Term("blockID", term.toBytesRef()));
}
final IndexReader r = w.getReader();
diff --git a/lucene/misc/src/test/org/apache/lucene/util/fst/TestFSTsMisc.java b/lucene/misc/src/test/org/apache/lucene/util/fst/TestFSTsMisc.java
index c0341a9a534..970d2ed19dd 100644
--- a/lucene/misc/src/test/org/apache/lucene/util/fst/TestFSTsMisc.java
+++ b/lucene/misc/src/test/org/apache/lucene/util/fst/TestFSTsMisc.java
@@ -28,6 +28,7 @@ import java.util.Set;
import org.apache.lucene.store.MockDirectoryWrapper;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.IntsRef;
+import org.apache.lucene.util.IntsRefBuilder;
import org.apache.lucene.util.LuceneTestCase;
import org.apache.lucene.util.TestUtil;
import org.apache.lucene.util.TestUtil;
@@ -168,7 +169,7 @@ public class TestFSTsMisc extends LuceneTestCase {
ListOfOutputs<Long> outputs = new ListOfOutputs<>(_outputs);
final Builder<Object> builder = new Builder<>(FST.INPUT_TYPE.BYTE1, outputs);
- final IntsRef scratch = new IntsRef();
+ final IntsRefBuilder scratch = new IntsRefBuilder();
// Add the same input more than once and the outputs
// are merged:
builder.add(Util.toIntsRef(new BytesRef("a"), scratch), 1L);
@@ -197,11 +198,11 @@ public class TestFSTsMisc extends LuceneTestCase {
ListOfOutputs<Long> outputs = new ListOfOutputs<>(_outputs);
final Builder<Object> builder = new Builder<>(FST.INPUT_TYPE.BYTE1, outputs);
- final IntsRef scratch = new IntsRef();
- builder.add(scratch, 0L);
- builder.add(scratch, 1L);
- builder.add(scratch, 17L);
- builder.add(scratch, 1L);
+ final IntsRefBuilder scratch = new IntsRefBuilder();
+ builder.add(scratch.get(), 0L);
+ builder.add(scratch.get(), 1L);
+ builder.add(scratch.get(), 17L);
+ builder.add(scratch.get(), 1L);
builder.add(Util.toIntsRef(new BytesRef("a"), scratch), 1L);
builder.add(Util.toIntsRef(new BytesRef("a"), scratch), 3L);
diff --git a/lucene/queries/src/java/org/apache/lucene/queries/function/FunctionValues.java b/lucene/queries/src/java/org/apache/lucene/queries/function/FunctionValues.java
index 9b529fd01f0..85054c47e79 100644
--- a/lucene/queries/src/java/org/apache/lucene/queries/function/FunctionValues.java
+++ b/lucene/queries/src/java/org/apache/lucene/queries/function/FunctionValues.java
@@ -19,7 +19,7 @@ package org.apache.lucene.queries.function;
import org.apache.lucene.search.*;
import org.apache.lucene.index.IndexReader;
-import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.mutable.MutableValue;
import org.apache.lucene.util.mutable.MutableValueFloat;
@@ -53,10 +53,10 @@ public abstract class FunctionValues {
}
/** returns the bytes representation of the string val - TODO: should this return the indexed raw bytes not? */
- public boolean bytesVal(int doc, BytesRef target) {
+ public boolean bytesVal(int doc, BytesRefBuilder target) {
String s = strVal(doc);
if (s==null) {
- target.length = 0;
+ target.clear();
return false;
}
target.copyChars(s);
diff --git a/lucene/queries/src/java/org/apache/lucene/queries/function/docvalues/DocTermsIndexDocValues.java b/lucene/queries/src/java/org/apache/lucene/queries/function/docvalues/DocTermsIndexDocValues.java
index dff274a5cc1..dea3ea3fe74 100644
--- a/lucene/queries/src/java/org/apache/lucene/queries/function/docvalues/DocTermsIndexDocValues.java
+++ b/lucene/queries/src/java/org/apache/lucene/queries/function/docvalues/DocTermsIndexDocValues.java
@@ -27,8 +27,8 @@ import org.apache.lucene.queries.function.FunctionValues;
import org.apache.lucene.queries.function.ValueSource;
import org.apache.lucene.queries.function.ValueSourceScorer;
import org.apache.lucene.util.BytesRef;
-import org.apache.lucene.util.CharsRef;
-import org.apache.lucene.util.UnicodeUtil;
+import org.apache.lucene.util.BytesRefBuilder;
+import org.apache.lucene.util.CharsRefBuilder;
import org.apache.lucene.util.mutable.MutableValue;
import org.apache.lucene.util.mutable.MutableValueStr;
@@ -40,7 +40,7 @@ public abstract class DocTermsIndexDocValues extends FunctionValues {
protected final SortedDocValues termsIndex;
protected final ValueSource vs;
protected final MutableValueStr val = new MutableValueStr();
- protected final CharsRef spareChars = new CharsRef();
+ protected final CharsRefBuilder spareChars = new CharsRefBuilder();
public DocTermsIndexDocValues(ValueSource vs, AtomicReaderContext context, String field) throws IOException {
this(vs, open(context, field));
@@ -69,10 +69,10 @@ public abstract class DocTermsIndexDocValues extends FunctionValues {
}
@Override
- public boolean bytesVal(int doc, BytesRef target) {
- target.length = 0;
+ public boolean bytesVal(int doc, BytesRefBuilder target) {
+ target.clear();
target.copyBytes(termsIndex.get(doc));
- return target.length > 0;
+ return target.length() > 0;
}
@Override
@@ -81,7 +81,7 @@ public abstract class DocTermsIndexDocValues extends FunctionValues {
if (term.length == 0) {
return null;
}
- UnicodeUtil.UTF8toUTF16(term, spareChars);
+ spareChars.copyUTF8Bytes(term);
return spareChars.toString();
}
@@ -149,7 +149,7 @@ public abstract class DocTermsIndexDocValues extends FunctionValues {
@Override
public void fillValue(int doc) {
int ord = termsIndex.getOrd(doc);
- mval.value.length = 0;
+ mval.value.clear();
mval.exists = ord >= 0;
if (mval.exists) {
mval.value.copyBytes(termsIndex.lookupOrd(ord));
diff --git a/lucene/queries/src/java/org/apache/lucene/queries/function/valuesource/BytesRefFieldSource.java b/lucene/queries/src/java/org/apache/lucene/queries/function/valuesource/BytesRefFieldSource.java
index ff6641f3141..ade654330f5 100644
--- a/lucene/queries/src/java/org/apache/lucene/queries/function/valuesource/BytesRefFieldSource.java
+++ b/lucene/queries/src/java/org/apache/lucene/queries/function/valuesource/BytesRefFieldSource.java
@@ -28,7 +28,7 @@ import org.apache.lucene.index.FieldInfo;
import org.apache.lucene.queries.function.FunctionValues;
import org.apache.lucene.queries.function.docvalues.DocTermsIndexDocValues;
import org.apache.lucene.util.Bits;
-import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.mutable.MutableValue;
import org.apache.lucene.util.mutable.MutableValueStr;
@@ -58,15 +58,15 @@ public class BytesRefFieldSource extends FieldCacheSource {
}
@Override
- public boolean bytesVal(int doc, BytesRef target) {
+ public boolean bytesVal(int doc, BytesRefBuilder target) {
target.copyBytes(binaryValues.get(doc));
- return target.length > 0;
+ return target.length() > 0;
}
public String strVal(int doc) {
- final BytesRef bytes = new BytesRef();
+ final BytesRefBuilder bytes = new BytesRefBuilder();
return bytesVal(doc, bytes)
- ? bytes.utf8ToString()
+ ? bytes.get().utf8ToString()
: null;
}
@@ -93,7 +93,7 @@ public class BytesRefFieldSource extends FieldCacheSource {
@Override
public void fillValue(int doc) {
mval.exists = docsWithField.get(doc);
- mval.value.length = 0;
+ mval.value.clear();
mval.value.copyBytes(binaryValues.get(doc));
}
};
diff --git a/lucene/queries/src/java/org/apache/lucene/queries/function/valuesource/DefFunction.java b/lucene/queries/src/java/org/apache/lucene/queries/function/valuesource/DefFunction.java
index c94782409bb..7a0326ffc02 100644
--- a/lucene/queries/src/java/org/apache/lucene/queries/function/valuesource/DefFunction.java
+++ b/lucene/queries/src/java/org/apache/lucene/queries/function/valuesource/DefFunction.java
@@ -19,11 +19,9 @@ package org.apache.lucene.queries.function.valuesource;
import org.apache.lucene.index.AtomicReaderContext;
import org.apache.lucene.queries.function.FunctionValues;
import org.apache.lucene.queries.function.ValueSource;
-import org.apache.lucene.search.IndexSearcher;
-import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import java.io.IOException;
-import java.util.Arrays;
import java.util.List;
import java.util.Map;
@@ -102,7 +100,7 @@ public class DefFunction extends MultiFunction {
}
@Override
- public boolean bytesVal(int doc, BytesRef target) {
+ public boolean bytesVal(int doc, BytesRefBuilder target) {
return get(doc).bytesVal(doc, target);
}
diff --git a/lucene/queries/src/java/org/apache/lucene/queries/function/valuesource/IfFunction.java b/lucene/queries/src/java/org/apache/lucene/queries/function/valuesource/IfFunction.java
index fde5c5c528a..4062c633fca 100644
--- a/lucene/queries/src/java/org/apache/lucene/queries/function/valuesource/IfFunction.java
+++ b/lucene/queries/src/java/org/apache/lucene/queries/function/valuesource/IfFunction.java
@@ -23,7 +23,7 @@ import org.apache.lucene.queries.function.FunctionValues;
import org.apache.lucene.queries.function.ValueSource;
import org.apache.lucene.search.Explanation;
import org.apache.lucene.search.IndexSearcher;
-import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import java.io.IOException;
import java.util.List;
@@ -94,7 +94,7 @@ public class IfFunction extends BoolFunction {
}
@Override
- public boolean bytesVal(int doc, BytesRef target) {
+ public boolean bytesVal(int doc, BytesRefBuilder target) {
return ifVals.boolVal(doc) ? trueVals.bytesVal(doc, target) : falseVals.bytesVal(doc, target);
}
diff --git a/lucene/queries/src/java/org/apache/lucene/queries/function/valuesource/LiteralValueSource.java b/lucene/queries/src/java/org/apache/lucene/queries/function/valuesource/LiteralValueSource.java
index 1762a80abc2..a369bab72a0 100644
--- a/lucene/queries/src/java/org/apache/lucene/queries/function/valuesource/LiteralValueSource.java
+++ b/lucene/queries/src/java/org/apache/lucene/queries/function/valuesource/LiteralValueSource.java
@@ -21,6 +21,7 @@ import org.apache.lucene.queries.function.FunctionValues;
import org.apache.lucene.queries.function.ValueSource;
import org.apache.lucene.queries.function.docvalues.StrDocValues;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import java.util.Map;
import java.io.IOException;
@@ -54,7 +55,7 @@ public class LiteralValueSource extends ValueSource {
}
@Override
- public boolean bytesVal(int doc, BytesRef target) {
+ public boolean bytesVal(int doc, BytesRefBuilder target) {
target.copyBytes(bytesRef);
return true;
}
diff --git a/lucene/queries/src/java/org/apache/lucene/queries/mlt/MoreLikeThis.java b/lucene/queries/src/java/org/apache/lucene/queries/mlt/MoreLikeThis.java
index db926ec4ad6..4d857d1335e 100644
--- a/lucene/queries/src/java/org/apache/lucene/queries/mlt/MoreLikeThis.java
+++ b/lucene/queries/src/java/org/apache/lucene/queries/mlt/MoreLikeThis.java
@@ -34,6 +34,7 @@ import org.apache.lucene.search.similarities.DefaultSimilarity;
import org.apache.lucene.search.similarities.TFIDFSimilarity;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.CharsRef;
+import org.apache.lucene.util.CharsRefBuilder;
import org.apache.lucene.util.PriorityQueue;
import org.apache.lucene.util.UnicodeUtil;
@@ -748,10 +749,10 @@ public final class MoreLikeThis {
*/
private void addTermFrequencies(Map<String, Int> termFreqMap, Terms vector) throws IOException {
final TermsEnum termsEnum = vector.iterator(null);
- final CharsRef spare = new CharsRef();
+ final CharsRefBuilder spare = new CharsRefBuilder();
BytesRef text;
while((text = termsEnum.next()) != null) {
- UnicodeUtil.UTF8toUTF16(text, spare);
+ spare.copyUTF8Bytes(text);
final String term = spare.toString();
if (isNoiseWord(term)) {
continue;
diff --git a/lucene/queries/src/test/org/apache/lucene/queries/function/TestDocValuesFieldSources.java b/lucene/queries/src/test/org/apache/lucene/queries/function/TestDocValuesFieldSources.java
index 24d1bb8bebb..c4dbd76f51a 100644
--- a/lucene/queries/src/test/org/apache/lucene/queries/function/TestDocValuesFieldSources.java
+++ b/lucene/queries/src/test/org/apache/lucene/queries/function/TestDocValuesFieldSources.java
@@ -34,6 +34,7 @@ import org.apache.lucene.queries.function.valuesource.BytesRefFieldSource;
import org.apache.lucene.queries.function.valuesource.LongFieldSource;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.LuceneTestCase;
import org.apache.lucene.util.TestUtil;
import org.apache.lucene.util.packed.PackedInts;
@@ -108,7 +109,7 @@ public class TestDocValuesFieldSources extends LuceneTestCase {
throw new AssertionError();
}
final FunctionValues values = vs.getValues(null, leave);
- BytesRef bytes = new BytesRef();
+ BytesRefBuilder bytes = new BytesRefBuilder();
for (int i = 0; i < leave.reader().maxDoc(); ++i) {
assertTrue(values.exists(i));
if (vs instanceof BytesRefFieldSource) {
@@ -131,7 +132,7 @@ public class TestDocValuesFieldSources extends LuceneTestCase {
assertEquals(expected, values.objectVal(i));
assertEquals(expected, values.strVal(i));
assertTrue(values.bytesVal(i, bytes));
- assertEquals(new BytesRef((String) expected), bytes);
+ assertEquals(new BytesRef((String) expected), bytes.get());
break;
case NUMERIC:
assertEquals(((Number) expected).longValue(), values.longVal(i));
diff --git a/lucene/sandbox/src/java/org/apache/lucene/codecs/idversion/IDVersionSegmentTermsEnum.java b/lucene/sandbox/src/java/org/apache/lucene/codecs/idversion/IDVersionSegmentTermsEnum.java
index bca8027b142..68ac9fd0119 100644
--- a/lucene/sandbox/src/java/org/apache/lucene/codecs/idversion/IDVersionSegmentTermsEnum.java
+++ b/lucene/sandbox/src/java/org/apache/lucene/codecs/idversion/IDVersionSegmentTermsEnum.java
@@ -31,6 +31,7 @@ import org.apache.lucene.store.IndexInput;
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.RamUsageEstimator;
import org.apache.lucene.util.fst.FST;
import org.apache.lucene.util.fst.PairOutputs.Pair;
@@ -63,7 +64,7 @@ public final class IDVersionSegmentTermsEnum extends TermsEnum {
// assert only:
private boolean eof;
- final BytesRef term = new BytesRef();
+ final BytesRefBuilder term = new BytesRefBuilder();
private final FST.BytesReader fstReader;
@SuppressWarnings({"rawtypes","unchecked"}) private FST.Arc<Pair<BytesRef,Long>>[] arcs =
@@ -242,9 +243,7 @@ public final class IDVersionSegmentTermsEnum extends TermsEnum {
throw new IllegalStateException("terms index was not loaded");
}
- if (term.bytes.length <= target.length) {
- term.bytes = ArrayUtil.grow(term.bytes, 1+target.length);
- }
+ term.grow(1 + target.length);
assert clearEOF();
@@ -284,7 +283,7 @@ public final class IDVersionSegmentTermsEnum extends TermsEnum {
targetUpto = 0;
IDVersionSegmentTermsEnumFrame lastFrame = stack[0];
- assert validIndexPrefix <= term.length: "validIndexPrefix=" + validIndexPrefix + " term.length=" + term.length + " seg=" + fr.parent.segment;
+ assert validIndexPrefix <= term.length(): "validIndexPrefix=" + validIndexPrefix + " term.length=" + term.length() + " seg=" + fr.parent.segment;
final int targetLimit = Math.min(target.length, validIndexPrefix);
@@ -295,7 +294,7 @@ public final class IDVersionSegmentTermsEnum extends TermsEnum {
// First compare up to valid seek frames:
while (targetUpto < targetLimit) {
- cmp = (term.bytes[targetUpto]&0xFF) - (target.bytes[target.offset + targetUpto]&0xFF);
+ cmp = (term.byteAt(targetUpto)&0xFF) - (target.bytes[target.offset + targetUpto]&0xFF);
// if (DEBUG) {
// System.out.println(" cycle targetUpto=" + targetUpto + " (vs limit=" + targetLimit + ") cmp=" + cmp + " (targetLabel=" + (char) (target.bytes[target.offset + targetUpto]) + " vs termLabel=" + (char) (term.bytes[targetUpto]) + ")" + " arc.output=" + arc.output + " output=" + output);
// }
@@ -323,9 +322,9 @@ public final class IDVersionSegmentTermsEnum extends TermsEnum {
// don't save arc/output/frame; we only do this
// to find out if the target term is before,
// equal or after the current term
- final int targetLimit2 = Math.min(target.length, term.length);
+ final int targetLimit2 = Math.min(target.length, term.length());
while (targetUpto < targetLimit2) {
- cmp = (term.bytes[targetUpto]&0xFF) - (target.bytes[target.offset + targetUpto]&0xFF);
+ cmp = (term.byteAt(targetUpto)&0xFF) - (target.bytes[target.offset + targetUpto]&0xFF);
// if (DEBUG) {
// System.out.println(" cycle2 targetUpto=" + targetUpto + " (vs limit=" + targetLimit + ") cmp=" + cmp + " (targetLabel=" + (char) (target.bytes[target.offset + targetUpto]) + " vs termLabel=" + (char) (term.bytes[targetUpto]) + ")");
// }
@@ -336,7 +335,7 @@ public final class IDVersionSegmentTermsEnum extends TermsEnum {
}
if (cmp == 0) {
- cmp = term.length - target.length;
+ cmp = term.length() - target.length;
}
targetUpto = targetUptoMid;
}
@@ -364,7 +363,7 @@ public final class IDVersionSegmentTermsEnum extends TermsEnum {
currentFrame.rewind();
} else {
// Target is exactly the same as current term
- assert term.length == target.length;
+ assert term.length() == target.length;
if (termExists) {
if (currentFrame.maxIDVersion < minIDVersion) {
@@ -447,8 +446,8 @@ public final class IDVersionSegmentTermsEnum extends TermsEnum {
if (!currentFrame.hasTerms) {
termExists = false;
- term.bytes[targetUpto] = (byte) targetLabel;
- term.length = 1+targetUpto;
+ term.setByteAt(targetUpto, (byte) targetLabel);
+ term.setLength(1+targetUpto);
// if (DEBUG) {
// System.out.println(" FAST NOT_FOUND term=" + brToString(term));
// }
@@ -465,12 +464,12 @@ public final class IDVersionSegmentTermsEnum extends TermsEnum {
if (currentFrame.fp != startFrameFP || changed) {
//if (targetUpto+1 > term.length) {
termExists = false;
- term.bytes[targetUpto] = (byte) targetLabel;
- term.length = 1+targetUpto;
+ term.setByteAt(targetUpto, (byte) targetLabel);
+ term.setLength(1+targetUpto);
// if (DEBUG) {
// System.out.println(" reset current term");
// }
- validIndexPrefix = Math.min(validIndexPrefix, term.length);
+ validIndexPrefix = Math.min(validIndexPrefix, term.length());
}
//if (currentFrame.ord != startFrameOrd) {
//termExists = false;
@@ -511,12 +510,12 @@ public final class IDVersionSegmentTermsEnum extends TermsEnum {
} else {
// Follow this arc
arc = nextArc;
- if (term.bytes[targetUpto] != (byte) targetLabel) {
+ if (term.byteAt(targetUpto) != (byte) targetLabel) {
// if (DEBUG) {
// System.out.println(" now set termExists=false targetUpto=" + targetUpto + " term=" + term.bytes[targetUpto] + " targetLabel=" + targetLabel);
// }
changed = true;
- term.bytes[targetUpto] = (byte) targetLabel;
+ term.setByteAt(targetUpto, (byte) targetLabel);
termExists = false;
}
// Aggregate output as we go:
@@ -546,7 +545,7 @@ public final class IDVersionSegmentTermsEnum extends TermsEnum {
// Target term is entirely contained in the index:
if (!currentFrame.hasTerms) {
termExists = false;
- term.length = targetUpto;
+ term.setLength(targetUpto);
// if (DEBUG) {
// System.out.println(" FAST NOT_FOUND term=" + brToString(term));
// }
@@ -560,7 +559,7 @@ public final class IDVersionSegmentTermsEnum extends TermsEnum {
if (currentFrame.maxIDVersion < minIDVersion) {
// The max version for all terms in this block is lower than the minVersion
termExists = false;
- term.length = targetUpto;
+ term.setLength(targetUpto);
return false;
}
@@ -591,10 +590,8 @@ public final class IDVersionSegmentTermsEnum extends TermsEnum {
if (fr.index == null) {
throw new IllegalStateException("terms index was not loaded");
}
-
- if (term.bytes.length <= target.length) {
- term.bytes = ArrayUtil.grow(term.bytes, 1+target.length);
- }
+
+ term.grow(1 + target.length);
assert clearEOF();
@@ -628,7 +625,7 @@ public final class IDVersionSegmentTermsEnum extends TermsEnum {
targetUpto = 0;
IDVersionSegmentTermsEnumFrame lastFrame = stack[0];
- assert validIndexPrefix <= term.length;
+ assert validIndexPrefix <= term.length();
final int targetLimit = Math.min(target.length, validIndexPrefix);
@@ -639,7 +636,7 @@ public final class IDVersionSegmentTermsEnum extends TermsEnum {
// First compare up to valid seek frames:
while (targetUpto < targetLimit) {
- cmp = (term.bytes[targetUpto]&0xFF) - (target.bytes[target.offset + targetUpto]&0xFF);
+ cmp = (term.byteAt(targetUpto)&0xFF) - (target.bytes[target.offset + targetUpto]&0xFF);
//if (DEBUG) {
//System.out.println(" cycle targetUpto=" + targetUpto + " (vs limit=" + targetLimit + ") cmp=" + cmp + " (targetLabel=" + (char) (target.bytes[target.offset + targetUpto]) + " vs termLabel=" + (char) (term.bytes[targetUpto]) + ")" + " arc.output=" + arc.output + " output=" + output);
//}
@@ -667,9 +664,9 @@ public final class IDVersionSegmentTermsEnum extends TermsEnum {
final int targetUptoMid = targetUpto;
// Second compare the rest of the term, but
// don't save arc/output/frame:
- final int targetLimit2 = Math.min(target.length, term.length);
+ final int targetLimit2 = Math.min(target.length, term.length());
while (targetUpto < targetLimit2) {
- cmp = (term.bytes[targetUpto]&0xFF) - (target.bytes[target.offset + targetUpto]&0xFF);
+ cmp = (term.byteAt(targetUpto)&0xFF) - (target.bytes[target.offset + targetUpto]&0xFF);
//if (DEBUG) {
//System.out.println(" cycle2 targetUpto=" + targetUpto + " (vs limit=" + targetLimit + ") cmp=" + cmp + " (targetLabel=" + (char) (target.bytes[target.offset + targetUpto]) + " vs termLabel=" + (char) (term.bytes[targetUpto]) + ")");
//}
@@ -680,7 +677,7 @@ public final class IDVersionSegmentTermsEnum extends TermsEnum {
}
if (cmp == 0) {
- cmp = term.length - target.length;
+ cmp = term.length() - target.length;
}
targetUpto = targetUptoMid;
}
@@ -707,7 +704,7 @@ public final class IDVersionSegmentTermsEnum extends TermsEnum {
currentFrame.rewind();
} else {
// Target is exactly the same as current term
- assert term.length == target.length;
+ assert term.length() == target.length;
if (termExists) {
//if (DEBUG) {
//System.out.println(" target is same as current; return FOUND");
@@ -791,7 +788,7 @@ public final class IDVersionSegmentTermsEnum extends TermsEnum {
}
} else {
// Follow this arc
- term.bytes[targetUpto] = (byte) targetLabel;
+ term.setByteAt(targetUpto, (byte) targetLabel);
arc = nextArc;
// Aggregate output as we go:
assert arc.output != null;
@@ -851,7 +848,7 @@ public final class IDVersionSegmentTermsEnum extends TermsEnum {
while(true) {
IDVersionSegmentTermsEnumFrame f = getFrame(ord);
assert f != null;
- final BytesRef prefix = new BytesRef(term.bytes, 0, f.prefix);
+ final BytesRef prefix = new BytesRef(term.bytes(), 0, f.prefix);
if (f.nextEnt == -1) {
out.println(" frame " + (isSeekFrame ? "(seek)" : "(next)") + " ord=" + ord + " fp=" + f.fp + (f.isFloor ? (" (fpOrig=" + f.fpOrig + ")") : "") + " prefixLen=" + f.prefix + " prefix=" + brToString(prefix) + (f.nextEnt == -1 ? "" : (" (of " + f.entCount + ")")) + " hasTerms=" + f.hasTerms + " isFloor=" + f.isFloor + " code=" + ((f.fp<<VersionBlockTreeTermsWriter.OUTPUT_FLAGS_NUM_BITS) + (f.hasTerms ? VersionBlockTreeTermsWriter.OUTPUT_FLAG_HAS_TERMS:0) + (f.isFloor ? VersionBlockTreeTermsWriter.OUTPUT_FLAG_IS_FLOOR:0)) + " isLastInFloor=" + f.isLastInFloor + " mdUpto=" + f.metaDataUpto + " tbOrd=" + f.getTermBlockOrd());
} else {
@@ -859,8 +856,8 @@ public final class IDVersionSegmentTermsEnum extends TermsEnum {
}
if (fr.index != null) {
assert !isSeekFrame || f.arc != null: "isSeekFrame=" + isSeekFrame + " f.arc=" + f.arc;
- if (f.prefix > 0 && isSeekFrame && f.arc.label != (term.bytes[f.prefix-1]&0xFF)) {
- out.println(" broken seek state: arc.label=" + (char) f.arc.label + " vs term byte=" + (char) (term.bytes[f.prefix-1]&0xFF));
+ if (f.prefix > 0 && isSeekFrame && f.arc.label != (term.byteAt(f.prefix-1)&0xFF)) {
+ out.println(" broken seek state: arc.label=" + (char) f.arc.label + " vs term byte=" + (char) (term.byteAt(f.prefix-1)&0xFF));
throw new RuntimeException("seek state is broken");
}
Pair<BytesRef,Long> output = Util.get(fr.index, prefix);
@@ -924,7 +921,7 @@ public final class IDVersionSegmentTermsEnum extends TermsEnum {
// this method catches up all internal state so next()
// works properly:
//if (DEBUG) System.out.println(" re-seek to pending term=" + term.utf8ToString() + " " + term);
- final boolean result = seekExact(term);
+ final boolean result = seekExact(term.get());
assert result;
}
@@ -937,7 +934,7 @@ public final class IDVersionSegmentTermsEnum extends TermsEnum {
if (currentFrame.ord == 0) {
//if (DEBUG) System.out.println(" return null");
assert setEOF();
- term.length = 0;
+ term.clear();
validIndexPrefix = 0;
currentFrame.rewind();
termExists = false;
@@ -949,7 +946,7 @@ public final class IDVersionSegmentTermsEnum extends TermsEnum {
if (currentFrame.nextEnt == -1 || currentFrame.lastSubFP != lastFP) {
// We popped into a frame that's not loaded
// yet or not scan'd to the right entry
- currentFrame.scanToFloorFrame(term);
+ currentFrame.scanToFloorFrame(term.get());
currentFrame.loadBlock();
currentFrame.scanToSubBlock(lastFP);
}
@@ -967,7 +964,7 @@ public final class IDVersionSegmentTermsEnum extends TermsEnum {
if (currentFrame.next()) {
// Push to new block:
//if (DEBUG) System.out.println(" push frame");
- currentFrame = pushFrame(null, currentFrame.lastSubFP, term.length);
+ currentFrame = pushFrame(null, currentFrame.lastSubFP, term.length());
// This is a "next" frame -- even if it's
// floor'd we must pretend it isn't so we don't
// try to scan to the right floor frame:
@@ -976,7 +973,7 @@ public final class IDVersionSegmentTermsEnum extends TermsEnum {
currentFrame.loadBlock();
} else {
//if (DEBUG) System.out.println(" return term=" + term.utf8ToString() + " " + term + " currentFrame.ord=" + currentFrame.ord);
- return term;
+ return term.get();
}
}
}
@@ -984,7 +981,7 @@ public final class IDVersionSegmentTermsEnum extends TermsEnum {
@Override
public BytesRef term() {
assert !eof;
- return term;
+ return term.get();
}
@Override
@@ -1030,7 +1027,7 @@ public final class IDVersionSegmentTermsEnum extends TermsEnum {
// System.out.println("BTTR.seekExact termState seg=" + segment + " target=" + target.utf8ToString() + " " + target + " state=" + otherState);
// }
assert clearEOF();
- if (target.compareTo(term) != 0 || !termExists) {
+ if (target.compareTo(term.get()) != 0 || !termExists) {
assert otherState != null && otherState instanceof BlockTermState;
currentFrame = staticFrame;
currentFrame.state.copyFrom(otherState);
diff --git a/lucene/sandbox/src/java/org/apache/lucene/codecs/idversion/IDVersionSegmentTermsEnumFrame.java b/lucene/sandbox/src/java/org/apache/lucene/codecs/idversion/IDVersionSegmentTermsEnumFrame.java
index fa64056c7f8..314f4a15fa5 100644
--- a/lucene/sandbox/src/java/org/apache/lucene/codecs/idversion/IDVersionSegmentTermsEnumFrame.java
+++ b/lucene/sandbox/src/java/org/apache/lucene/codecs/idversion/IDVersionSegmentTermsEnumFrame.java
@@ -266,11 +266,9 @@ final class IDVersionSegmentTermsEnumFrame {
nextEnt++;
suffix = suffixesReader.readVInt();
startBytePos = suffixesReader.getPosition();
- ste.term.length = prefix + suffix;
- if (ste.term.bytes.length < ste.term.length) {
- ste.term.grow(ste.term.length);
- }
- suffixesReader.readBytes(ste.term.bytes, prefix, suffix);
+ ste.term.setLength(prefix + suffix);
+ ste.term.grow(ste.term.length());
+ suffixesReader.readBytes(ste.term.bytes(), prefix, suffix);
// A normal term
ste.termExists = true;
return false;
@@ -283,11 +281,9 @@ final class IDVersionSegmentTermsEnumFrame {
final int code = suffixesReader.readVInt();
suffix = code >>> 1;
startBytePos = suffixesReader.getPosition();
- ste.term.length = prefix + suffix;
- if (ste.term.bytes.length < ste.term.length) {
- ste.term.grow(ste.term.length);
- }
- suffixesReader.readBytes(ste.term.bytes, prefix, suffix);
+ ste.term.setLength(prefix + suffix);
+ ste.term.grow(ste.term.length());
+ suffixesReader.readBytes(ste.term.bytes(), prefix, suffix);
if ((code & 1) == 0) {
// A normal term
ste.termExists = true;
@@ -417,7 +413,7 @@ final class IDVersionSegmentTermsEnumFrame {
// Used only by assert
private boolean prefixMatches(BytesRef target) {
for(int bytePos=0;bytePos<prefix;bytePos++) {
- if (target.bytes[target.offset + bytePos] != ste.term.bytes[bytePos]) {
+ if (target.bytes[target.offset + bytePos] != ste.term.byteAt(bytePos)) {
return false;
}
}
@@ -552,7 +548,7 @@ final class IDVersionSegmentTermsEnumFrame {
ste.currentFrame = ste.pushFrame(null, ste.currentFrame.lastSubFP, termLen);
ste.currentFrame.loadBlock();
while (ste.currentFrame.next()) {
- ste.currentFrame = ste.pushFrame(null, ste.currentFrame.lastSubFP, ste.term.length);
+ ste.currentFrame = ste.pushFrame(null, ste.currentFrame.lastSubFP, ste.term.length());
ste.currentFrame.loadBlock();
}
}
@@ -685,7 +681,7 @@ final class IDVersionSegmentTermsEnumFrame {
ste.currentFrame = ste.pushFrame(null, ste.currentFrame.lastSubFP, termLen);
ste.currentFrame.loadBlock();
while (ste.currentFrame.next()) {
- ste.currentFrame = ste.pushFrame(null, ste.currentFrame.lastSubFP, ste.term.length);
+ ste.currentFrame = ste.pushFrame(null, ste.currentFrame.lastSubFP, ste.term.length());
ste.currentFrame.loadBlock();
}
}
@@ -729,10 +725,8 @@ final class IDVersionSegmentTermsEnumFrame {
private void fillTerm() {
final int termLength = prefix + suffix;
- ste.term.length = prefix + suffix;
- if (ste.term.bytes.length < termLength) {
- ste.term.grow(termLength);
- }
- System.arraycopy(suffixBytes, startBytePos, ste.term.bytes, prefix, suffix);
+ ste.term.setLength(prefix + suffix);
+ ste.term.grow(termLength);
+ System.arraycopy(suffixBytes, startBytePos, ste.term.bytes(), prefix, suffix);
}
}
diff --git a/lucene/sandbox/src/java/org/apache/lucene/codecs/idversion/VersionBlockTreeTermsWriter.java b/lucene/sandbox/src/java/org/apache/lucene/codecs/idversion/VersionBlockTreeTermsWriter.java
index 3bc4ad5bd18..25193af0a5a 100644
--- a/lucene/sandbox/src/java/org/apache/lucene/codecs/idversion/VersionBlockTreeTermsWriter.java
+++ b/lucene/sandbox/src/java/org/apache/lucene/codecs/idversion/VersionBlockTreeTermsWriter.java
@@ -38,9 +38,10 @@ import org.apache.lucene.store.IndexOutput;
import org.apache.lucene.store.RAMOutputStream;
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.FixedBitSet;
import org.apache.lucene.util.IOUtils;
-import org.apache.lucene.util.IntsRef;
+import org.apache.lucene.util.IntsRefBuilder;
import org.apache.lucene.util.StringHelper;
import org.apache.lucene.util.fst.Builder;
import org.apache.lucene.util.fst.ByteSequenceOutputs;
@@ -336,7 +337,7 @@ public final class VersionBlockTreeTermsWriter extends FieldsConsumer {
return "BLOCK: " + brToString(prefix);
}
- public void compileIndex(List<PendingBlock> blocks, RAMOutputStream scratchBytes, IntsRef scratchIntsRef) throws IOException {
+ public void compileIndex(List<PendingBlock> blocks, RAMOutputStream scratchBytes, IntsRefBuilder scratchIntsRef) throws IOException {
assert (isFloor && blocks.size() > 1) || (isFloor == false && blocks.size() == 1): "isFloor=" + isFloor + " blocks=" + blocks;
assert this == blocks.get(0);
@@ -402,7 +403,7 @@ public final class VersionBlockTreeTermsWriter extends FieldsConsumer {
// TODO: maybe we could add bulk-add method to
// Builder? Takes FST and unions it w/ current
// FST.
- private void append(Builder<Pair<BytesRef,Long>> builder, FST<Pair<BytesRef,Long>> subIndex, IntsRef scratchIntsRef) throws IOException {
+ private void append(Builder<Pair<BytesRef,Long>> builder, FST<Pair<BytesRef,Long>> subIndex, IntsRefBuilder scratchIntsRef) throws IOException {
final BytesRefFSTEnum<Pair<BytesRef,Long>> subIndexEnum = new BytesRefFSTEnum<>(subIndex);
BytesRefFSTEnum.InputOutput<Pair<BytesRef,Long>> indexEnt;
while((indexEnt = subIndexEnum.next()) != null) {
@@ -415,7 +416,7 @@ public final class VersionBlockTreeTermsWriter extends FieldsConsumer {
}
private final RAMOutputStream scratchBytes = new RAMOutputStream();
- private final IntsRef scratchIntsRef = new IntsRef();
+ private final IntsRefBuilder scratchIntsRef = new IntsRefBuilder();
class TermsWriter {
private final FieldInfo fieldInfo;
@@ -429,7 +430,7 @@ public final class VersionBlockTreeTermsWriter extends FieldsConsumer {
// startsByPrefix[0] is the index into pending for the first
// term/sub-block starting with 't'. We use this to figure out when
// to write a new block:
- private final BytesRef lastTerm = new BytesRef();
+ private final BytesRefBuilder lastTerm = new BytesRefBuilder();
private int[] prefixStarts = new int[8];
private final long[] longs;
@@ -567,7 +568,7 @@ public final class VersionBlockTreeTermsWriter extends FieldsConsumer {
boolean hasFloorLeadLabel = isFloor && floorLeadLabel != -1;
final BytesRef prefix = new BytesRef(prefixLength + (hasFloorLeadLabel ? 1 : 0));
- System.arraycopy(lastTerm.bytes, 0, prefix.bytes, 0, prefixLength);
+ System.arraycopy(lastTerm.bytes(), 0, prefix.bytes, 0, prefixLength);
prefix.length = prefixLength;
// Write block header:
@@ -762,18 +763,18 @@ public final class VersionBlockTreeTermsWriter extends FieldsConsumer {
/** Pushes the new term to the top of the stack, and writes new blocks. */
private void pushTerm(BytesRef text) throws IOException {
- int limit = Math.min(lastTerm.length, text.length);
+ int limit = Math.min(lastTerm.length(), text.length);
// Find common prefix between last term and current term:
int pos = 0;
- while (pos < limit && lastTerm.bytes[pos] == text.bytes[text.offset+pos]) {
+ while (pos < limit && lastTerm.byteAt(pos) == text.bytes[text.offset+pos]) {
pos++;
}
// if (DEBUG) System.out.println(" shared=" + pos + " lastTerm.length=" + lastTerm.length);
// Close the "abandoned" suffix now:
- for(int i=lastTerm.length-1;i>=pos;i--) {
+ for(int i=lastTerm.length()-1;i>=pos;i--) {
// How many items on top of the stack share the current suffix
// we are closing:
diff --git a/lucene/sandbox/src/java/org/apache/lucene/sandbox/queries/SlowFuzzyTermsEnum.java b/lucene/sandbox/src/java/org/apache/lucene/sandbox/queries/SlowFuzzyTermsEnum.java
index 0bdc37deefc..5ba963d0919 100644
--- a/lucene/sandbox/src/java/org/apache/lucene/sandbox/queries/SlowFuzzyTermsEnum.java
+++ b/lucene/sandbox/src/java/org/apache/lucene/sandbox/queries/SlowFuzzyTermsEnum.java
@@ -28,6 +28,7 @@ import org.apache.lucene.search.FuzzyTermsEnum;
import org.apache.lucene.util.AttributeSource;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.IntsRef;
+import org.apache.lucene.util.IntsRefBuilder;
import org.apache.lucene.util.StringHelper;
import org.apache.lucene.util.UnicodeUtil;
@@ -103,7 +104,7 @@ public final class SlowFuzzyTermsEnum extends FuzzyTermsEnum {
private final BytesRef prefixBytesRef;
// used for unicode conversion from BytesRef byte[] to int[]
- private final IntsRef utf32 = new IntsRef(20);
+ private final IntsRefBuilder utf32 = new IntsRefBuilder();
/**
* <p>The termCompare method in FuzzyTermEnum uses Levenshtein distance to
@@ -121,8 +122,8 @@ public final class SlowFuzzyTermsEnum extends FuzzyTermsEnum {
@Override
protected final AcceptStatus accept(BytesRef term) {
if (StringHelper.startsWith(term, prefixBytesRef)) {
- UnicodeUtil.UTF8toUTF32(term, utf32);
- final int distance = calcDistance(utf32.ints, realPrefixLength, utf32.length - realPrefixLength);
+ utf32.copyUTF8Bytes(term);
+ final int distance = calcDistance(utf32.ints(), realPrefixLength, utf32.length() - realPrefixLength);
//Integer.MIN_VALUE is the sentinel that Levenshtein stopped early
if (distance == Integer.MIN_VALUE){
@@ -132,7 +133,7 @@ public final class SlowFuzzyTermsEnum extends FuzzyTermsEnum {
if (raw == true && distance > maxEdits){
return AcceptStatus.NO;
}
- final float similarity = calcSimilarity(distance, (utf32.length - realPrefixLength), text.length);
+ final float similarity = calcSimilarity(distance, (utf32.length() - realPrefixLength), text.length);
//if raw is true, then distance must also be <= maxEdits by now
//given the previous if statement
diff --git a/lucene/sandbox/src/java/org/apache/lucene/sandbox/queries/regex/JakartaRegexpCapabilities.java b/lucene/sandbox/src/java/org/apache/lucene/sandbox/queries/regex/JakartaRegexpCapabilities.java
index 7ef386288c3..5996f9cbfc0 100644
--- a/lucene/sandbox/src/java/org/apache/lucene/sandbox/queries/regex/JakartaRegexpCapabilities.java
+++ b/lucene/sandbox/src/java/org/apache/lucene/sandbox/queries/regex/JakartaRegexpCapabilities.java
@@ -19,10 +19,12 @@ package org.apache.lucene.sandbox.queries.regex;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.CharsRef;
+import org.apache.lucene.util.CharsRefBuilder;
import org.apache.lucene.util.UnicodeUtil;
import org.apache.regexp.CharacterIterator;
import org.apache.regexp.RE;
import org.apache.regexp.REProgram;
+
import java.lang.reflect.Field;
import java.lang.reflect.Method;
@@ -113,27 +115,27 @@ public class JakartaRegexpCapabilities implements RegexCapabilities {
class JakartaRegexMatcher implements RegexCapabilities.RegexMatcher {
private RE regexp;
- private final CharsRef utf16 = new CharsRef(10);
+ private final CharsRefBuilder utf16 = new CharsRefBuilder();
private final CharacterIterator utf16wrapper = new CharacterIterator() {
@Override
public char charAt(int pos) {
- return utf16.chars[pos];
+ return utf16.charAt(pos);
}
@Override
public boolean isEnd(int pos) {
- return pos >= utf16.length;
+ return pos >= utf16.length();
}
@Override
public String substring(int beginIndex) {
- return substring(beginIndex, utf16.length);
+ return substring(beginIndex, utf16.length());
}
@Override
public String substring(int beginIndex, int endIndex) {
- return new String(utf16.chars, beginIndex, endIndex - beginIndex);
+ return new String(utf16.chars(), beginIndex, endIndex - beginIndex);
}
};
@@ -144,7 +146,7 @@ public class JakartaRegexpCapabilities implements RegexCapabilities {
@Override
public boolean match(BytesRef term) {
- UnicodeUtil.UTF8toUTF16(term.bytes, term.offset, term.length, utf16);
+ utf16.copyUTF8Bytes(term);
return regexp.match(utf16wrapper, 0);
}
diff --git a/lucene/sandbox/src/java/org/apache/lucene/sandbox/queries/regex/JavaUtilRegexCapabilities.java b/lucene/sandbox/src/java/org/apache/lucene/sandbox/queries/regex/JavaUtilRegexCapabilities.java
index 443c7a94cbf..13d0324fe21 100644
--- a/lucene/sandbox/src/java/org/apache/lucene/sandbox/queries/regex/JavaUtilRegexCapabilities.java
+++ b/lucene/sandbox/src/java/org/apache/lucene/sandbox/queries/regex/JavaUtilRegexCapabilities.java
@@ -22,6 +22,7 @@ import java.util.regex.Pattern;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.CharsRef;
+import org.apache.lucene.util.CharsRefBuilder;
import org.apache.lucene.util.UnicodeUtil;
/**
@@ -104,16 +105,17 @@ public class JavaUtilRegexCapabilities implements RegexCapabilities {
class JavaUtilRegexMatcher implements RegexCapabilities.RegexMatcher {
private final Pattern pattern;
private final Matcher matcher;
- private final CharsRef utf16 = new CharsRef(10);
+ private final CharsRefBuilder utf16 = new CharsRefBuilder();
public JavaUtilRegexMatcher(String regex, int flags) {
this.pattern = Pattern.compile(regex, flags);
- this.matcher = this.pattern.matcher(utf16);
+ this.matcher = this.pattern.matcher(utf16.get());
}
@Override
public boolean match(BytesRef term) {
- UnicodeUtil.UTF8toUTF16(term.bytes, term.offset, term.length, utf16);
+ utf16.copyUTF8Bytes(term);
+ utf16.get();
return matcher.reset().matches();
}
diff --git a/lucene/spatial/src/java/org/apache/lucene/spatial/bbox/BBoxStrategy.java b/lucene/spatial/src/java/org/apache/lucene/spatial/bbox/BBoxStrategy.java
index 55713ff9f7f..9e40f45ab1e 100644
--- a/lucene/spatial/src/java/org/apache/lucene/spatial/bbox/BBoxStrategy.java
+++ b/lucene/spatial/src/java/org/apache/lucene/spatial/bbox/BBoxStrategy.java
@@ -21,6 +21,7 @@ import com.spatial4j.core.context.SpatialContext;
import com.spatial4j.core.shape.Point;
import com.spatial4j.core.shape.Rectangle;
import com.spatial4j.core.shape.Shape;
+
import org.apache.lucene.document.DoubleField;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.FieldType;
@@ -43,6 +44,7 @@ import org.apache.lucene.spatial.query.SpatialOperation;
import org.apache.lucene.spatial.query.UnsupportedSpatialOperation;
import org.apache.lucene.spatial.util.DistanceToShapeValueSource;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.NumericUtils;
@@ -586,9 +588,9 @@ public class BBoxStrategy extends SpatialStrategy {
}
private Query makeNumberTermQuery(String field, double number) {
- BytesRef bytes = new BytesRef();
+ BytesRefBuilder bytes = new BytesRefBuilder();
NumericUtils.longToPrefixCodedBytes(NumericUtils.doubleToSortableLong(number), 0, bytes);
- return new TermQuery(new Term(field, bytes));
+ return new TermQuery(new Term(field, bytes.get()));
}
}
diff --git a/lucene/spatial/src/java/org/apache/lucene/spatial/prefix/TermQueryPrefixTreeStrategy.java b/lucene/spatial/src/java/org/apache/lucene/spatial/prefix/TermQueryPrefixTreeStrategy.java
index c21261d1f9a..41bb66bb9ab 100644
--- a/lucene/spatial/src/java/org/apache/lucene/spatial/prefix/TermQueryPrefixTreeStrategy.java
+++ b/lucene/spatial/src/java/org/apache/lucene/spatial/prefix/TermQueryPrefixTreeStrategy.java
@@ -19,6 +19,7 @@ package org.apache.lucene.spatial.prefix;
import com.spatial4j.core.shape.Point;
import com.spatial4j.core.shape.Shape;
+
import org.apache.lucene.queries.TermsFilter;
import org.apache.lucene.search.Filter;
import org.apache.lucene.spatial.prefix.tree.Cell;
@@ -28,6 +29,7 @@ import org.apache.lucene.spatial.query.SpatialArgs;
import org.apache.lucene.spatial.query.SpatialOperation;
import org.apache.lucene.spatial.query.UnsupportedSpatialOperation;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import java.util.ArrayList;
import java.util.List;
@@ -68,7 +70,7 @@ public class TermQueryPrefixTreeStrategy extends PrefixTreeStrategy {
else
GUESS_NUM_TERMS = 4096;//should this be a method on SpatialPrefixTree?
- BytesRef masterBytes = new BytesRef(GUESS_NUM_TERMS*detailLevel);//shared byte array for all terms
+ BytesRefBuilder masterBytes = new BytesRefBuilder();//shared byte array for all terms
List<BytesRef> terms = new ArrayList<>(GUESS_NUM_TERMS);
CellIterator cells = grid.getTreeCellIterator(shape, detailLevel);
@@ -79,15 +81,15 @@ public class TermQueryPrefixTreeStrategy extends PrefixTreeStrategy {
BytesRef term = cell.getTokenBytesNoLeaf(null);//null because we want a new BytesRef
//We copy out the bytes because it may be re-used across the iteration. This also gives us the opportunity
// to use one contiguous block of memory for the bytes of all terms we need.
- masterBytes.grow(masterBytes.length + term.length);
+ masterBytes.grow(masterBytes.length() + term.length);
masterBytes.append(term);
term.bytes = null;//don't need; will reset later
- term.offset = masterBytes.length - term.length;
+ term.offset = masterBytes.length() - term.length;
terms.add(term);
}
//doing this now because if we did earlier, it's possible the bytes needed to grow()
for (BytesRef byteRef : terms) {
- byteRef.bytes = masterBytes.bytes;
+ byteRef.bytes = masterBytes.bytes();
}
//unfortunately TermsFilter will needlessly sort & dedupe
return new TermsFilter(getFieldName(), terms);
diff --git a/lucene/spatial/src/java/org/apache/lucene/spatial/prefix/tree/QuadPrefixTree.java b/lucene/spatial/src/java/org/apache/lucene/spatial/prefix/tree/QuadPrefixTree.java
index def3877c850..5cf730b05ad 100644
--- a/lucene/spatial/src/java/org/apache/lucene/spatial/prefix/tree/QuadPrefixTree.java
+++ b/lucene/spatial/src/java/org/apache/lucene/spatial/prefix/tree/QuadPrefixTree.java
@@ -22,11 +22,13 @@ import com.spatial4j.core.shape.Point;
import com.spatial4j.core.shape.Rectangle;
import com.spatial4j.core.shape.Shape;
import com.spatial4j.core.shape.SpatialRelation;
+
import org.apache.lucene.util.BytesRef;
import java.io.PrintStream;
import java.text.NumberFormat;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Locale;
@@ -231,21 +233,20 @@ public class QuadPrefixTree extends LegacyPrefixTree {
@Override
protected Collection<Cell> getSubCells() {
BytesRef source = getTokenBytesNoLeaf(null);
- BytesRef target = new BytesRef();
List<Cell> cells = new ArrayList<>(4);
- cells.add(new QuadCell(concat(source, (byte)'A', target), null));
- cells.add(new QuadCell(concat(source, (byte)'B', target), null));
- cells.add(new QuadCell(concat(source, (byte)'C', target), null));
- cells.add(new QuadCell(concat(source, (byte)'D', target), null));
+ cells.add(new QuadCell(concat(source, (byte)'A'), null));
+ cells.add(new QuadCell(concat(source, (byte)'B'), null));
+ cells.add(new QuadCell(concat(source, (byte)'C'), null));
+ cells.add(new QuadCell(concat(source, (byte)'D'), null));
return cells;
}
- private BytesRef concat(BytesRef source, byte b, BytesRef target) {
- assert target.offset == 0;
- target.bytes = new byte[source.length + 2];//+2 for new char + potential leaf
- target.length = 0;
- target.copyBytes(source);
+ private BytesRef concat(BytesRef source, byte b) {
+ //+2 for new char + potential leaf
+ final byte[] buffer = Arrays.copyOfRange(source.bytes, source.offset, source.offset + source.length + 2);
+ BytesRef target = new BytesRef(buffer);
+ target.length = source.length;
target.bytes[target.length++] = b;
return target;
}
diff --git a/lucene/spatial/src/java/org/apache/lucene/spatial/serialized/SerializedDVStrategy.java b/lucene/spatial/src/java/org/apache/lucene/spatial/serialized/SerializedDVStrategy.java
index 7c242ec15f0..8c46dca94c1 100644
--- a/lucene/spatial/src/java/org/apache/lucene/spatial/serialized/SerializedDVStrategy.java
+++ b/lucene/spatial/src/java/org/apache/lucene/spatial/serialized/SerializedDVStrategy.java
@@ -39,6 +39,7 @@ import org.apache.lucene.spatial.util.DistanceToShapeValueSource;
import org.apache.lucene.spatial.util.ShapePredicateValueSource;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@@ -217,14 +218,14 @@ public class SerializedDVStrategy extends SpatialStrategy {
return new FunctionValues() {
int bytesRefDoc = -1;
- BytesRef bytesRef = new BytesRef();//scratch
+ BytesRefBuilder bytesRef = new BytesRefBuilder();
boolean fillBytes(int doc) {
if (bytesRefDoc != doc) {
bytesRef.copyBytes(docValues.get(doc));
bytesRefDoc = doc;
}
- return bytesRef.length != 0;
+ return bytesRef.length() != 0;
}
@Override
@@ -233,14 +234,12 @@ public class SerializedDVStrategy extends SpatialStrategy {
}
@Override
- public boolean bytesVal(int doc, BytesRef target) {
+ public boolean bytesVal(int doc, BytesRefBuilder target) {
+ target.clear();
if (fillBytes(doc)) {
- target.bytes = bytesRef.bytes;
- target.offset = bytesRef.offset;
- target.length = bytesRef.length;
+ target.copyBytes(bytesRef);
return true;
} else {
- target.length = 0;
return false;
}
}
@@ -250,7 +249,7 @@ public class SerializedDVStrategy extends SpatialStrategy {
if (!fillBytes(docId))
return null;
DataInputStream dataInput = new DataInputStream(
- new ByteArrayInputStream(bytesRef.bytes, bytesRef.offset, bytesRef.length));
+ new ByteArrayInputStream(bytesRef.bytes(), 0, bytesRef.length()));
try {
return binaryCodec.readShape(dataInput);
} catch (IOException e) {
diff --git a/lucene/suggest/src/java/org/apache/lucene/search/spell/DirectSpellChecker.java b/lucene/suggest/src/java/org/apache/lucene/search/spell/DirectSpellChecker.java
index adb453d51cd..631ff49c6b0 100644
--- a/lucene/suggest/src/java/org/apache/lucene/search/spell/DirectSpellChecker.java
+++ b/lucene/suggest/src/java/org/apache/lucene/search/spell/DirectSpellChecker.java
@@ -28,6 +28,7 @@ import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.AttributeSource;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.CharsRef;
+import org.apache.lucene.util.CharsRefBuilder;
import org.apache.lucene.util.UnicodeUtil;
import org.apache.lucene.util.automaton.LevenshteinAutomata;
@@ -317,7 +318,7 @@ public class DirectSpellChecker {
*/
public SuggestWord[] suggestSimilar(Term term, int numSug, IndexReader ir,
SuggestMode suggestMode, float accuracy) throws IOException {
- final CharsRef spare = new CharsRef();
+ final CharsRefBuilder spare = new CharsRefBuilder();
String text = term.text();
if (minQueryLength > 0 && text.codePointCount(0, text.length()) < minQueryLength)
return new SuggestWord[0];
@@ -367,7 +368,7 @@ public class DirectSpellChecker {
for (ScoreTerm s : terms) {
SuggestWord suggestion = new SuggestWord();
if (s.termAsString == null) {
- UnicodeUtil.UTF8toUTF16(s.term, spare);
+ spare.copyUTF8Bytes(s.term);
s.termAsString = spare.toString();
}
suggestion.string = s.termAsString;
@@ -399,7 +400,7 @@ public class DirectSpellChecker {
* @throws IOException If I/O related errors occur
*/
protected Collection<ScoreTerm> suggestSimilar(Term term, int numSug, IndexReader ir, int docfreq, int editDistance,
- float accuracy, final CharsRef spare) throws IOException {
+ float accuracy, final CharsRefBuilder spare) throws IOException {
AttributeSource atts = new AttributeSource();
MaxNonCompetitiveBoostAttribute maxBoostAtt =
@@ -440,7 +441,7 @@ public class DirectSpellChecker {
// undo FuzzyTermsEnum's scale factor for a real scaled lev score
score = boost / e.getScaleFactor() + e.getMinSimilarity();
} else {
- UnicodeUtil.UTF8toUTF16(candidateTerm, spare);
+ spare.copyUTF8Bytes(candidateTerm);
termAsString = spare.toString();
score = distance.getDistance(term.text(), termAsString);
}
diff --git a/lucene/suggest/src/java/org/apache/lucene/search/spell/HighFrequencyDictionary.java b/lucene/suggest/src/java/org/apache/lucene/search/spell/HighFrequencyDictionary.java
index b6b81d97b2f..5994af3647a 100644
--- a/lucene/suggest/src/java/org/apache/lucene/search/spell/HighFrequencyDictionary.java
+++ b/lucene/suggest/src/java/org/apache/lucene/search/spell/HighFrequencyDictionary.java
@@ -26,6 +26,7 @@ import org.apache.lucene.index.Terms;
import org.apache.lucene.index.MultiFields;
import org.apache.lucene.search.suggest.InputIterator;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
/**
* HighFrequencyDictionary: terms taken from the given field
@@ -61,7 +62,7 @@ public class HighFrequencyDictionary implements Dictionary {
}
final class HighFrequencyIterator implements InputIterator {
- private final BytesRef spare = new BytesRef();
+ private final BytesRefBuilder spare = new BytesRefBuilder();
private final TermsEnum termsEnum;
private int minNumDocs;
private long freq;
@@ -93,7 +94,7 @@ public class HighFrequencyDictionary implements Dictionary {
if (isFrequent(termsEnum.docFreq())) {
freq = termsEnum.docFreq();
spare.copyBytes(next);
- return spare;
+ return spare.get();
}
}
}
diff --git a/lucene/suggest/src/java/org/apache/lucene/search/spell/PlainTextDictionary.java b/lucene/suggest/src/java/org/apache/lucene/search/spell/PlainTextDictionary.java
index 91f9db6328c..a87ef87a859 100644
--- a/lucene/suggest/src/java/org/apache/lucene/search/spell/PlainTextDictionary.java
+++ b/lucene/suggest/src/java/org/apache/lucene/search/spell/PlainTextDictionary.java
@@ -26,6 +26,7 @@ import java.nio.charset.StandardCharsets;
import org.apache.lucene.search.suggest.InputIterator;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.BytesRefIterator;
import org.apache.lucene.util.IOUtils;
@@ -74,7 +75,7 @@ public class PlainTextDictionary implements Dictionary {
final class FileIterator implements BytesRefIterator {
private boolean done = false;
- private final BytesRef spare = new BytesRef();
+ private final BytesRefBuilder spare = new BytesRefBuilder();
@Override
public BytesRef next() throws IOException {
if (done) {
@@ -86,7 +87,7 @@ public class PlainTextDictionary implements Dictionary {
String line;
if ((line = in.readLine()) != null) {
spare.copyChars(line);
- result = spare;
+ result = spare.get();
} else {
done = true;
IOUtils.close(in);
diff --git a/lucene/suggest/src/java/org/apache/lucene/search/suggest/BufferedInputIterator.java b/lucene/suggest/src/java/org/apache/lucene/search/suggest/BufferedInputIterator.java
index 85dcce3e929..27ce5397751 100644
--- a/lucene/suggest/src/java/org/apache/lucene/search/suggest/BufferedInputIterator.java
+++ b/lucene/suggest/src/java/org/apache/lucene/search/suggest/BufferedInputIterator.java
@@ -25,6 +25,7 @@ import java.util.Set;
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.BytesRefArray;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.Counter;
/**
@@ -43,8 +44,8 @@ public class BufferedInputIterator implements InputIterator {
protected int curPos = -1;
/** buffered weights, parallel with {@link #entries} */
protected long[] freqs = new long[1];
- private final BytesRef spare = new BytesRef();
- private final BytesRef payloadSpare = new BytesRef();
+ private final BytesRefBuilder spare = new BytesRefBuilder();
+ private final BytesRefBuilder payloadSpare = new BytesRefBuilder();
private final boolean hasPayloads;
private final boolean hasContexts;
@@ -79,7 +80,7 @@ public class BufferedInputIterator implements InputIterator {
public BytesRef next() throws IOException {
if (++curPos < entries.size()) {
entries.get(spare, curPos);
- return spare;
+ return spare.get();
}
return null;
}
diff --git a/lucene/suggest/src/java/org/apache/lucene/search/suggest/FileDictionary.java b/lucene/suggest/src/java/org/apache/lucene/search/suggest/FileDictionary.java
index 5006cb4e8d9..01fbdc3b5c9 100644
--- a/lucene/suggest/src/java/org/apache/lucene/search/suggest/FileDictionary.java
+++ b/lucene/suggest/src/java/org/apache/lucene/search/suggest/FileDictionary.java
@@ -24,6 +24,7 @@ import java.util.Set;
import org.apache.lucene.search.spell.Dictionary;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.IOUtils;
@@ -118,8 +119,8 @@ public class FileDictionary implements Dictionary {
final class FileIterator implements InputIterator {
private long curWeight;
- private final BytesRef spare = new BytesRef();
- private BytesRef curPayload = new BytesRef();
+ private final BytesRefBuilder spare = new BytesRefBuilder();
+ private BytesRefBuilder curPayload = new BytesRefBuilder();
private boolean isFirstLine = true;
private boolean hasPayloads = false;
@@ -159,7 +160,7 @@ public class FileDictionary implements Dictionary {
}
if (isFirstLine) {
isFirstLine = false;
- return spare;
+ return spare.get();
}
line = in.readLine();
if (line != null) {
@@ -176,16 +177,16 @@ public class FileDictionary implements Dictionary {
spare.copyChars(fields[0]);
readWeight(fields[1]);
if (hasPayloads) { // have an empty payload
- curPayload = new BytesRef();
+ curPayload = new BytesRefBuilder();
}
} else { // only term
spare.copyChars(fields[0]);
curWeight = 1;
if (hasPayloads) {
- curPayload = new BytesRef();
+ curPayload = new BytesRefBuilder();
}
}
- return spare;
+ return spare.get();
} else {
done = true;
IOUtils.close(in);
@@ -195,7 +196,7 @@ public class FileDictionary implements Dictionary {
@Override
public BytesRef payload() {
- return (hasPayloads) ? curPayload : null;
+ return (hasPayloads) ? curPayload.get() : null;
}
@Override
diff --git a/lucene/suggest/src/java/org/apache/lucene/search/suggest/SortedInputIterator.java b/lucene/suggest/src/java/org/apache/lucene/search/suggest/SortedInputIterator.java
index d340134d59b..8a4db6cc1d5 100644
--- a/lucene/suggest/src/java/org/apache/lucene/search/suggest/SortedInputIterator.java
+++ b/lucene/suggest/src/java/org/apache/lucene/search/suggest/SortedInputIterator.java
@@ -27,6 +27,7 @@ import org.apache.lucene.store.ByteArrayDataInput;
import org.apache.lucene.store.ByteArrayDataOutput;
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.OfflineSorter;
import org.apache.lucene.util.OfflineSorter.ByteSequencesReader;
@@ -48,7 +49,7 @@ public class SortedInputIterator implements InputIterator {
private boolean done = false;
private long weight;
- private final BytesRef scratch = new BytesRef();
+ private final BytesRefBuilder scratch = new BytesRefBuilder();
private BytesRef payload = new BytesRef();
private Set<BytesRef> contexts = null;
@@ -81,15 +82,16 @@ public class SortedInputIterator implements InputIterator {
try {
ByteArrayDataInput input = new ByteArrayDataInput();
if (reader.read(scratch)) {
- weight = decode(scratch, input);
+ final BytesRef bytes = scratch.get();
+ weight = decode(bytes, input);
if (hasPayloads) {
- payload = decodePayload(scratch, input);
+ payload = decodePayload(bytes, input);
}
if (hasContexts) {
- contexts = decodeContexts(scratch, input);
+ contexts = decodeContexts(bytes, input);
}
success = true;
- return scratch;
+ return bytes;
}
close();
success = done = true;
diff --git a/lucene/suggest/src/java/org/apache/lucene/search/suggest/UnsortedInputIterator.java b/lucene/suggest/src/java/org/apache/lucene/search/suggest/UnsortedInputIterator.java
index 1bc3a545f0a..9b717abe623 100644
--- a/lucene/suggest/src/java/org/apache/lucene/search/suggest/UnsortedInputIterator.java
+++ b/lucene/suggest/src/java/org/apache/lucene/search/suggest/UnsortedInputIterator.java
@@ -22,6 +22,7 @@ import java.util.Random;
import java.util.Set;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
/**
* This wrapper buffers the incoming elements and makes sure they are in
@@ -32,8 +33,8 @@ public class UnsortedInputIterator extends BufferedInputIterator {
// TODO keep this for now
private final int[] ords;
private int currentOrd = -1;
- private final BytesRef spare = new BytesRef();
- private final BytesRef payloadSpare = new BytesRef();
+ private final BytesRefBuilder spare = new BytesRefBuilder();
+ private final BytesRefBuilder payloadSpare = new BytesRefBuilder();
/**
* Creates a new iterator, wrapping the specified iterator and
* returning elements in a random order.
diff --git a/lucene/suggest/src/java/org/apache/lucene/search/suggest/analyzing/AnalyzingSuggester.java b/lucene/suggest/src/java/org/apache/lucene/search/suggest/analyzing/AnalyzingSuggester.java
index afae341b6e1..48afe0bffb6 100644
--- a/lucene/suggest/src/java/org/apache/lucene/search/suggest/analyzing/AnalyzingSuggester.java
+++ b/lucene/suggest/src/java/org/apache/lucene/search/suggest/analyzing/AnalyzingSuggester.java
@@ -38,9 +38,12 @@ import org.apache.lucene.store.DataInput;
import org.apache.lucene.store.DataOutput;
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.CharsRef;
+import org.apache.lucene.util.CharsRefBuilder;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.IntsRef;
+import org.apache.lucene.util.IntsRefBuilder;
import org.apache.lucene.util.OfflineSorter;
import org.apache.lucene.util.UnicodeUtil;
import org.apache.lucene.util.automaton.Operations;
@@ -420,7 +423,7 @@ public class AnalyzingSuggester extends Lookup {
OfflineSorter.ByteSequencesWriter writer = new OfflineSorter.ByteSequencesWriter(tempInput);
OfflineSorter.ByteSequencesReader reader = null;
- BytesRef scratch = new BytesRef();
+ BytesRefBuilder scratch = new BytesRefBuilder();
TokenStreamToAutomaton ts2a = getTokenStreamToAutomaton();
@@ -441,10 +444,10 @@ public class AnalyzingSuggester extends Lookup {
Util.toBytesRef(path, scratch);
// length of the analyzed text (FST input)
- if (scratch.length > Short.MAX_VALUE-2) {
- throw new IllegalArgumentException("cannot handle analyzed forms > " + (Short.MAX_VALUE-2) + " in length (got " + scratch.length + ")");
+ if (scratch.length() > Short.MAX_VALUE-2) {
+ throw new IllegalArgumentException("cannot handle analyzed forms > " + (Short.MAX_VALUE-2) + " in length (got " + scratch.length() + ")");
}
- short analyzedLength = (short) scratch.length;
+ short analyzedLength = (short) scratch.length();
// compute the required length:
// analyzed sequence + weight (4) + surface + analyzedLength (short)
@@ -469,7 +472,7 @@ public class AnalyzingSuggester extends Lookup {
output.writeShort(analyzedLength);
- output.writeBytes(scratch.bytes, scratch.offset, scratch.length);
+ output.writeBytes(scratch.bytes(), 0, scratch.length());
output.writeInt(encodeWeight(iterator.weight()));
@@ -505,10 +508,10 @@ public class AnalyzingSuggester extends Lookup {
Builder<Pair<Long,BytesRef>> builder = new Builder<>(FST.INPUT_TYPE.BYTE1, outputs);
// Build FST:
- BytesRef previousAnalyzed = null;
- BytesRef analyzed = new BytesRef();
+ BytesRefBuilder previousAnalyzed = null;
+ BytesRefBuilder analyzed = new BytesRefBuilder();
BytesRef surface = new BytesRef();
- IntsRef scratchInts = new IntsRef();
+ IntsRefBuilder scratchInts = new IntsRefBuilder();
ByteArrayDataInput input = new ByteArrayDataInput();
// Used to remove duplicate surface forms (but we
@@ -519,28 +522,28 @@ public class AnalyzingSuggester extends Lookup {
int dedup = 0;
while (reader.read(scratch)) {
- input.reset(scratch.bytes, scratch.offset, scratch.length);
+ input.reset(scratch.bytes(), 0, scratch.length());
short analyzedLength = input.readShort();
analyzed.grow(analyzedLength+2);
- input.readBytes(analyzed.bytes, 0, analyzedLength);
- analyzed.length = analyzedLength;
+ input.readBytes(analyzed.bytes(), 0, analyzedLength);
+ analyzed.setLength(analyzedLength);
long cost = input.readInt();
- surface.bytes = scratch.bytes;
+ surface.bytes = scratch.bytes();
if (hasPayloads) {
surface.length = input.readShort();
surface.offset = input.getPosition();
} else {
surface.offset = input.getPosition();
- surface.length = scratch.length - surface.offset;
+ surface.length = scratch.length() - surface.offset;
}
if (previousAnalyzed == null) {
- previousAnalyzed = new BytesRef();
- previousAnalyzed.copyBytes(analyzed);
+ previousAnalyzed = new BytesRefBuilder();
+ previousAnalyzed.copyBytes(analyzed.get());
seenSurfaceForms.add(BytesRef.deepCopyOf(surface));
- } else if (analyzed.equals(previousAnalyzed)) {
+ } else if (analyzed.get().equals(previousAnalyzed.get())) {
dedup++;
if (dedup >= maxSurfaceFormsPerAnalyzedForm) {
// More than maxSurfaceFormsPerAnalyzedForm
@@ -566,23 +569,22 @@ public class AnalyzingSuggester extends Lookup {
// NOTE: must be byte 0 so we sort before whatever
// is next
- analyzed.bytes[analyzed.offset+analyzed.length] = 0;
- analyzed.bytes[analyzed.offset+analyzed.length+1] = (byte) dedup;
- analyzed.length += 2;
+ analyzed.append((byte) 0);
+ analyzed.append((byte) dedup);
- Util.toIntsRef(analyzed, scratchInts);
+ Util.toIntsRef(analyzed.get(), scratchInts);
//System.out.println("ADD: " + scratchInts + " -> " + cost + ": " + surface.utf8ToString());
if (!hasPayloads) {
- builder.add(scratchInts, outputs.newPair(cost, BytesRef.deepCopyOf(surface)));
+ builder.add(scratchInts.get(), outputs.newPair(cost, BytesRef.deepCopyOf(surface)));
} else {
int payloadOffset = input.getPosition() + surface.length;
- int payloadLength = scratch.length - payloadOffset;
+ int payloadLength = scratch.length() - payloadOffset;
BytesRef br = new BytesRef(surface.length + 1 + payloadLength);
System.arraycopy(surface.bytes, surface.offset, br.bytes, 0, surface.length);
br.bytes[surface.length] = PAYLOAD_SEP;
- System.arraycopy(scratch.bytes, payloadOffset, br.bytes, surface.length+1, payloadLength);
+ System.arraycopy(scratch.bytes(), payloadOffset, br.bytes, surface.length+1, payloadLength);
br.length = br.bytes.length;
- builder.add(scratchInts, outputs.newPair(cost, br));
+ builder.add(scratchInts.get(), outputs.newPair(cost, br));
}
}
fst = builder.finish();
@@ -624,7 +626,7 @@ public class AnalyzingSuggester extends Lookup {
return true;
}
- private LookupResult getLookupResult(Long output1, BytesRef output2, CharsRef spare) {
+ private LookupResult getLookupResult(Long output1, BytesRef output2, CharsRefBuilder spare) {
LookupResult result;
if (hasPayloads) {
int sepIndex = -1;
@@ -637,14 +639,14 @@ public class AnalyzingSuggester extends Lookup {
assert sepIndex != -1;
spare.grow(sepIndex);
final int payloadLen = output2.length - sepIndex - 1;
- UnicodeUtil.UTF8toUTF16(output2.bytes, output2.offset, sepIndex, spare);
+ spare.copyUTF8Bytes(output2.bytes, output2.offset, sepIndex);
BytesRef payload = new BytesRef(payloadLen);
System.arraycopy(output2.bytes, sepIndex+1, payload.bytes, 0, payloadLen);
payload.length = payloadLen;
result = new LookupResult(spare.toString(), decodeWeight(output1), payload);
} else {
spare.grow(output2.length);
- UnicodeUtil.UTF8toUTF16(output2, spare);
+ spare.copyUTF8Bytes(output2);
result = new LookupResult(spare.toString(), decodeWeight(output1));
}
@@ -695,7 +697,7 @@ public class AnalyzingSuggester extends Lookup {
try {
Automaton lookupAutomaton = toLookupAutomaton(key);
- final CharsRef spare = new CharsRef();
+ final CharsRefBuilder spare = new CharsRefBuilder();
//System.out.println(" now intersect exactFirst=" + exactFirst);
diff --git a/lucene/suggest/src/java/org/apache/lucene/search/suggest/analyzing/FSTUtil.java b/lucene/suggest/src/java/org/apache/lucene/search/suggest/analyzing/FSTUtil.java
index ef6ea6034ca..c0158957ef8 100644
--- a/lucene/suggest/src/java/org/apache/lucene/search/suggest/analyzing/FSTUtil.java
+++ b/lucene/suggest/src/java/org/apache/lucene/search/suggest/analyzing/FSTUtil.java
@@ -22,6 +22,7 @@ import java.util.ArrayList;
import java.util.List;
import org.apache.lucene.util.IntsRef;
+import org.apache.lucene.util.IntsRefBuilder;
import org.apache.lucene.util.automaton.Automaton;
import org.apache.lucene.util.automaton.Transition;
import org.apache.lucene.util.fst.FST;
@@ -51,10 +52,10 @@ public class FSTUtil {
T output;
/** Input of the path so far: */
- public final IntsRef input;
+ public final IntsRefBuilder input;
/** Sole constructor. */
- public Path(int state, FST.Arc<T> fstNode, T output, IntsRef input) {
+ public Path(int state, FST.Arc<T> fstNode, T output, IntsRefBuilder input) {
this.state = state;
this.fstNode = fstNode;
this.output = output;
@@ -77,7 +78,7 @@ public class FSTUtil {
queue.add(new Path<>(0, fst
.getFirstArc(new FST.Arc<T>()), fst.outputs.getNoOutput(),
- new IntsRef()));
+ new IntsRefBuilder()));
final FST.Arc<T> scratchArc = new FST.Arc<>();
final FST.BytesReader fstReader = fst.getBytesReader();
@@ -93,7 +94,7 @@ public class FSTUtil {
continue;
}
- IntsRef currentInput = path.input;
+ IntsRefBuilder currentInput = path.input;
int count = a.initTransition(path.state, t);
for (int i=0;i<count;i++) {
a.getNextTransition(t);
@@ -103,10 +104,9 @@ public class FSTUtil {
final FST.Arc<T> nextArc = fst.findTargetArc(t.min,
path.fstNode, scratchArc, fstReader);
if (nextArc != null) {
- final IntsRef newInput = new IntsRef(currentInput.length + 1);
- newInput.copyInts(currentInput);
- newInput.ints[currentInput.length] = t.min;
- newInput.length = currentInput.length + 1;
+ final IntsRefBuilder newInput = new IntsRefBuilder();
+ newInput.copyInts(currentInput.get());
+ newInput.append(t.min);
queue.add(new Path<>(t.dest, new FST.Arc<T>()
.copyFrom(nextArc), fst.outputs
.add(path.output, nextArc.output), newInput));
@@ -125,10 +125,9 @@ public class FSTUtil {
assert nextArc.label <= max;
assert nextArc.label >= min : nextArc.label + " "
+ min;
- final IntsRef newInput = new IntsRef(currentInput.length + 1);
- newInput.copyInts(currentInput);
- newInput.ints[currentInput.length] = nextArc.label;
- newInput.length = currentInput.length + 1;
+ final IntsRefBuilder newInput = new IntsRefBuilder();
+ newInput.copyInts(currentInput.get());
+ newInput.append(nextArc.label);
queue.add(new Path<>(t.dest, new FST.Arc<T>()
.copyFrom(nextArc), fst.outputs
.add(path.output, nextArc.output), newInput));
diff --git a/lucene/suggest/src/java/org/apache/lucene/search/suggest/analyzing/FreeTextSuggester.java b/lucene/suggest/src/java/org/apache/lucene/search/suggest/analyzing/FreeTextSuggester.java
index 98047628358..aa4719406c9 100644
--- a/lucene/suggest/src/java/org/apache/lucene/search/suggest/analyzing/FreeTextSuggester.java
+++ b/lucene/suggest/src/java/org/apache/lucene/search/suggest/analyzing/FreeTextSuggester.java
@@ -50,9 +50,12 @@ import org.apache.lucene.store.DataOutput;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.CharsRef;
+import org.apache.lucene.util.CharsRefBuilder;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.IntsRef;
+import org.apache.lucene.util.IntsRefBuilder;
import org.apache.lucene.util.OfflineSorter;
import org.apache.lucene.util.UnicodeUtil;
import org.apache.lucene.util.Version;
@@ -350,7 +353,7 @@ public class FreeTextSuggester extends Lookup {
Outputs<Long> outputs = PositiveIntOutputs.getSingleton();
Builder<Long> builder = new Builder<>(FST.INPUT_TYPE.BYTE1, outputs);
- IntsRef scratchInts = new IntsRef();
+ IntsRefBuilder scratchInts = new IntsRefBuilder();
while (true) {
BytesRef term = termsEnum.next();
if (term == null) {
@@ -487,7 +490,7 @@ public class FreeTextSuggester extends Lookup {
PositionIncrementAttribute posIncAtt = ts.addAttribute(PositionIncrementAttribute.class);
ts.reset();
- BytesRef[] lastTokens = new BytesRef[grams];
+ BytesRefBuilder[] lastTokens = new BytesRefBuilder[grams];
//System.out.println("lookup: key='" + key + "'");
// Run full analysis, but save only the
@@ -510,7 +513,9 @@ public class FreeTextSuggester extends Lookup {
throw new IllegalArgumentException("tokens must not contain separator byte; got token=" + tokenBytes + " but gramCount=" + gramCount + " does not match recalculated count=" + countGrams(tokenBytes));
}
maxEndOffset = Math.max(maxEndOffset, offsetAtt.endOffset());
- lastTokens[gramCount-1] = BytesRef.deepCopyOf(tokenBytes);
+ BytesRefBuilder b = new BytesRefBuilder();
+ b.append(tokenBytes);
+ lastTokens[gramCount-1] = b;
}
ts.end();
@@ -538,16 +543,14 @@ public class FreeTextSuggester extends Lookup {
// all bigrams starting w/ foo, and not any unigrams
// starting with "foo":
for(int i=grams-1;i>0;i--) {
- BytesRef token = lastTokens[i-1];
+ BytesRefBuilder token = lastTokens[i-1];
if (token == null) {
continue;
}
- token.grow(token.length+1);
- token.bytes[token.length] = separator;
- token.length++;
+ token.append(separator);
lastTokens[i] = token;
}
- lastTokens[0] = new BytesRef();
+ lastTokens[0] = new BytesRefBuilder();
}
Arc<Long> arc = new Arc<>();
@@ -566,9 +569,9 @@ public class FreeTextSuggester extends Lookup {
final Set<BytesRef> seen = new HashSet<>();
for(int gram=grams-1;gram>=0;gram--) {
- BytesRef token = lastTokens[gram];
+ BytesRefBuilder token = lastTokens[gram];
// Don't make unigram predictions from empty string:
- if (token == null || (token.length == 0 && key.length() > 0)) {
+ if (token == null || (token.length() == 0 && key.length() > 0)) {
// Input didn't have enough tokens:
//System.out.println(" gram=" + gram + ": skip: not enough input");
continue;
@@ -589,7 +592,7 @@ public class FreeTextSuggester extends Lookup {
//Pair<Long,BytesRef> prefixOutput = null;
Long prefixOutput = null;
try {
- prefixOutput = lookupPrefix(fst, bytesReader, token, arc);
+ prefixOutput = lookupPrefix(fst, bytesReader, token.get(), arc);
} catch (IOException bogus) {
throw new RuntimeException(bogus);
}
@@ -611,27 +614,25 @@ public class FreeTextSuggester extends Lookup {
BytesRef lastTokenFragment = null;
- for(int i=token.length-1;i>=0;i--) {
- if (token.bytes[token.offset+i] == separator) {
- BytesRef context = new BytesRef(token.bytes, token.offset, i);
- Long output = Util.get(fst, Util.toIntsRef(context, new IntsRef()));
+ for(int i=token.length()-1;i>=0;i--) {
+ if (token.byteAt(i) == separator) {
+ BytesRef context = new BytesRef(token.bytes(), 0, i);
+ Long output = Util.get(fst, Util.toIntsRef(context, new IntsRefBuilder()));
assert output != null;
contextCount = decodeWeight(output);
- lastTokenFragment = new BytesRef(token.bytes, token.offset + i + 1, token.length - i - 1);
+ lastTokenFragment = new BytesRef(token.bytes(), i + 1, token.length() - i - 1);
break;
}
}
- final BytesRef finalLastToken;
-
+ final BytesRefBuilder finalLastToken = new BytesRefBuilder();
if (lastTokenFragment == null) {
- finalLastToken = BytesRef.deepCopyOf(token);
+ finalLastToken.copyBytes(token.get());
} else {
- finalLastToken = BytesRef.deepCopyOf(lastTokenFragment);
+ finalLastToken.copyBytes(lastTokenFragment);
}
- assert finalLastToken.offset == 0;
- CharsRef spare = new CharsRef();
+ CharsRefBuilder spare = new CharsRefBuilder();
// complete top-N
TopResults<Long> completions = null;
@@ -650,7 +651,7 @@ public class FreeTextSuggester extends Lookup {
// reject up to seen.size() paths in acceptResult():
Util.TopNSearcher<Long> searcher = new Util.TopNSearcher<Long>(fst, num, num+seen.size(), weightComparator) {
- BytesRef scratchBytes = new BytesRef();
+ BytesRefBuilder scratchBytes = new BytesRefBuilder();
@Override
protected void addIfCompetitive(Util.FSTPath<Long> path) {
@@ -665,20 +666,20 @@ public class FreeTextSuggester extends Lookup {
@Override
protected boolean acceptResult(IntsRef input, Long output) {
Util.toBytesRef(input, scratchBytes);
- finalLastToken.grow(finalLastToken.length + scratchBytes.length);
- int lenSav = finalLastToken.length;
+ finalLastToken.grow(finalLastToken.length() + scratchBytes.length());
+ int lenSav = finalLastToken.length();
finalLastToken.append(scratchBytes);
//System.out.println(" accept? input='" + scratchBytes.utf8ToString() + "'; lastToken='" + finalLastToken.utf8ToString() + "'; return " + (seen.contains(finalLastToken) == false));
- boolean ret = seen.contains(finalLastToken) == false;
+ boolean ret = seen.contains(finalLastToken.get()) == false;
- finalLastToken.length = lenSav;
+ finalLastToken.setLength(lenSav);
return ret;
}
};
// since this search is initialized with a single start node
// it is okay to start with an empty input path here
- searcher.addStartPaths(arc, prefixOutput, true, new IntsRef());
+ searcher.addStartPaths(arc, prefixOutput, true, new IntsRefBuilder());
completions = searcher.search();
assert completions.isComplete;
@@ -686,14 +687,14 @@ public class FreeTextSuggester extends Lookup {
throw new RuntimeException(bogus);
}
- int prefixLength = token.length;
+ int prefixLength = token.length();
- BytesRef suffix = new BytesRef(8);
+ BytesRefBuilder suffix = new BytesRefBuilder();
//System.out.println(" " + completions.length + " completions");
nextCompletion:
for (Result<Long> completion : completions) {
- token.length = prefixLength;
+ token.setLength(prefixLength);
// append suffix
Util.toBytesRef(completion.input, suffix);
token.append(suffix);
@@ -702,11 +703,11 @@ public class FreeTextSuggester extends Lookup {
// Skip this path if a higher-order model already
// saw/predicted its last token:
- BytesRef lastToken = token;
- for(int i=token.length-1;i>=0;i--) {
- if (token.bytes[token.offset+i] == separator) {
- assert token.length-i-1 > 0;
- lastToken = new BytesRef(token.bytes, token.offset+i+1, token.length-i-1);
+ BytesRef lastToken = token.get();
+ for(int i=token.length()-1;i>=0;i--) {
+ if (token.byteAt(i) == separator) {
+ assert token.length()-i-1 > 0;
+ lastToken = new BytesRef(token.bytes(), i+1, token.length()-i-1);
break;
}
}
@@ -715,8 +716,7 @@ public class FreeTextSuggester extends Lookup {
continue nextCompletion;
}
seen.add(BytesRef.deepCopyOf(lastToken));
- spare.grow(token.length);
- UnicodeUtil.UTF8toUTF16(token, spare);
+ spare.copyUTF8Bytes(token.get());
LookupResult result = new LookupResult(spare.toString(), (long) (Long.MAX_VALUE * backoff * ((double) decodeWeight(completion.output)) / contextCount));
results.add(result);
assert results.size() == seen.size();
diff --git a/lucene/suggest/src/java/org/apache/lucene/search/suggest/fst/FSTCompletionBuilder.java b/lucene/suggest/src/java/org/apache/lucene/search/suggest/fst/FSTCompletionBuilder.java
index e04d40c50bb..9a57b72cd9c 100644
--- a/lucene/suggest/src/java/org/apache/lucene/search/suggest/fst/FSTCompletionBuilder.java
+++ b/lucene/suggest/src/java/org/apache/lucene/search/suggest/fst/FSTCompletionBuilder.java
@@ -22,8 +22,10 @@ import java.io.IOException;
import org.apache.lucene.search.suggest.InMemorySorter;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.BytesRefIterator;
import org.apache.lucene.util.IntsRef;
+import org.apache.lucene.util.IntsRefBuilder;
import org.apache.lucene.util.fst.*;
import org.apache.lucene.util.packed.PackedInts;
@@ -137,7 +139,7 @@ public class FSTCompletionBuilder {
/**
* Scratch buffer for {@link #add(BytesRef, int)}.
*/
- private final BytesRef scratch = new BytesRef();
+ private final BytesRefBuilder scratch = new BytesRefBuilder();
/**
* Max tail sharing length.
@@ -206,14 +208,11 @@ public class FSTCompletionBuilder {
"Bucket outside of the allowed range [0, " + buckets + "): " + bucket);
}
- if (scratch.bytes.length < utf8.length + 1) {
- scratch.grow(utf8.length + 10);
- }
-
- scratch.length = 1;
- scratch.bytes[0] = (byte) bucket;
+ scratch.grow(utf8.length + 10);
+ scratch.clear();
+ scratch.append((byte) bucket);
scratch.append(utf8);
- sorter.add(scratch);
+ sorter.add(scratch.get());
}
/**
@@ -242,14 +241,14 @@ public class FSTCompletionBuilder {
shareMaxTailLength, outputs, false,
PackedInts.DEFAULT, true, 15);
- BytesRef scratch = new BytesRef();
+ BytesRefBuilder scratch = new BytesRefBuilder();
BytesRef entry;
- final IntsRef scratchIntsRef = new IntsRef();
+ final IntsRefBuilder scratchIntsRef = new IntsRefBuilder();
int count = 0;
BytesRefIterator iter = sorter.iterator();
while((entry = iter.next()) != null) {
count++;
- if (scratch.compareTo(entry) != 0) {
+ if (scratch.get().compareTo(entry) != 0) {
builder.add(Util.toIntsRef(entry, scratchIntsRef), empty);
scratch.copyBytes(entry);
}
diff --git a/lucene/suggest/src/java/org/apache/lucene/search/suggest/fst/FSTCompletionLookup.java b/lucene/suggest/src/java/org/apache/lucene/search/suggest/fst/FSTCompletionLookup.java
index fe6adfa7420..e6b33de2d48 100644
--- a/lucene/suggest/src/java/org/apache/lucene/search/suggest/fst/FSTCompletionLookup.java
+++ b/lucene/suggest/src/java/org/apache/lucene/search/suggest/fst/FSTCompletionLookup.java
@@ -34,7 +34,9 @@ import org.apache.lucene.store.DataOutput;
import org.apache.lucene.util.Accountable;
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.CharsRef;
+import org.apache.lucene.util.CharsRefBuilder;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.OfflineSorter;
import org.apache.lucene.util.OfflineSorter.SortInfo;
@@ -197,10 +199,10 @@ public class FSTCompletionLookup extends Lookup implements Accountable {
int previousBucket = 0;
int previousScore = 0;
ByteArrayDataInput input = new ByteArrayDataInput();
- BytesRef tmp1 = new BytesRef();
+ BytesRefBuilder tmp1 = new BytesRefBuilder();
BytesRef tmp2 = new BytesRef();
while (reader.read(tmp1)) {
- input.reset(tmp1.bytes);
+ input.reset(tmp1.bytes());
int currentScore = input.readInt();
int bucket;
@@ -213,9 +215,9 @@ public class FSTCompletionLookup extends Lookup implements Accountable {
previousBucket = bucket;
// Only append the input, discard the weight.
- tmp2.bytes = tmp1.bytes;
+ tmp2.bytes = tmp1.bytes();
tmp2.offset = input.getPosition();
- tmp2.length = tmp1.length - input.getPosition();
+ tmp2.length = tmp1.length() - input.getPosition();
builder.add(tmp2, bucket);
line++;
@@ -260,10 +262,9 @@ public class FSTCompletionLookup extends Lookup implements Accountable {
}
final ArrayList<LookupResult> results = new ArrayList<>(completions.size());
- CharsRef spare = new CharsRef();
+ CharsRefBuilder spare = new CharsRefBuilder();
for (Completion c : completions) {
- spare.grow(c.utf8.length);
- UnicodeUtil.UTF8toUTF16(c.utf8, spare);
+ spare.copyUTF8Bytes(c.utf8);
results.add(new LookupResult(spare.toString(), c.bucket));
}
return results;
diff --git a/lucene/suggest/src/java/org/apache/lucene/search/suggest/fst/WFSTCompletionLookup.java b/lucene/suggest/src/java/org/apache/lucene/search/suggest/fst/WFSTCompletionLookup.java
index 474605f4c5a..e8e70c9a18a 100644
--- a/lucene/suggest/src/java/org/apache/lucene/search/suggest/fst/WFSTCompletionLookup.java
+++ b/lucene/suggest/src/java/org/apache/lucene/search/suggest/fst/WFSTCompletionLookup.java
@@ -33,10 +33,10 @@ import org.apache.lucene.store.DataInput;
import org.apache.lucene.store.DataOutput;
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.BytesRef;
-import org.apache.lucene.util.CharsRef;
-import org.apache.lucene.util.IntsRef;
+import org.apache.lucene.util.BytesRefBuilder;
+import org.apache.lucene.util.CharsRefBuilder;
+import org.apache.lucene.util.IntsRefBuilder;
import org.apache.lucene.util.OfflineSorter.ByteSequencesWriter;
-import org.apache.lucene.util.UnicodeUtil;
import org.apache.lucene.util.fst.Builder;
import org.apache.lucene.util.fst.FST.Arc;
import org.apache.lucene.util.fst.FST.BytesReader;
@@ -104,21 +104,21 @@ public class WFSTCompletionLookup extends Lookup {
count = 0;
BytesRef scratch = new BytesRef();
InputIterator iter = new WFSTInputIterator(iterator);
- IntsRef scratchInts = new IntsRef();
- BytesRef previous = null;
+ IntsRefBuilder scratchInts = new IntsRefBuilder();
+ BytesRefBuilder previous = null;
PositiveIntOutputs outputs = PositiveIntOutputs.getSingleton();
Builder<Long> builder = new Builder<>(FST.INPUT_TYPE.BYTE1, outputs);
while ((scratch = iter.next()) != null) {
long cost = iter.weight();
if (previous == null) {
- previous = new BytesRef();
- } else if (scratch.equals(previous)) {
+ previous = new BytesRefBuilder();
+ } else if (scratch.equals(previous.get())) {
continue; // for duplicate suggestions, the best weight is actually
// added
}
Util.toIntsRef(scratch, scratchInts);
- builder.add(scratchInts, cost);
+ builder.add(scratchInts.get(), cost);
previous.copyBytes(scratch);
count++;
}
@@ -158,14 +158,15 @@ public class WFSTCompletionLookup extends Lookup {
return Collections.emptyList();
}
- BytesRef scratch = new BytesRef(key);
- int prefixLength = scratch.length;
+ BytesRefBuilder scratch = new BytesRefBuilder();
+ scratch.copyChars(key);
+ int prefixLength = scratch.length();
Arc<Long> arc = new Arc<>();
// match the prefix portion exactly
Long prefixOutput = null;
try {
- prefixOutput = lookupPrefix(scratch, arc);
+ prefixOutput = lookupPrefix(scratch.get(), arc);
} catch (IOException bogus) { throw new RuntimeException(bogus); }
if (prefixOutput == null) {
@@ -173,10 +174,9 @@ public class WFSTCompletionLookup extends Lookup {
}
List<LookupResult> results = new ArrayList<>(num);
- CharsRef spare = new CharsRef();
+ CharsRefBuilder spare = new CharsRefBuilder();
if (exactFirst && arc.isFinal()) {
- spare.grow(scratch.length);
- UnicodeUtil.UTF8toUTF16(scratch, spare);
+ spare.copyUTF8Bytes(scratch.get());
results.add(new LookupResult(spare.toString(), decodeWeight(prefixOutput + arc.nextFinalOutput)));
if (--num == 0) {
return results; // that was quick
@@ -192,14 +192,13 @@ public class WFSTCompletionLookup extends Lookup {
throw new RuntimeException(bogus);
}
- BytesRef suffix = new BytesRef(8);
+ BytesRefBuilder suffix = new BytesRefBuilder();
for (Result<Long> completion : completions) {
- scratch.length = prefixLength;
+ scratch.setLength(prefixLength);
// append suffix
Util.toBytesRef(completion.input, suffix);
scratch.append(suffix);
- spare.grow(scratch.length);
- UnicodeUtil.UTF8toUTF16(scratch, spare);
+ spare.copyUTF8Bytes(scratch.get());
results.add(new LookupResult(spare.toString(), decodeWeight(completion.output)));
}
return results;
diff --git a/lucene/suggest/src/java/org/apache/lucene/search/suggest/jaspell/JaspellLookup.java b/lucene/suggest/src/java/org/apache/lucene/search/suggest/jaspell/JaspellLookup.java
index 07702c86703..6182fa42329 100644
--- a/lucene/suggest/src/java/org/apache/lucene/search/suggest/jaspell/JaspellLookup.java
+++ b/lucene/suggest/src/java/org/apache/lucene/search/suggest/jaspell/JaspellLookup.java
@@ -30,6 +30,7 @@ import org.apache.lucene.store.DataOutput;
import org.apache.lucene.util.Accountable;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.CharsRef;
+import org.apache.lucene.util.CharsRefBuilder;
import org.apache.lucene.util.UnicodeUtil;
/**
@@ -66,15 +67,14 @@ public class JaspellLookup extends Lookup implements Accountable {
trie = new JaspellTernarySearchTrie();
trie.setMatchAlmostDiff(editDistance);
BytesRef spare;
- final CharsRef charsSpare = new CharsRef();
+ final CharsRefBuilder charsSpare = new CharsRefBuilder();
while ((spare = iterator.next()) != null) {
final long weight = iterator.weight();
if (spare.length == 0) {
continue;
}
- charsSpare.grow(spare.length);
- UnicodeUtil.UTF8toUTF16(spare.bytes, spare.offset, spare.length, charsSpare);
+ charsSpare.copyUTF8Bytes(spare);
trie.put(charsSpare.toString(), Long.valueOf(weight));
count++;
}
diff --git a/lucene/suggest/src/java/org/apache/lucene/search/suggest/tst/TSTLookup.java b/lucene/suggest/src/java/org/apache/lucene/search/suggest/tst/TSTLookup.java
index 00d38beef9f..a0c0e8c8e44 100644
--- a/lucene/suggest/src/java/org/apache/lucene/search/suggest/tst/TSTLookup.java
+++ b/lucene/suggest/src/java/org/apache/lucene/search/suggest/tst/TSTLookup.java
@@ -29,6 +29,7 @@ import org.apache.lucene.store.DataInput;
import org.apache.lucene.store.DataOutput;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.CharsRef;
+import org.apache.lucene.util.CharsRefBuilder;
import org.apache.lucene.util.RamUsageEstimator;
import org.apache.lucene.util.UnicodeUtil;
@@ -67,10 +68,9 @@ public class TSTLookup extends Lookup {
ArrayList<String> tokens = new ArrayList<>();
ArrayList<Number> vals = new ArrayList<>();
BytesRef spare;
- CharsRef charsSpare = new CharsRef();
+ CharsRefBuilder charsSpare = new CharsRefBuilder();
while ((spare = iterator.next()) != null) {
- charsSpare.grow(spare.length);
- UnicodeUtil.UTF8toUTF16(spare.bytes, spare.offset, spare.length, charsSpare);
+ charsSpare.copyUTF8Bytes(spare);
tokens.add(charsSpare.toString());
vals.add(Long.valueOf(iterator.weight()));
count++;
diff --git a/lucene/suggest/src/test/org/apache/lucene/search/suggest/InputArrayIterator.java b/lucene/suggest/src/test/org/apache/lucene/search/suggest/InputArrayIterator.java
index 937fb9ea2c8..cdd96d69334 100644
--- a/lucene/suggest/src/test/org/apache/lucene/search/suggest/InputArrayIterator.java
+++ b/lucene/suggest/src/test/org/apache/lucene/search/suggest/InputArrayIterator.java
@@ -22,6 +22,7 @@ import java.util.Iterator;
import java.util.Set;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
/**
* A {@link InputIterator} over a sequence of {@link Input}s.
@@ -32,7 +33,7 @@ public final class InputArrayIterator implements InputIterator {
private final boolean hasContexts;
private boolean first;
private Input current;
- private final BytesRef spare = new BytesRef();
+ private final BytesRefBuilder spare = new BytesRefBuilder();
public InputArrayIterator(Iterator<Input> i) {
this.i = i;
@@ -68,7 +69,7 @@ public final class InputArrayIterator implements InputIterator {
current = i.next();
}
spare.copyBytes(current.term);
- return spare;
+ return spare.get();
}
return null;
}
diff --git a/lucene/suggest/src/test/org/apache/lucene/search/suggest/analyzing/FuzzySuggesterTest.java b/lucene/suggest/src/test/org/apache/lucene/search/suggest/analyzing/FuzzySuggesterTest.java
index 085905542e6..103c4b91ae5 100644
--- a/lucene/suggest/src/test/org/apache/lucene/search/suggest/analyzing/FuzzySuggesterTest.java
+++ b/lucene/suggest/src/test/org/apache/lucene/search/suggest/analyzing/FuzzySuggesterTest.java
@@ -44,6 +44,7 @@ import org.apache.lucene.search.suggest.Input;
import org.apache.lucene.search.suggest.InputArrayIterator;
import org.apache.lucene.search.suggest.Lookup.LookupResult;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.IntsRef;
import org.apache.lucene.util.LuceneTestCase;
import org.apache.lucene.util.TestUtil;
@@ -755,10 +756,10 @@ public class FuzzySuggesterTest extends LuceneTestCase {
assertTrue(automaton.isDeterministic());
// TODO: could be faster... but its slowCompletor for a reason
- BytesRef spare = new BytesRef();
+ BytesRefBuilder spare = new BytesRefBuilder();
for (TermFreqPayload2 e : slowCompletor) {
spare.copyChars(e.analyzedForm);
- Set<IntsRef> finiteStrings = suggester.toFiniteStrings(spare, tokenStreamToAutomaton);
+ Set<IntsRef> finiteStrings = suggester.toFiniteStrings(spare.get(), tokenStreamToAutomaton);
for (IntsRef intsRef : finiteStrings) {
int p = 0;
BytesRef ref = Util.toBytesRef(intsRef, spare);
diff --git a/lucene/suggest/src/test/org/apache/lucene/search/suggest/fst/LargeInputFST.java b/lucene/suggest/src/test/org/apache/lucene/search/suggest/fst/LargeInputFST.java
index d55e8febb64..02b09b78023 100644
--- a/lucene/suggest/src/test/org/apache/lucene/search/suggest/fst/LargeInputFST.java
+++ b/lucene/suggest/src/test/org/apache/lucene/search/suggest/fst/LargeInputFST.java
@@ -26,6 +26,7 @@ import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.OfflineSorter;
/**
@@ -46,12 +47,12 @@ public class LargeInputFST {
new InputStreamReader(
new FileInputStream(input), StandardCharsets.UTF_8));
- BytesRef scratch = new BytesRef();
+ BytesRefBuilder scratch = new BytesRefBuilder();
String line;
int count = 0;
while ((line = reader.readLine()) != null) {
scratch.copyChars(line);
- builder.add(scratch, count % buckets);
+ builder.add(scratch.get(), count % buckets);
if ((count++ % 100000) == 0) {
System.err.println("Line: " + count);
}
diff --git a/lucene/test-framework/src/java/org/apache/lucene/analysis/CannedBinaryTokenStream.java b/lucene/test-framework/src/java/org/apache/lucene/analysis/CannedBinaryTokenStream.java
index c6f1f8fd6a2..00231f7c51a 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/analysis/CannedBinaryTokenStream.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/analysis/CannedBinaryTokenStream.java
@@ -23,6 +23,7 @@ import org.apache.lucene.analysis.tokenattributes.PositionLengthAttribute;
import org.apache.lucene.analysis.tokenattributes.TermToBytesRefAttribute;
import org.apache.lucene.util.AttributeImpl;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
/**
* TokenStream from a canned list of binary (BytesRef-based)
@@ -69,16 +70,16 @@ public final class CannedBinaryTokenStream extends TokenStream {
/** Implementation for {@link BinaryTermAttribute}. */
public final static class BinaryTermAttributeImpl extends AttributeImpl implements BinaryTermAttribute, TermToBytesRefAttribute {
- private final BytesRef bytes = new BytesRef();
+ private final BytesRefBuilder bytes = new BytesRefBuilder();
@Override
public void fillBytesRef() {
- // no-op: we already filled externally during owner's incrementToken
+ bytes.get(); // sets the length on the bytesref
}
@Override
public BytesRef getBytesRef() {
- return bytes;
+ return bytes.get();
}
@Override
diff --git a/lucene/test-framework/src/java/org/apache/lucene/codecs/asserting/AssertingPostingsFormat.java b/lucene/test-framework/src/java/org/apache/lucene/codecs/asserting/AssertingPostingsFormat.java
index 1221c84fff8..2f0c3adaa5b 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/codecs/asserting/AssertingPostingsFormat.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/codecs/asserting/AssertingPostingsFormat.java
@@ -34,6 +34,7 @@ import org.apache.lucene.index.SegmentWriteState;
import org.apache.lucene.index.Terms;
import org.apache.lucene.index.TermsEnum;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
/**
* Just like {@link Lucene41PostingsFormat} but with additional asserts.
@@ -131,7 +132,7 @@ public final class AssertingPostingsFormat extends PostingsFormat {
assert terms != null;
termsEnum = terms.iterator(termsEnum);
- BytesRef lastTerm = null;
+ BytesRefBuilder lastTerm = null;
DocsEnum docsEnum = null;
DocsAndPositionsEnum posEnum = null;
@@ -148,9 +149,10 @@ public final class AssertingPostingsFormat extends PostingsFormat {
if (term == null) {
break;
}
- assert lastTerm == null || lastTerm.compareTo(term) < 0;
+ assert lastTerm == null || lastTerm.get().compareTo(term) < 0;
if (lastTerm == null) {
- lastTerm = BytesRef.deepCopyOf(term);
+ lastTerm = new BytesRefBuilder();
+ lastTerm.append(term);
} else {
lastTerm.copyBytes(term);
}
diff --git a/lucene/test-framework/src/java/org/apache/lucene/codecs/lucene42/Lucene42DocValuesConsumer.java b/lucene/test-framework/src/java/org/apache/lucene/codecs/lucene42/Lucene42DocValuesConsumer.java
index 464bd4f920c..48762c51843 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/codecs/lucene42/Lucene42DocValuesConsumer.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/codecs/lucene42/Lucene42DocValuesConsumer.java
@@ -35,6 +35,7 @@ import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.IOUtils;
import org.apache.lucene.util.IntsRef;
+import org.apache.lucene.util.IntsRefBuilder;
import org.apache.lucene.util.MathUtil;
import org.apache.lucene.util.fst.Builder;
import org.apache.lucene.util.fst.FST.INPUT_TYPE;
@@ -254,7 +255,7 @@ class Lucene42DocValuesConsumer extends DocValuesConsumer {
meta.writeLong(data.getFilePointer());
PositiveIntOutputs outputs = PositiveIntOutputs.getSingleton();
Builder<Long> builder = new Builder<>(INPUT_TYPE.BYTE1, outputs);
- IntsRef scratch = new IntsRef();
+ IntsRefBuilder scratch = new IntsRefBuilder();
long ord = 0;
for (BytesRef v : values) {
builder.add(Util.toIntsRef(v, scratch), ord);
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 8bef30484a1..4375313178e 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
@@ -902,9 +902,9 @@ public final class TestUtil {
public static CharSequence bytesToCharSequence(BytesRef ref, Random random) {
switch(random.nextInt(5)) {
case 4:
- CharsRef chars = new CharsRef(ref.length);
- UnicodeUtil.UTF8toUTF16(ref.bytes, ref.offset, ref.length, chars);
- return chars;
+ final char[] chars = new char[ref.length];
+ final int len = UnicodeUtil.UTF8toUTF16(ref.bytes, ref.offset, ref.length, chars);
+ return new CharsRef(chars, 0, len);
case 3:
return CharBuffer.wrap(ref.utf8ToString());
default:
diff --git a/lucene/test-framework/src/java/org/apache/lucene/util/automaton/AutomatonTestUtil.java b/lucene/test-framework/src/java/org/apache/lucene/util/automaton/AutomatonTestUtil.java
index 41d7c513446..9b8a97e657c 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/util/automaton/AutomatonTestUtil.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/util/automaton/AutomatonTestUtil.java
@@ -28,6 +28,7 @@ import java.util.Set;
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.IntsRef;
+import org.apache.lucene.util.IntsRefBuilder;
import org.apache.lucene.util.TestUtil;
import org.apache.lucene.util.UnicodeUtil;
@@ -401,7 +402,7 @@ public class AutomatonTestUtil {
*/
public static Set<IntsRef> getFiniteStringsRecursive(Automaton a, int limit) {
HashSet<IntsRef> strings = new HashSet<>();
- if (!getFiniteStrings(a, 0, new HashSet<Integer>(), strings, new IntsRef(), limit)) {
+ if (!getFiniteStrings(a, 0, new HashSet<Integer>(), strings, new IntsRefBuilder(), limit)) {
return strings;
}
return strings;
@@ -413,7 +414,7 @@ public class AutomatonTestUtil {
* <code>limit</code>&lt;0 means "infinite".
*/
private static boolean getFiniteStrings(Automaton a, int s, HashSet<Integer> pathstates,
- HashSet<IntsRef> strings, IntsRef path, int limit) {
+ HashSet<IntsRef> strings, IntsRefBuilder path, int limit) {
pathstates.add(s);
Transition t = new Transition();
int count = a.initTransition(s, t);
@@ -423,11 +424,9 @@ public class AutomatonTestUtil {
return false;
}
for (int n = t.min; n <= t.max; n++) {
- path.grow(path.length+1);
- path.ints[path.length] = n;
- path.length++;
+ path.append(n);
if (a.isAccept(t.dest)) {
- strings.add(IntsRef.deepCopyOf(path));
+ strings.add(path.toIntsRef());
if (limit >= 0 && strings.size() > limit) {
return false;
}
@@ -435,7 +434,7 @@ public class AutomatonTestUtil {
if (!getFiniteStrings(a, t.dest, pathstates, strings, path, limit)) {
return false;
}
- path.length--;
+ path.setLength(path.length() - 1);
}
}
pathstates.remove(s);
diff --git a/lucene/test-framework/src/java/org/apache/lucene/util/fst/FSTTester.java b/lucene/test-framework/src/java/org/apache/lucene/util/fst/FSTTester.java
index 60c5dbf7780..4b41901b14d 100644
--- a/lucene/test-framework/src/java/org/apache/lucene/util/fst/FSTTester.java
+++ b/lucene/test-framework/src/java/org/apache/lucene/util/fst/FSTTester.java
@@ -38,6 +38,7 @@ import org.apache.lucene.store.IndexInput;
import org.apache.lucene.store.IndexOutput;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.IntsRef;
+import org.apache.lucene.util.IntsRefBuilder;
import org.apache.lucene.util.LuceneTestCase;
import org.apache.lucene.util.TestUtil;
import org.apache.lucene.util.UnicodeUtil;
@@ -122,10 +123,10 @@ public class FSTTester<T> {
}
static IntsRef toIntsRef(String s, int inputMode) {
- return toIntsRef(s, inputMode, new IntsRef(10));
+ return toIntsRef(s, inputMode, new IntsRefBuilder());
}
- static IntsRef toIntsRef(String s, int inputMode, IntsRef ir) {
+ static IntsRef toIntsRef(String s, int inputMode, IntsRefBuilder ir) {
if (inputMode == 0) {
// utf8
return toIntsRef(new BytesRef(s), ir);
@@ -135,32 +136,28 @@ public class FSTTester<T> {
}
}
- static IntsRef toIntsRefUTF32(String s, IntsRef ir) {
+ static IntsRef toIntsRefUTF32(String s, IntsRefBuilder ir) {
final int charLength = s.length();
int charIdx = 0;
int intIdx = 0;
+ ir.clear();
while(charIdx < charLength) {
- if (intIdx == ir.ints.length) {
- ir.grow(intIdx+1);
- }
+ ir.grow(intIdx+1);
final int utf32 = s.codePointAt(charIdx);
- ir.ints[intIdx] = utf32;
+ ir.append(utf32);
charIdx += Character.charCount(utf32);
intIdx++;
}
- ir.length = intIdx;
- return ir;
+ return ir.get();
}
- static IntsRef toIntsRef(BytesRef br, IntsRef ir) {
- if (br.length > ir.ints.length) {
- ir.grow(br.length);
- }
+ static IntsRef toIntsRef(BytesRef br, IntsRefBuilder ir) {
+ ir.grow(br.length);
+ ir.clear();
for(int i=0;i<br.length;i++) {
- ir.ints[i] = br.bytes[br.offset+i]&0xFF;
+ ir.append(br.bytes[br.offset+i]&0xFF);
}
- ir.length = br.length;
- return ir;
+ return ir.get();
}
/** Holds one input/output pair. */
@@ -234,12 +231,11 @@ public class FSTTester<T> {
return output;
}
- private T randomAcceptedWord(FST<T> fst, IntsRef in) throws IOException {
+ private T randomAcceptedWord(FST<T> fst, IntsRefBuilder in) throws IOException {
FST.Arc<T> arc = fst.getFirstArc(new FST.Arc<T>());
final List<FST.Arc<T>> arcs = new ArrayList<>();
- in.length = 0;
- in.offset = 0;
+ in.clear();
final T NO_OUTPUT = fst.outputs.getNoOutput();
T output = NO_OUTPUT;
final FST.BytesReader fstReader = fst.getBytesReader();
@@ -265,10 +261,7 @@ public class FSTTester<T> {
break;
}
- if (in.ints.length == in.length) {
- in.grow(1+in.length);
- }
- in.ints[in.length++] = arc.label;
+ in.append(arc.label);
}
return output;
@@ -444,19 +437,19 @@ public class FSTTester<T> {
if (LuceneTestCase.VERBOSE) {
System.out.println("TEST: verify random accepted terms");
}
- final IntsRef scratch = new IntsRef(10);
+ final IntsRefBuilder scratch = new IntsRefBuilder();
int num = LuceneTestCase.atLeast(random, 500);
for(int iter=0;iter<num;iter++) {
T output = randomAcceptedWord(fst, scratch);
- assertTrue("accepted word " + inputToString(inputMode, scratch) + " is not valid", termsMap.containsKey(scratch));
- assertTrue(outputsEqual(termsMap.get(scratch), output));
+ assertTrue("accepted word " + inputToString(inputMode, scratch.get()) + " is not valid", termsMap.containsKey(scratch.get()));
+ assertTrue(outputsEqual(termsMap.get(scratch.get()), output));
if (doReverseLookup) {
//System.out.println("lookup output=" + output + " outs=" + fst.outputs);
IntsRef input = Util.getByOutput(fstLong, (Long) output);
assertNotNull(input);
//System.out.println(" got " + Util.toBytesRef(input, new BytesRef()).utf8ToString());
- assertEquals(scratch, input);
+ assertEquals(scratch.get(), input);
}
}
@@ -683,17 +676,17 @@ public class FSTTester<T> {
// build all prefixes
final Map<IntsRef,CountMinOutput<T>> prefixes = new HashMap<>();
- final IntsRef scratch = new IntsRef(10);
+ final IntsRefBuilder scratch = new IntsRefBuilder();
for(InputOutput<T> pair: pairs) {
scratch.copyInts(pair.input);
for(int idx=0;idx<=pair.input.length;idx++) {
- scratch.length = idx;
- CountMinOutput<T> cmo = prefixes.get(scratch);
+ scratch.setLength(idx);
+ CountMinOutput<T> cmo = prefixes.get(scratch.get());
if (cmo == null) {
cmo = new CountMinOutput<>();
cmo.count = 1;
cmo.output = pair.output;
- prefixes.put(IntsRef.deepCopyOf(scratch), cmo);
+ prefixes.put(scratch.toIntsRef(), cmo);
} else {
cmo.count++;
T output1 = cmo.output;
@@ -735,9 +728,9 @@ public class FSTTester<T> {
keep = true;
} else if (prefix.length > 0) {
// consult our parent
- scratch.length = prefix.length-1;
- System.arraycopy(prefix.ints, prefix.offset, scratch.ints, 0, scratch.length);
- final CountMinOutput<T> cmo2 = prefixes.get(scratch);
+ scratch.setLength(prefix.length-1);
+ System.arraycopy(prefix.ints, prefix.offset, scratch.ints(), 0, scratch.length());
+ final CountMinOutput<T> cmo2 = prefixes.get(scratch.get());
//System.out.println(" parent count = " + (cmo2 == null ? -1 : cmo2.count));
keep = cmo2 != null && ((prune2 > 1 && cmo2.count >= prune2) || (prune2 == 1 && (cmo2.count >= 2 || prefix.length <= 1)));
} else if (cmo.count >= prune2) {
@@ -754,14 +747,14 @@ public class FSTTester<T> {
// clear isLeaf for all ancestors
//System.out.println(" keep");
scratch.copyInts(prefix);
- scratch.length--;
- while(scratch.length >= 0) {
- final CountMinOutput<T> cmo2 = prefixes.get(scratch);
+ scratch.setLength(scratch.length() - 1);
+ while(scratch.length() >= 0) {
+ final CountMinOutput<T> cmo2 = prefixes.get(scratch.get());
if (cmo2 != null) {
//System.out.println(" clear isLeaf " + inputToString(inputMode, scratch));
cmo2.isLeaf = false;
}
- scratch.length--;
+ scratch.setLength(scratch.length() - 1);
}
}
}
diff --git a/solr/core/src/java/org/apache/solr/analytics/util/valuesource/MultiStringFunction.java b/solr/core/src/java/org/apache/solr/analytics/util/valuesource/MultiStringFunction.java
index d99eab63e6d..5ef3fddb61a 100644
--- a/solr/core/src/java/org/apache/solr/analytics/util/valuesource/MultiStringFunction.java
+++ b/solr/core/src/java/org/apache/solr/analytics/util/valuesource/MultiStringFunction.java
@@ -25,7 +25,7 @@ import org.apache.lucene.index.AtomicReaderContext;
import org.apache.lucene.queries.function.FunctionValues;
import org.apache.lucene.queries.function.ValueSource;
import org.apache.lucene.queries.function.docvalues.StrDocValues;
-import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.mutable.MutableValue;
import org.apache.lucene.util.mutable.MutableValueStr;
@@ -84,15 +84,13 @@ public abstract class MultiStringFunction extends ValueSource {
}
@Override
- public boolean bytesVal(int doc, BytesRef bytes) {
+ public boolean bytesVal(int doc, BytesRefBuilder bytes) {
+ bytes.clear();
CharSequence cs = func(doc, valsArr);
if( cs != null ){
bytes.copyChars(func(doc,valsArr));
return true;
} else {
- bytes.bytes = BytesRef.EMPTY_BYTES;
- bytes.length = 0;
- bytes.offset = 0;
return false;
}
}
diff --git a/solr/core/src/java/org/apache/solr/analytics/util/valuesource/SingleStringFunction.java b/solr/core/src/java/org/apache/solr/analytics/util/valuesource/SingleStringFunction.java
index c5178b9d1b7..7540649f891 100644
--- a/solr/core/src/java/org/apache/solr/analytics/util/valuesource/SingleStringFunction.java
+++ b/solr/core/src/java/org/apache/solr/analytics/util/valuesource/SingleStringFunction.java
@@ -25,6 +25,7 @@ import org.apache.lucene.queries.function.FunctionValues;
import org.apache.lucene.queries.function.ValueSource;
import org.apache.lucene.queries.function.docvalues.StrDocValues;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.mutable.MutableValue;
import org.apache.lucene.util.mutable.MutableValueStr;
@@ -58,15 +59,13 @@ public abstract class SingleStringFunction extends ValueSource {
}
@Override
- public boolean bytesVal(int doc, BytesRef bytes) {
+ public boolean bytesVal(int doc, BytesRefBuilder bytes) {
CharSequence cs = func(doc, vals);
if( cs != null ){
bytes.copyChars(func(doc,vals));
return true;
} else {
- bytes.bytes = BytesRef.EMPTY_BYTES;
- bytes.length = 0;
- bytes.offset = 0;
+ bytes.clear();
return false;
}
}
diff --git a/solr/core/src/java/org/apache/solr/handler/AnalysisRequestHandlerBase.java b/solr/core/src/java/org/apache/solr/handler/AnalysisRequestHandlerBase.java
index a2cd9ed448b..624a31e8298 100644
--- a/solr/core/src/java/org/apache/solr/handler/AnalysisRequestHandlerBase.java
+++ b/solr/core/src/java/org/apache/solr/handler/AnalysisRequestHandlerBase.java
@@ -31,6 +31,7 @@ import org.apache.lucene.util.AttributeSource;
import org.apache.lucene.util.AttributeReflector;
import org.apache.lucene.util.CharsRef;
import org.apache.lucene.util.ArrayUtil;
+import org.apache.lucene.util.CharsRefBuilder;
import org.apache.lucene.util.IOUtils;
import org.apache.solr.analysis.TokenizerChain;
import org.apache.solr.common.util.NamedList;
@@ -44,6 +45,7 @@ import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.*;
+
import org.apache.commons.lang.ArrayUtils;
/**
@@ -245,7 +247,7 @@ public abstract class AnalysisRequestHandlerBase extends RequestHandlerBase {
final TermToBytesRefAttribute termAtt = token.getAttribute(TermToBytesRefAttribute.class);
BytesRef rawBytes = termAtt.getBytesRef();
termAtt.fillBytesRef();
- final String text = fieldType.indexedToReadable(rawBytes, new CharsRef(rawBytes.length)).toString();
+ final String text = fieldType.indexedToReadable(rawBytes, new CharsRefBuilder()).toString();
tokenNamedList.add("text", text);
if (token.hasAttribute(CharTermAttribute.class)) {
diff --git a/solr/core/src/java/org/apache/solr/handler/admin/LukeRequestHandler.java b/solr/core/src/java/org/apache/solr/handler/admin/LukeRequestHandler.java
index 19ac2937dde..ed4dfd1cb15 100644
--- a/solr/core/src/java/org/apache/solr/handler/admin/LukeRequestHandler.java
+++ b/solr/core/src/java/org/apache/solr/handler/admin/LukeRequestHandler.java
@@ -34,6 +34,7 @@ import org.apache.lucene.search.similarities.Similarity;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.CharsRef;
+import org.apache.lucene.util.CharsRefBuilder;
import org.apache.lucene.util.PriorityQueue;
import org.apache.lucene.util.UnicodeUtil;
import org.apache.solr.analysis.TokenizerChain;
@@ -249,7 +250,7 @@ public class LukeRequestHandler extends RequestHandlerBase
private static SimpleOrderedMap<Object> getDocumentFieldsInfo( StoredDocument doc, int docId, IndexReader reader,
IndexSchema schema ) throws IOException
{
- final CharsRef spare = new CharsRef();
+ final CharsRefBuilder spare = new CharsRefBuilder();
SimpleOrderedMap<Object> finfo = new SimpleOrderedMap<>();
for( Object o : doc.getFields() ) {
Field field = (Field)o;
@@ -286,7 +287,7 @@ public class LukeRequestHandler extends RequestHandlerBase
BytesRef text;
while((text = termsEnum.next()) != null) {
final int freq = (int) termsEnum.totalTermFreq();
- UnicodeUtil.UTF8toUTF16(text, spare);
+ spare.copyUTF8Bytes(text);
tfv.add(spare.toString(), freq);
}
f.add( "termVector", tfv );
@@ -594,7 +595,7 @@ public class LukeRequestHandler extends RequestHandlerBase
TopTermQueue tiq = new TopTermQueue(numTerms + 1); // Something to collect the top N terms in.
- final CharsRef spare = new CharsRef();
+ final CharsRefBuilder spare = new CharsRefBuilder();
Fields fields = MultiFields.getFields(req.getSearcher().getIndexReader());
@@ -615,7 +616,7 @@ public class LukeRequestHandler extends RequestHandlerBase
int slot = 32 - Integer.numberOfLeadingZeros(Math.max(0, freq - 1));
buckets[slot] = buckets[slot] + 1;
if (numTerms > 0 && freq > tiq.minFreq) {
- UnicodeUtil.UTF8toUTF16(text, spare);
+ spare.copyUTF8Bytes(text);
String t = spare.toString();
tiq.add(new TopTermQueue.TermInfo(new Term(field, t), termsEnum.docFreq()));
diff --git a/solr/core/src/java/org/apache/solr/handler/component/ExpandComponent.java b/solr/core/src/java/org/apache/solr/handler/component/ExpandComponent.java
index 19ef933c535..5781036bc66 100644
--- a/solr/core/src/java/org/apache/solr/handler/component/ExpandComponent.java
+++ b/solr/core/src/java/org/apache/solr/handler/component/ExpandComponent.java
@@ -22,6 +22,7 @@ import com.carrotsearch.hppc.IntObjectOpenHashMap;
import com.carrotsearch.hppc.IntOpenHashSet;
import com.carrotsearch.hppc.cursors.IntObjectCursor;
import com.carrotsearch.hppc.cursors.ObjectCursor;
+
import org.apache.lucene.index.AtomicReader;
import org.apache.lucene.index.AtomicReaderContext;
import org.apache.lucene.index.DocValues;
@@ -39,6 +40,7 @@ import org.apache.lucene.search.TopFieldCollector;
import org.apache.lucene.search.TopScoreDocCollector;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.CharsRef;
+import org.apache.lucene.util.CharsRefBuilder;
import org.apache.lucene.util.FixedBitSet;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.params.ExpandParams;
@@ -218,7 +220,7 @@ public class ExpandComponent extends SearchComponent implements PluginInfoInitia
searcher.search(query, pfilter.filter, collector);
IntObjectMap groups = groupExpandCollector.getGroups();
Map<String, DocSlice> outMap = new HashMap<>();
- CharsRef charsRef = new CharsRef();
+ CharsRefBuilder charsRef = new CharsRefBuilder();
FieldType fieldType = searcher.getSchema().getField(field).getType();
for (IntObjectCursor cursor : (Iterable<IntObjectCursor>) groups) {
int ord = cursor.key;
diff --git a/solr/core/src/java/org/apache/solr/handler/component/PivotFacetHelper.java b/solr/core/src/java/org/apache/solr/handler/component/PivotFacetHelper.java
index 07f3c16c1e6..262e46db850 100644
--- a/solr/core/src/java/org/apache/solr/handler/component/PivotFacetHelper.java
+++ b/solr/core/src/java/org/apache/solr/handler/component/PivotFacetHelper.java
@@ -17,32 +17,32 @@
package org.apache.solr.handler.component;
-import org.apache.lucene.util.BytesRef;
-import org.apache.solr.schema.SchemaField;
-import org.apache.solr.search.SolrIndexSearcher;
-import org.apache.solr.search.DocSet;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Deque;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.lucene.index.Term;
+import org.apache.lucene.search.Query;
+import org.apache.lucene.search.TermQuery;
+import org.apache.lucene.search.TermRangeQuery;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.solr.common.SolrException;
-import org.apache.solr.common.util.NamedList;
-import org.apache.solr.common.util.SimpleOrderedMap;
import org.apache.solr.common.SolrException.ErrorCode;
-import org.apache.solr.common.params.SolrParams;
import org.apache.solr.common.params.FacetParams;
+import org.apache.solr.common.params.SolrParams;
+import org.apache.solr.common.util.NamedList;
+import org.apache.solr.common.util.SimpleOrderedMap;
import org.apache.solr.request.SimpleFacets;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.schema.FieldType;
-import org.apache.lucene.search.Query;
-import org.apache.lucene.search.TermQuery;
-import org.apache.lucene.search.TermRangeQuery;
-import org.apache.lucene.index.Term;
+import org.apache.solr.schema.SchemaField;
+import org.apache.solr.search.DocSet;
+import org.apache.solr.search.SolrIndexSearcher;
import org.apache.solr.search.SyntaxError;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Deque;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-
/**
* @since solr 4.0
*/
@@ -116,16 +116,16 @@ public class PivotFacetHelper extends SimpleFacets
// don't reuse the same BytesRef each time since we will be
// constructing Term objects used in TermQueries that may be cached.
- BytesRef termval = null;
+ BytesRefBuilder termval = null;
SimpleOrderedMap<Object> pivot = new SimpleOrderedMap<>();
pivot.add( "field", field );
if (null == fieldValue) {
pivot.add( "value", null );
} else {
- termval = new BytesRef();
+ termval = new BytesRefBuilder();
ftype.readableToIndexed(fieldValue, termval);
- pivot.add( "value", ftype.toObject(sfield, termval) );
+ pivot.add( "value", ftype.toObject(sfield, termval.get()) );
}
pivot.add( "count", kv.getValue() );
@@ -139,7 +139,7 @@ public class PivotFacetHelper extends SimpleFacets
(new TermRangeQuery(field, null, null, false, false));
subset = docs.andNot(hasVal);
} else {
- Query query = new TermQuery(new Term(field, termval));
+ Query query = new TermQuery(new Term(field, termval.get()));
subset = searcher.getDocSet(query, docs);
}
super.docs = subset;//used by getTermCounts()
diff --git a/solr/core/src/java/org/apache/solr/handler/component/QueryElevationComponent.java b/solr/core/src/java/org/apache/solr/handler/component/QueryElevationComponent.java
index c2592a04ceb..246b9c7f202 100644
--- a/solr/core/src/java/org/apache/solr/handler/component/QueryElevationComponent.java
+++ b/solr/core/src/java/org/apache/solr/handler/component/QueryElevationComponent.java
@@ -19,6 +19,7 @@ package org.apache.solr.handler.component;
import com.carrotsearch.hppc.IntOpenHashSet;
import com.carrotsearch.hppc.IntIntOpenHashMap;
+
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
@@ -41,6 +42,7 @@ import org.apache.lucene.search.SortField;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.SentinelIntSet;
import org.apache.solr.cloud.ZkController;
import org.apache.solr.common.SolrException;
@@ -74,6 +76,7 @@ import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
+
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
@@ -681,17 +684,17 @@ public class QueryElevationComponent extends SearchComponent implements SolrCore
Terms terms = fields.terms(idField);
if (terms == null) return this;
termsEnum = terms.iterator(termsEnum);
- BytesRef term = new BytesRef();
+ BytesRefBuilder term = new BytesRefBuilder();
Bits liveDocs = context.reader().getLiveDocs();
for (String id : elevations.ids) {
term.copyChars(id);
- if (seen.contains(id) == false && termsEnum.seekExact(term)) {
+ if (seen.contains(id) == false && termsEnum.seekExact(term.get())) {
docsEnum = termsEnum.docs(liveDocs, docsEnum, DocsEnum.FLAG_NONE);
if (docsEnum != null) {
int docId = docsEnum.nextDoc();
if (docId == DocIdSetIterator.NO_MORE_DOCS ) continue; // must have been deleted
- termValues[ordSet.put(docId)] = BytesRef.deepCopyOf(term);
+ termValues[ordSet.put(docId)] = term.toBytesRef();
seen.add(id);
assert docsEnum.nextDoc() == DocIdSetIterator.NO_MORE_DOCS;
}
diff --git a/solr/core/src/java/org/apache/solr/handler/component/RealTimeGetComponent.java b/solr/core/src/java/org/apache/solr/handler/component/RealTimeGetComponent.java
index 0d60807e549..0710f6c9bfa 100644
--- a/solr/core/src/java/org/apache/solr/handler/component/RealTimeGetComponent.java
+++ b/solr/core/src/java/org/apache/solr/handler/component/RealTimeGetComponent.java
@@ -30,6 +30,7 @@ import org.apache.lucene.index.StorableField;
import org.apache.lucene.index.StoredDocument;
import org.apache.lucene.index.Term;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.solr.client.solrj.SolrResponse;
import org.apache.solr.cloud.CloudDescriptor;
import org.apache.solr.cloud.ZkController;
@@ -139,11 +140,11 @@ public class RealTimeGetComponent extends SearchComponent
try {
SolrIndexSearcher searcher = null;
- BytesRef idBytes = new BytesRef();
+ BytesRefBuilder idBytes = new BytesRefBuilder();
for (String idStr : allIds) {
fieldType.readableToIndexed(idStr, idBytes);
if (ulog != null) {
- Object o = ulog.lookup(idBytes);
+ Object o = ulog.lookup(idBytes.get());
if (o != null) {
// should currently be a List<Oper,Ver,Doc/Id>
List entry = (List)o;
@@ -174,7 +175,7 @@ public class RealTimeGetComponent extends SearchComponent
// SolrCore.verbose("RealTimeGet using searcher ", searcher);
- int docid = searcher.getFirstMatch(new Term(idField.getName(), idBytes));
+ int docid = searcher.getFirstMatch(new Term(idField.getName(), idBytes.get()));
if (docid < 0) continue;
StoredDocument luceneDocument = searcher.doc(docid);
SolrDocument doc = toSolrDoc(luceneDocument, core.getLatestSchema());
diff --git a/solr/core/src/java/org/apache/solr/handler/component/TermsComponent.java b/solr/core/src/java/org/apache/solr/handler/component/TermsComponent.java
index 339de148f2d..ae6c92745d4 100644
--- a/solr/core/src/java/org/apache/solr/handler/component/TermsComponent.java
+++ b/solr/core/src/java/org/apache/solr/handler/component/TermsComponent.java
@@ -18,7 +18,9 @@ package org.apache.solr.handler.component;
import org.apache.lucene.index.*;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.CharsRef;
+import org.apache.lucene.util.CharsRefBuilder;
import org.apache.lucene.util.StringHelper;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.params.*;
@@ -29,7 +31,6 @@ import org.apache.solr.schema.FieldType;
import org.apache.solr.schema.StrField;
import org.apache.solr.request.SimpleFacets.CountPair;
import org.apache.solr.util.BoundedTreeSet;
-
import org.apache.solr.client.solrj.response.TermsResponse;
import java.io.IOException;
@@ -138,8 +139,9 @@ public class TermsComponent extends SearchComponent {
BytesRef upperBytes = null;
if (upperStr != null) {
- upperBytes = new BytesRef();
- ft.readableToIndexed(upperStr, upperBytes);
+ BytesRefBuilder b = new BytesRefBuilder();
+ ft.readableToIndexed(upperStr, b);
+ upperBytes = b.get();
}
BytesRef lowerBytes;
@@ -153,8 +155,9 @@ public class TermsComponent extends SearchComponent {
// perhaps we detect if the FieldType is non-character and expect hex if so?
lowerBytes = new BytesRef(lowerStr);
} else {
- lowerBytes = new BytesRef();
- ft.readableToIndexed(lowerStr, lowerBytes);
+ BytesRefBuilder b = new BytesRefBuilder();
+ ft.readableToIndexed(lowerStr, b);
+ lowerBytes = b.get();
}
}
@@ -179,7 +182,7 @@ public class TermsComponent extends SearchComponent {
int i = 0;
BoundedTreeSet<CountPair<BytesRef, Integer>> queue = (sort ? new BoundedTreeSet<CountPair<BytesRef, Integer>>(limit) : null);
- CharsRef external = new CharsRef();
+ CharsRefBuilder external = new CharsRefBuilder();
while (term != null && (i<limit || sort)) {
boolean externalized = false; // did we fill in "external" yet for this term?
@@ -191,7 +194,7 @@ public class TermsComponent extends SearchComponent {
// TODO: support "raw" mode?
ft.indexedToReadable(term, external);
externalized = true;
- if (!pattern.matcher(external).matches()) {
+ if (!pattern.matcher(external.get()).matches()) {
term = termsEnum.next();
continue;
}
diff --git a/solr/core/src/java/org/apache/solr/request/DocValuesFacets.java b/solr/core/src/java/org/apache/solr/request/DocValuesFacets.java
index 81d1220406e..2a70e85e2c9 100644
--- a/solr/core/src/java/org/apache/solr/request/DocValuesFacets.java
+++ b/solr/core/src/java/org/apache/solr/request/DocValuesFacets.java
@@ -31,7 +31,9 @@ import org.apache.lucene.search.DocIdSet;
import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.search.Filter;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.CharsRef;
+import org.apache.lucene.util.CharsRefBuilder;
import org.apache.lucene.util.LongValues;
import org.apache.lucene.util.UnicodeUtil;
import org.apache.solr.common.params.FacetParams;
@@ -86,22 +88,23 @@ public class DocValuesFacets {
throw new UnsupportedOperationException("Currently this faceting method is limited to " + Integer.MAX_VALUE + " unique terms");
}
- final BytesRef prefixRef;
+ final BytesRefBuilder prefixRef;
if (prefix == null) {
prefixRef = null;
} else if (prefix.length()==0) {
prefix = null;
prefixRef = null;
} else {
- prefixRef = new BytesRef(prefix);
+ prefixRef = new BytesRefBuilder();
+ prefixRef.copyChars(prefix);
}
int startTermIndex, endTermIndex;
if (prefix!=null) {
- startTermIndex = (int) si.lookupTerm(prefixRef);
+ startTermIndex = (int) si.lookupTerm(prefixRef.get());
if (startTermIndex<0) startTermIndex=-startTermIndex-1;
prefixRef.append(UnicodeUtil.BIG_TERM);
- endTermIndex = (int) si.lookupTerm(prefixRef);
+ endTermIndex = (int) si.lookupTerm(prefixRef.get());
assert endTermIndex < 0;
endTermIndex = -endTermIndex-1;
} else {
@@ -111,7 +114,7 @@ public class DocValuesFacets {
final int nTerms=endTermIndex-startTermIndex;
int missingCount = -1;
- final CharsRef charsRef = new CharsRef(10);
+ final CharsRefBuilder charsRef = new CharsRefBuilder();
if (nTerms>0 && docs.size() >= mincount) {
// count collection array only needs to be as big as the number of terms we are
diff --git a/solr/core/src/java/org/apache/solr/request/NumericFacets.java b/solr/core/src/java/org/apache/solr/request/NumericFacets.java
index 2f2dd7d2a85..bf07e1c91ba 100644
--- a/solr/core/src/java/org/apache/solr/request/NumericFacets.java
+++ b/solr/core/src/java/org/apache/solr/request/NumericFacets.java
@@ -40,6 +40,7 @@ import org.apache.lucene.queries.function.ValueSource;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.CharsRef;
+import org.apache.lucene.util.CharsRefBuilder;
import org.apache.lucene.util.PriorityQueue;
import org.apache.lucene.util.StringHelper;
import org.apache.solr.common.params.FacetParams;
@@ -290,7 +291,7 @@ final class NumericFacets {
default:
throw new AssertionError();
}
- final CharsRef spare = new CharsRef();
+ final CharsRefBuilder spare = new CharsRefBuilder();
for (int skipped = hashTable.size; skipped < offset && term != null && StringHelper.startsWith(term, prefix); ) {
ft.indexedToReadable(term, spare);
final String termStr = spare.toString();
@@ -343,7 +344,7 @@ final class NumericFacets {
default:
throw new AssertionError();
}
- final CharsRef spare = new CharsRef();
+ final CharsRefBuilder spare = new CharsRefBuilder();
for (int i = 0; i < offset && term != null && StringHelper.startsWith(term, prefix); ++i) {
term = termsEnum.next();
}
diff --git a/solr/core/src/java/org/apache/solr/request/PerSegmentSingleValuedFaceting.java b/solr/core/src/java/org/apache/solr/request/PerSegmentSingleValuedFaceting.java
index 5caf34baabb..dcd565d972e 100644
--- a/solr/core/src/java/org/apache/solr/request/PerSegmentSingleValuedFaceting.java
+++ b/solr/core/src/java/org/apache/solr/request/PerSegmentSingleValuedFaceting.java
@@ -29,7 +29,9 @@ import org.apache.lucene.search.DocIdSet;
import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.search.Filter;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.CharsRef;
+import org.apache.lucene.util.CharsRefBuilder;
import org.apache.lucene.util.PriorityQueue;
import org.apache.lucene.util.UnicodeUtil;
import org.apache.lucene.util.packed.PackedInts;
@@ -169,7 +171,7 @@ class PerSegmentSingleValuedFaceting {
collector = new IndexSortedFacetCollector(offset, limit, mincount);
}
- BytesRef val = new BytesRef();
+ BytesRefBuilder val = new BytesRefBuilder();
while (queue.size() > 0) {
SegFacet seg = queue.top();
@@ -194,9 +196,9 @@ class PerSegmentSingleValuedFaceting {
seg.tempBR = seg.tenum.next();
seg = queue.updateTop();
}
- } while (seg != null && val.compareTo(seg.tempBR) == 0);
+ } while (seg != null && val.get().compareTo(seg.tempBR) == 0);
- boolean stop = collector.collect(val, count);
+ boolean stop = collector.collect(val.get(), count);
if (stop) break;
}
@@ -240,12 +242,13 @@ class PerSegmentSingleValuedFaceting {
// SolrCore.log.info("reader= " + reader + " FC=" + System.identityHashCode(si));
if (prefix!=null) {
- BytesRef prefixRef = new BytesRef(prefix);
- startTermIndex = si.lookupTerm(prefixRef);
+ BytesRefBuilder prefixRef = new BytesRefBuilder();
+ prefixRef.copyChars(prefix);
+ startTermIndex = si.lookupTerm(prefixRef.get());
if (startTermIndex<0) startTermIndex=-startTermIndex-1;
prefixRef.append(UnicodeUtil.BIG_TERM);
// TODO: we could constrain the lower endpoint if we had a binarySearch method that allowed passing start/end
- endTermIndex = si.lookupTerm(prefixRef);
+ endTermIndex = si.lookupTerm(prefixRef.get());
assert endTermIndex < 0;
endTermIndex = -endTermIndex-1;
} else {
@@ -295,7 +298,7 @@ abstract class FacetCollector {
// This collector expects facets to be collected in index order
class CountSortedFacetCollector extends FacetCollector {
- private final CharsRef spare = new CharsRef();
+ private final CharsRefBuilder spare = new CharsRefBuilder();
final int offset;
final int limit;
@@ -318,7 +321,7 @@ class CountSortedFacetCollector extends FacetCollector {
// NOTE: we use c>min rather than c>=min as an optimization because we are going in
// index order, so we already know that the keys are ordered. This can be very
// important if a lot of the counts are repeated (like zero counts would be).
- UnicodeUtil.UTF8toUTF16(term, spare);
+ spare.copyUTF8Bytes(term);
queue.add(new SimpleFacets.CountPair<>(spare.toString(), count));
if (queue.size()>=maxsize) min=queue.last().val;
}
@@ -342,7 +345,7 @@ class CountSortedFacetCollector extends FacetCollector {
// This collector expects facets to be collected in index order
class IndexSortedFacetCollector extends FacetCollector {
- private final CharsRef spare = new CharsRef();
+ private final CharsRefBuilder spare = new CharsRefBuilder();
int offset;
int limit;
@@ -367,7 +370,7 @@ class IndexSortedFacetCollector extends FacetCollector {
}
if (limit > 0) {
- UnicodeUtil.UTF8toUTF16(term, spare);
+ spare.copyUTF8Bytes(term);
res.add(spare.toString(), count);
limit--;
}
diff --git a/solr/core/src/java/org/apache/solr/request/SimpleFacets.java b/solr/core/src/java/org/apache/solr/request/SimpleFacets.java
index 4379a78510d..72932242c8b 100644
--- a/solr/core/src/java/org/apache/solr/request/SimpleFacets.java
+++ b/solr/core/src/java/org/apache/solr/request/SimpleFacets.java
@@ -58,6 +58,7 @@ import org.apache.lucene.search.grouping.term.TermAllGroupsCollector;
import org.apache.lucene.search.grouping.term.TermGroupFacetCollector;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.CharsRef;
+import org.apache.lucene.util.CharsRefBuilder;
import org.apache.lucene.util.StringHelper;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.SolrException.ErrorCode;
@@ -480,7 +481,7 @@ public class SimpleFacets {
(offset + limit),
mincount, orderByCount);
- CharsRef charsRef = new CharsRef();
+ CharsRefBuilder charsRef = new CharsRefBuilder();
FieldType facetFieldType = searcher.getSchema().getFieldType(field);
NamedList<Integer> facetCounts = new NamedList<>();
List<TermGroupFacetCollector.FacetEntry> scopedEntries
@@ -699,7 +700,7 @@ public class SimpleFacets {
}
DocsEnum docsEnum = null;
- CharsRef charsRef = new CharsRef(10);
+ CharsRefBuilder charsRef = new CharsRefBuilder();
if (docs.size() >= mincount) {
while (term != null) {
diff --git a/solr/core/src/java/org/apache/solr/request/UnInvertedField.java b/solr/core/src/java/org/apache/solr/request/UnInvertedField.java
index 9f9e9f0bb05..3e771e5a495 100644
--- a/solr/core/src/java/org/apache/solr/request/UnInvertedField.java
+++ b/solr/core/src/java/org/apache/solr/request/UnInvertedField.java
@@ -30,7 +30,9 @@ import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TermRangeQuery;
import org.apache.lucene.uninverting.DocTermOrds;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.CharsRef;
+import org.apache.lucene.util.CharsRefBuilder;
import org.apache.lucene.util.FixedBitSet;
import org.apache.lucene.util.UnicodeUtil;
import org.apache.solr.common.SolrException;
@@ -239,14 +241,15 @@ public class UnInvertedField extends DocTermOrds {
TermsEnum te = getOrdTermsEnum(searcher.getAtomicReader());
if (te != null && prefix != null && prefix.length() > 0) {
- final BytesRef prefixBr = new BytesRef(prefix);
- if (te.seekCeil(prefixBr) == TermsEnum.SeekStatus.END) {
+ final BytesRefBuilder prefixBr = new BytesRefBuilder();
+ prefixBr.copyChars(prefix);
+ if (te.seekCeil(prefixBr.get()) == TermsEnum.SeekStatus.END) {
startTerm = numTermsInField;
} else {
startTerm = (int) te.ord();
}
prefixBr.append(UnicodeUtil.BIG_TERM);
- if (te.seekCeil(prefixBr) == TermsEnum.SeekStatus.END) {
+ if (te.seekCeil(prefixBr.get()) == TermsEnum.SeekStatus.END) {
endTerm = numTermsInField;
} else {
endTerm = (int) te.ord();
@@ -343,7 +346,7 @@ public class UnInvertedField extends DocTermOrds {
}
}
}
- final CharsRef charsRef = new CharsRef();
+ final CharsRefBuilder charsRef = new CharsRefBuilder();
int off=offset;
int lim=limit>=0 ? limit : Integer.MAX_VALUE;
@@ -623,7 +626,7 @@ public class UnInvertedField extends DocTermOrds {
}
- String getReadableValue(BytesRef termval, FieldType ft, CharsRef charsRef) {
+ String getReadableValue(BytesRef termval, FieldType ft, CharsRefBuilder charsRef) {
return ft.indexedToReadable(termval, charsRef).toString();
}
diff --git a/solr/core/src/java/org/apache/solr/response/PHPSerializedResponseWriter.java b/solr/core/src/java/org/apache/solr/response/PHPSerializedResponseWriter.java
index ba1933a3c5b..191699dc1a9 100644
--- a/solr/core/src/java/org/apache/solr/response/PHPSerializedResponseWriter.java
+++ b/solr/core/src/java/org/apache/solr/response/PHPSerializedResponseWriter.java
@@ -24,6 +24,7 @@ import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;
+import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.UnicodeUtil;
import org.apache.solr.common.SolrDocument;
@@ -68,11 +69,11 @@ public class PHPSerializedResponseWriter implements QueryResponseWriter {
}
class PHPSerializedWriter extends JSONWriter {
- final BytesRef utf8;
+ byte[] utf8;
public PHPSerializedWriter(Writer writer, SolrQueryRequest req, SolrQueryResponse rsp) {
super(writer, req, rsp);
- this.utf8 = new BytesRef();
+ this.utf8 = BytesRef.EMPTY_BYTES;
// never indent serialized PHP data
doIndent = false;
}
@@ -267,8 +268,8 @@ class PHPSerializedWriter extends JSONWriter {
public void writeStr(String name, String val, boolean needsEscaping) throws IOException {
// serialized PHP strings don't need to be escaped at all, however the
// string size reported needs be the number of bytes rather than chars.
- UnicodeUtil.UTF16toUTF8(val, 0, val.length(), utf8);
- int nBytes = utf8.length;
+ utf8 = ArrayUtil.grow(utf8, val.length() * UnicodeUtil.MAX_UTF8_BYTES_PER_CHAR);
+ final int nBytes = UnicodeUtil.UTF16toUTF8(val, 0, val.length(), utf8);
writer.write("s:");
writer.write(Integer.toString(nBytes));
diff --git a/solr/core/src/java/org/apache/solr/schema/BoolField.java b/solr/core/src/java/org/apache/solr/schema/BoolField.java
index a5d0e7bcb44..81bc0639b72 100644
--- a/solr/core/src/java/org/apache/solr/schema/BoolField.java
+++ b/solr/core/src/java/org/apache/solr/schema/BoolField.java
@@ -36,6 +36,7 @@ import org.apache.lucene.search.SortField;
import org.apache.lucene.uninverting.UninvertingReader.Type;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.CharsRef;
+import org.apache.lucene.util.CharsRefBuilder;
import org.apache.lucene.util.mutable.MutableValue;
import org.apache.lucene.util.mutable.MutableValueBool;
import org.apache.solr.analysis.SolrAnalyzer;
@@ -148,13 +149,13 @@ public class BoolField extends PrimitiveFieldType {
private static final CharsRef FALSE = new CharsRef("false");
@Override
- public CharsRef indexedToReadable(BytesRef input, CharsRef charsRef) {
+ public CharsRef indexedToReadable(BytesRef input, CharsRefBuilder charsRef) {
if (input.length > 0 && input.bytes[input.offset] == 'T') {
charsRef.copyChars(TRUE);
} else {
charsRef.copyChars(FALSE);
}
- return charsRef;
+ return charsRef.get();
}
@Override
diff --git a/solr/core/src/java/org/apache/solr/schema/EnumField.java b/solr/core/src/java/org/apache/solr/schema/EnumField.java
index d46d1faf5b2..786fe4f169e 100644
--- a/solr/core/src/java/org/apache/solr/schema/EnumField.java
+++ b/solr/core/src/java/org/apache/solr/schema/EnumField.java
@@ -24,7 +24,9 @@ import org.apache.lucene.queries.function.valuesource.EnumFieldSource;
import org.apache.lucene.search.*;
import org.apache.lucene.uninverting.UninvertingReader.Type;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.CharsRef;
+import org.apache.lucene.util.CharsRefBuilder;
import org.apache.lucene.util.NumericUtils;
import org.apache.solr.common.EnumFieldValue;
import org.apache.solr.common.SolrException;
@@ -43,9 +45,9 @@ import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
+
import java.io.IOException;
import java.io.InputStream;
-
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
@@ -272,16 +274,16 @@ public class EnumField extends PrimitiveFieldType {
if (val == null)
return null;
- final BytesRef bytes = new BytesRef(NumericUtils.BUF_SIZE_LONG);
+ final BytesRefBuilder bytes = new BytesRefBuilder();
readableToIndexed(val, bytes);
- return bytes.utf8ToString();
+ return bytes.get().utf8ToString();
}
/**
* {@inheritDoc}
*/
@Override
- public void readableToIndexed(CharSequence val, BytesRef result) {
+ public void readableToIndexed(CharSequence val, BytesRefBuilder result) {
final String s = val.toString();
if (s == null)
return;
@@ -326,13 +328,13 @@ public class EnumField extends PrimitiveFieldType {
* {@inheritDoc}
*/
@Override
- public CharsRef indexedToReadable(BytesRef input, CharsRef output) {
+ public CharsRef indexedToReadable(BytesRef input, CharsRefBuilder output) {
final Integer intValue = NumericUtils.prefixCodedToInt(input);
final String stringValue = intValueToStringValue(intValue);
output.grow(stringValue.length());
- output.length = stringValue.length();
- stringValue.getChars(0, output.length, output.chars, 0);
- return output;
+ output.setLength(stringValue.length());
+ stringValue.getChars(0, output.length(), output.chars(), 0);
+ return output.get();
}
/**
@@ -353,9 +355,9 @@ public class EnumField extends PrimitiveFieldType {
final Number val = f.numericValue();
if (val == null)
return null;
- final BytesRef bytes = new BytesRef(NumericUtils.BUF_SIZE_LONG);
+ final BytesRefBuilder bytes = new BytesRefBuilder();
NumericUtils.intToPrefixCoded(val.intValue(), 0, bytes);
- return bytes.utf8ToString();
+ return bytes.get().utf8ToString();
}
/**
diff --git a/solr/core/src/java/org/apache/solr/schema/FieldType.java b/solr/core/src/java/org/apache/solr/schema/FieldType.java
index 1927e38d0b2..337269b4b6c 100644
--- a/solr/core/src/java/org/apache/solr/schema/FieldType.java
+++ b/solr/core/src/java/org/apache/solr/schema/FieldType.java
@@ -43,7 +43,9 @@ import org.apache.lucene.search.TermRangeQuery;
import org.apache.lucene.search.similarities.Similarity;
import org.apache.lucene.uninverting.UninvertingReader;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.CharsRef;
+import org.apache.lucene.util.CharsRefBuilder;
import org.apache.lucene.util.UnicodeUtil;
import org.apache.solr.analysis.SolrAnalyzer;
import org.apache.solr.analysis.TokenizerChain;
@@ -358,7 +360,7 @@ public abstract class FieldType extends FieldProperties {
}
public Object toObject(SchemaField sf, BytesRef term) {
- final CharsRef ref = new CharsRef(term.length);
+ final CharsRefBuilder ref = new CharsRefBuilder();
indexedToReadable(term, ref);
final StorableField f = createField(sf, ref.toString(), 1.0f);
return toObject(f);
@@ -370,9 +372,9 @@ public abstract class FieldType extends FieldProperties {
}
/** Given an indexed term, append the human readable representation*/
- public CharsRef indexedToReadable(BytesRef input, CharsRef output) {
- UnicodeUtil.UTF8toUTF16(input, output);
- return output;
+ public CharsRef indexedToReadable(BytesRef input, CharsRefBuilder output) {
+ output.copyUTF8Bytes(input);
+ return output.get();
}
/** Given the stored field, return the human readable representation */
@@ -394,9 +396,9 @@ public abstract class FieldType extends FieldProperties {
}
/** Given the readable value, return the term value that will match it. */
- public void readableToIndexed(CharSequence val, BytesRef result) {
+ public void readableToIndexed(CharSequence val, BytesRefBuilder result) {
final String internal = readableToIndexed(val.toString());
- UnicodeUtil.UTF16toUTF8(internal, 0, internal.length(), result);
+ result.copyChars(internal);
}
public void setIsExplicitQueryAnalyzer(boolean isExplicitQueryAnalyzer) {
@@ -724,13 +726,13 @@ public abstract class FieldType extends FieldProperties {
*
*/
public Query getFieldQuery(QParser parser, SchemaField field, String externalVal) {
- BytesRef br = new BytesRef();
+ BytesRefBuilder br = new BytesRefBuilder();
readableToIndexed(externalVal, br);
if (field.hasDocValues() && !field.indexed()) {
// match-only
return getRangeQuery(parser, field, externalVal, externalVal, true, true);
} else {
- return new TermQuery(new Term(field.getName(), br));
+ return new TermQuery(new Term(field.getName(), br.toBytesRef()));
}
}
@@ -986,8 +988,8 @@ public abstract class FieldType extends FieldProperties {
if (null == value) {
return null;
}
- CharsRef spare = new CharsRef();
- UnicodeUtil.UTF8toUTF16((BytesRef)value, spare);
+ CharsRefBuilder spare = new CharsRefBuilder();
+ spare.copyUTF8Bytes((BytesRef)value);
return spare.toString();
}
@@ -998,10 +1000,10 @@ public abstract class FieldType extends FieldProperties {
if (null == value) {
return null;
}
- BytesRef spare = new BytesRef();
+ BytesRefBuilder spare = new BytesRefBuilder();
String stringVal = (String)value;
- UnicodeUtil.UTF16toUTF8(stringVal, 0, stringVal.length(), spare);
- return spare;
+ spare.copyChars(stringVal);
+ return spare.get();
}
/**
diff --git a/solr/core/src/java/org/apache/solr/schema/TrieField.java b/solr/core/src/java/org/apache/solr/schema/TrieField.java
index 165d946cad5..7cfd0cfcf5d 100644
--- a/solr/core/src/java/org/apache/solr/schema/TrieField.java
+++ b/solr/core/src/java/org/apache/solr/schema/TrieField.java
@@ -45,7 +45,9 @@ import org.apache.lucene.search.Query;
import org.apache.lucene.search.SortField;
import org.apache.lucene.uninverting.UninvertingReader.Type;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.CharsRef;
+import org.apache.lucene.util.CharsRefBuilder;
import org.apache.lucene.util.NumericUtils;
import org.apache.lucene.util.mutable.MutableValueDate;
import org.apache.lucene.util.mutable.MutableValueLong;
@@ -407,13 +409,13 @@ public class TrieField extends PrimitiveFieldType {
@Override
public String readableToIndexed(String val) {
// TODO: Numeric should never be handled as String, that may break in future lucene versions! Change to use BytesRef for term texts!
- final BytesRef bytes = new BytesRef(NumericUtils.BUF_SIZE_LONG);
+ final BytesRefBuilder bytes = new BytesRefBuilder();
readableToIndexed(val, bytes);
- return bytes.utf8ToString();
+ return bytes.get().utf8ToString();
}
@Override
- public void readableToIndexed(CharSequence val, BytesRef result) {
+ public void readableToIndexed(CharSequence val, BytesRefBuilder result) {
String s = val.toString();
try {
switch (type) {
@@ -478,7 +480,7 @@ public class TrieField extends PrimitiveFieldType {
}
@Override
- public CharsRef indexedToReadable(BytesRef indexedForm, CharsRef charsRef) {
+ public CharsRef indexedToReadable(BytesRef indexedForm, CharsRefBuilder charsRef) {
final String value;
switch (type) {
case INTEGER:
@@ -500,9 +502,9 @@ public class TrieField extends PrimitiveFieldType {
throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Unknown type for trie field: " + type);
}
charsRef.grow(value.length());
- charsRef.length = value.length();
- value.getChars(0, charsRef.length, charsRef.chars, 0);
- return charsRef;
+ charsRef.setLength(value.length());
+ value.getChars(0, charsRef.length(), charsRef.chars(), 0);
+ return charsRef.get();
}
@Override
@@ -525,7 +527,7 @@ public class TrieField extends PrimitiveFieldType {
@Override
public String storedToIndexed(StorableField f) {
- final BytesRef bytes = new BytesRef(NumericUtils.BUF_SIZE_LONG);
+ final BytesRefBuilder bytes = new BytesRefBuilder();
final Number val = f.numericValue();
if (val != null) {
switch (type) {
@@ -580,7 +582,7 @@ public class TrieField extends PrimitiveFieldType {
throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Unknown type for trie field: " + f.name());
}
}
- return bytes.utf8ToString();
+ return bytes.get().utf8ToString();
}
@Override
@@ -672,9 +674,9 @@ public class TrieField extends PrimitiveFieldType {
fields.add(field);
if (sf.multiValued()) {
- BytesRef bytes = new BytesRef();
+ BytesRefBuilder bytes = new BytesRefBuilder();
readableToIndexed(value.toString(), bytes);
- fields.add(new SortedSetDocValuesField(sf.getName(), bytes));
+ fields.add(new SortedSetDocValuesField(sf.getName(), bytes.get()));
} else {
final long bits;
if (field.numericValue() instanceof Integer || field.numericValue() instanceof Long) {
diff --git a/solr/core/src/java/org/apache/solr/search/CursorMark.java b/solr/core/src/java/org/apache/solr/search/CursorMark.java
index 13bdc937ee5..75c822c10b4 100644
--- a/solr/core/src/java/org/apache/solr/search/CursorMark.java
+++ b/solr/core/src/java/org/apache/solr/search/CursorMark.java
@@ -26,9 +26,12 @@ import org.apache.lucene.search.Sort;
import org.apache.lucene.search.SortField;
import org.apache.lucene.search.Query;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.SolrException.ErrorCode;
+
import static org.apache.solr.common.params.CursorMarkParams.*;
+
import org.apache.solr.common.util.Base64;
import org.apache.solr.common.util.JavaBinCodec;
import org.apache.solr.schema.IndexSchema;
@@ -200,6 +203,16 @@ public final class CursorMark {
ByteArrayInputStream in = new ByteArrayInputStream(rawData);
try {
pieces = (List<Object>) codec.unmarshal(in);
+ boolean b = false;
+ for (Object o : pieces) {
+ if (o instanceof BytesRefBuilder || o instanceof BytesRef || o instanceof String) {
+ b = true; break;
+ }
+ }
+ if (b) {
+ in.reset();
+ pieces = (List<Object>) codec.unmarshal(in);
+ }
} finally {
in.close();
}
diff --git a/solr/core/src/java/org/apache/solr/search/QueryParsing.java b/solr/core/src/java/org/apache/solr/search/QueryParsing.java
index 03389b4d14f..4fd12c13617 100644
--- a/solr/core/src/java/org/apache/solr/search/QueryParsing.java
+++ b/solr/core/src/java/org/apache/solr/search/QueryParsing.java
@@ -34,6 +34,7 @@ import org.apache.lucene.search.TermRangeQuery;
import org.apache.lucene.search.WildcardQuery;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.CharsRef;
+import org.apache.lucene.util.CharsRefBuilder;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.params.MapSolrParams;
import org.apache.solr.common.params.SolrParams;
@@ -42,6 +43,7 @@ import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.schema.FieldType;
import org.apache.solr.schema.IndexSchema;
import org.apache.solr.schema.SchemaField;
+
import java.io.IOException;
import java.util.Collections;
import java.util.ArrayList;
@@ -421,9 +423,9 @@ public class QueryParsing {
static void writeFieldVal(BytesRef val, FieldType ft, Appendable out, int flags) throws IOException {
if (ft != null) {
try {
- CharsRef readable = new CharsRef();
+ CharsRefBuilder readable = new CharsRefBuilder();
ft.indexedToReadable(val, readable);
- out.append(readable);
+ out.append(readable.get());
} catch (Exception e) {
out.append("EXCEPTION(val=");
out.append(val.utf8ToString());
diff --git a/solr/core/src/java/org/apache/solr/search/TermQParserPlugin.java b/solr/core/src/java/org/apache/solr/search/TermQParserPlugin.java
index 5b81943e947..27dd8c38b51 100644
--- a/solr/core/src/java/org/apache/solr/search/TermQParserPlugin.java
+++ b/solr/core/src/java/org/apache/solr/search/TermQParserPlugin.java
@@ -19,7 +19,7 @@ package org.apache.solr.search;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;
-import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.request.SolrQueryRequest;
@@ -55,13 +55,13 @@ public class TermQParserPlugin extends QParserPlugin {
String fname = localParams.get(QueryParsing.F);
FieldType ft = req.getSchema().getFieldTypeNoEx(fname);
String val = localParams.get(QueryParsing.V);
- BytesRef term = new BytesRef();
+ BytesRefBuilder term = new BytesRefBuilder();
if (ft != null) {
ft.readableToIndexed(val, term);
} else {
term.copyChars(val);
}
- return new TermQuery(new Term(fname, term));
+ return new TermQuery(new Term(fname, term.get()));
}
};
}
diff --git a/solr/core/src/java/org/apache/solr/search/TermsQParserPlugin.java b/solr/core/src/java/org/apache/solr/search/TermsQParserPlugin.java
index 3c8cb75b747..73ab4e688dc 100644
--- a/solr/core/src/java/org/apache/solr/search/TermsQParserPlugin.java
+++ b/solr/core/src/java/org/apache/solr/search/TermsQParserPlugin.java
@@ -29,6 +29,7 @@ import org.apache.lucene.search.Query;
import org.apache.lucene.search.QueryWrapperFilter;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.automaton.Automata;
import org.apache.lucene.util.automaton.Automaton;
import org.apache.solr.common.params.SolrParams;
@@ -121,16 +122,16 @@ public class TermsQParserPlugin extends QParserPlugin {
assert splitVals.length > 0;
BytesRef[] bytesRefs = new BytesRef[splitVals.length];
+ BytesRefBuilder term = new BytesRefBuilder();
for (int i = 0; i < splitVals.length; i++) {
String stringVal = splitVals[i];
//logic same as TermQParserPlugin
- BytesRef term = new BytesRef();
if (ft != null) {
ft.readableToIndexed(stringVal, term);
} else {
term.copyChars(stringVal);
}
- bytesRefs[i] = term;
+ bytesRefs[i] = term.toBytesRef();
}
return new SolrConstantScoreQuery(method.makeFilter(fname, bytesRefs));
diff --git a/solr/core/src/java/org/apache/solr/search/ValueSourceParser.java b/solr/core/src/java/org/apache/solr/search/ValueSourceParser.java
index 20531325d34..0ac1a42e243 100644
--- a/solr/core/src/java/org/apache/solr/search/ValueSourceParser.java
+++ b/solr/core/src/java/org/apache/solr/search/ValueSourceParser.java
@@ -17,6 +17,7 @@
package org.apache.solr.search;
import com.spatial4j.core.distance.DistanceUtils;
+
import org.apache.lucene.index.AtomicReaderContext;
import org.apache.lucene.index.Term;
import org.apache.lucene.queries.function.BoostedQuery;
@@ -35,12 +36,12 @@ import org.apache.lucene.search.spell.LevensteinDistance;
import org.apache.lucene.search.spell.NGramDistance;
import org.apache.lucene.search.spell.StringDistance;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.UnicodeUtil;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.request.SolrRequestInfo;
import org.apache.solr.schema.*;
-
import org.apache.solr.search.function.CollapseScoreFunction;
import org.apache.solr.search.function.OrdFieldSource;
import org.apache.solr.search.function.ReverseOrdFieldSource;
@@ -593,7 +594,7 @@ public abstract class ValueSourceParser implements NamedListInitializedPlugin {
@Override
public ValueSource parse(FunctionQParser fp) throws SyntaxError {
TInfo tinfo = parseTerm(fp);
- return new DocFreqValueSource(tinfo.field, tinfo.val, tinfo.indexedField, tinfo.indexedBytes);
+ return new DocFreqValueSource(tinfo.field, tinfo.val, tinfo.indexedField, tinfo.indexedBytes.get());
}
});
@@ -601,7 +602,7 @@ public abstract class ValueSourceParser implements NamedListInitializedPlugin {
@Override
public ValueSource parse(FunctionQParser fp) throws SyntaxError {
TInfo tinfo = parseTerm(fp);
- return new TotalTermFreqValueSource(tinfo.field, tinfo.val, tinfo.indexedField, tinfo.indexedBytes);
+ return new TotalTermFreqValueSource(tinfo.field, tinfo.val, tinfo.indexedField, tinfo.indexedBytes.get());
}
});
alias("totaltermfreq","ttf");
@@ -619,7 +620,7 @@ public abstract class ValueSourceParser implements NamedListInitializedPlugin {
@Override
public ValueSource parse(FunctionQParser fp) throws SyntaxError {
TInfo tinfo = parseTerm(fp);
- return new IDFValueSource(tinfo.field, tinfo.val, tinfo.indexedField, tinfo.indexedBytes);
+ return new IDFValueSource(tinfo.field, tinfo.val, tinfo.indexedField, tinfo.indexedBytes.get());
}
});
@@ -627,7 +628,7 @@ public abstract class ValueSourceParser implements NamedListInitializedPlugin {
@Override
public ValueSource parse(FunctionQParser fp) throws SyntaxError {
TInfo tinfo = parseTerm(fp);
- return new TermFreqValueSource(tinfo.field, tinfo.val, tinfo.indexedField, tinfo.indexedBytes);
+ return new TermFreqValueSource(tinfo.field, tinfo.val, tinfo.indexedField, tinfo.indexedBytes.get());
}
});
@@ -635,7 +636,7 @@ public abstract class ValueSourceParser implements NamedListInitializedPlugin {
@Override
public ValueSource parse(FunctionQParser fp) throws SyntaxError {
TInfo tinfo = parseTerm(fp);
- return new TFValueSource(tinfo.field, tinfo.val, tinfo.indexedField, tinfo.indexedBytes);
+ return new TFValueSource(tinfo.field, tinfo.val, tinfo.indexedField, tinfo.indexedBytes.get());
}
});
@@ -795,7 +796,7 @@ public abstract class ValueSourceParser implements NamedListInitializedPlugin {
tinfo.indexedField = tinfo.field = fp.parseArg();
tinfo.val = fp.parseArg();
- tinfo.indexedBytes = new BytesRef();
+ tinfo.indexedBytes = new BytesRefBuilder();
FieldType ft = fp.getReq().getSchema().getFieldTypeNoEx(tinfo.field);
if (ft == null) ft = new StrField();
@@ -809,7 +810,7 @@ public abstract class ValueSourceParser implements NamedListInitializedPlugin {
tinfo.indexedField = term.field();
indexedVal = term.text();
}
- UnicodeUtil.UTF16toUTF8(indexedVal, 0, indexedVal.length(), tinfo.indexedBytes);
+ tinfo.indexedBytes.copyChars(indexedVal);
} else {
ft.readableToIndexed(tinfo.val, tinfo.indexedBytes);
}
@@ -871,7 +872,7 @@ public abstract class ValueSourceParser implements NamedListInitializedPlugin {
String field;
String val;
String indexedField;
- BytesRef indexedBytes;
+ BytesRefBuilder indexedBytes;
}
}
diff --git a/solr/core/src/java/org/apache/solr/search/function/FileFloatSource.java b/solr/core/src/java/org/apache/solr/search/function/FileFloatSource.java
index 2570173f071..a86431076ba 100644
--- a/solr/core/src/java/org/apache/solr/search/function/FileFloatSource.java
+++ b/solr/core/src/java/org/apache/solr/search/function/FileFloatSource.java
@@ -22,6 +22,7 @@ import org.apache.lucene.queries.function.ValueSource;
import org.apache.lucene.queries.function.docvalues.FloatDocValues;
import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.solr.core.SolrCore;
import org.apache.solr.handler.RequestHandlerBase;
import org.apache.solr.handler.RequestHandlerUtils;
@@ -267,7 +268,7 @@ public class FileFloatSource extends ValueSource {
char delimiter='=';
- BytesRef internalKey = new BytesRef();
+ BytesRefBuilder internalKey = new BytesRefBuilder();
try {
TermsEnum termsEnum = MultiFields.getTerms(reader, idName).iterator(null);
@@ -297,7 +298,7 @@ public class FileFloatSource extends ValueSource {
continue; // go to next line in file.. leave values as default.
}
- if (!termsEnum.seekExact(internalKey)) {
+ if (!termsEnum.seekExact(internalKey.get())) {
if (notFoundCount<10) { // collect first 10 not found for logging
notFound.add(key);
}
diff --git a/solr/core/src/java/org/apache/solr/search/grouping/distributed/command/GroupConverter.java b/solr/core/src/java/org/apache/solr/search/grouping/distributed/command/GroupConverter.java
index 36294870181..e500ab76db3 100644
--- a/solr/core/src/java/org/apache/solr/search/grouping/distributed/command/GroupConverter.java
+++ b/solr/core/src/java/org/apache/solr/search/grouping/distributed/command/GroupConverter.java
@@ -26,6 +26,7 @@ import org.apache.lucene.search.grouping.GroupDocs;
import org.apache.lucene.search.grouping.SearchGroup;
import org.apache.lucene.search.grouping.TopGroups;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.mutable.MutableValue;
import org.apache.lucene.util.mutable.MutableValueDate;
import org.apache.lucene.util.mutable.MutableValueDouble;
@@ -53,9 +54,9 @@ class GroupConverter {
SearchGroup<BytesRef> converted = new SearchGroup<BytesRef>();
converted.sortValues = original.sortValues;
if (original.groupValue.exists) {
- BytesRef binary = new BytesRef();
+ BytesRefBuilder binary = new BytesRefBuilder();
fieldType.readableToIndexed(original.groupValue.toString(), binary);
- converted.groupValue = binary;
+ converted.groupValue = binary.get();
} else {
converted.groupValue = null;
}
@@ -146,9 +147,9 @@ class GroupConverter {
GroupDocs<MutableValue> original = values.groups[i];
final BytesRef groupValue;
if (original.groupValue.exists) {
- BytesRef binary = new BytesRef();
+ BytesRefBuilder binary = new BytesRefBuilder();
fieldType.readableToIndexed(original.groupValue.toString(), binary);
- groupValue = binary;
+ groupValue = binary.get();
} else {
groupValue = null;
}
diff --git a/solr/core/src/java/org/apache/solr/update/AddUpdateCommand.java b/solr/core/src/java/org/apache/solr/update/AddUpdateCommand.java
index 607ed34d94f..a00cccb600c 100644
--- a/solr/core/src/java/org/apache/solr/update/AddUpdateCommand.java
+++ b/solr/core/src/java/org/apache/solr/update/AddUpdateCommand.java
@@ -25,6 +25,7 @@ import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexDocument;
import org.apache.lucene.index.Term;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.SolrInputField;
@@ -95,8 +96,9 @@ public class AddUpdateCommand extends UpdateCommand implements Iterable<IndexDoc
} else if (count > 1) {
throw new SolrException( SolrException.ErrorCode.BAD_REQUEST,"Document contains multiple values for uniqueKey field: " + field);
} else {
- indexedId = new BytesRef();
- sf.getType().readableToIndexed(field.getFirstValue().toString(), indexedId);
+ BytesRefBuilder b = new BytesRefBuilder();
+ sf.getType().readableToIndexed(field.getFirstValue().toString(), b);
+ indexedId = b.get();
}
}
}
diff --git a/solr/core/src/java/org/apache/solr/update/DeleteUpdateCommand.java b/solr/core/src/java/org/apache/solr/update/DeleteUpdateCommand.java
index 50bcaf7a5d7..8db9693a2f7 100644
--- a/solr/core/src/java/org/apache/solr/update/DeleteUpdateCommand.java
+++ b/solr/core/src/java/org/apache/solr/update/DeleteUpdateCommand.java
@@ -18,7 +18,9 @@
package org.apache.solr.update;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.CharsRef;
+import org.apache.lucene.util.CharsRefBuilder;
import org.apache.solr.common.SolrInputField;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.schema.IndexSchema;
@@ -60,8 +62,9 @@ public class DeleteUpdateCommand extends UpdateCommand {
IndexSchema schema = req.getSchema();
SchemaField sf = schema.getUniqueKeyField();
if (sf != null && id != null) {
- indexedId = new BytesRef();
- sf.getType().readableToIndexed(id, indexedId);
+ BytesRefBuilder b = new BytesRefBuilder();
+ sf.getType().readableToIndexed(id, b);
+ indexedId = b.get();
}
}
return indexedId;
@@ -72,7 +75,7 @@ public class DeleteUpdateCommand extends UpdateCommand {
IndexSchema schema = req.getSchema();
SchemaField sf = schema.getUniqueKeyField();
if (sf != null) {
- CharsRef ref = new CharsRef();
+ CharsRefBuilder ref = new CharsRefBuilder();
sf.getType().indexedToReadable(indexedId, ref);
id = ref.toString();
}
diff --git a/solr/core/src/java/org/apache/solr/update/SolrIndexSplitter.java b/solr/core/src/java/org/apache/solr/update/SolrIndexSplitter.java
index f48b5013e3b..7074b579a1b 100644
--- a/solr/core/src/java/org/apache/solr/update/SolrIndexSplitter.java
+++ b/solr/core/src/java/org/apache/solr/update/SolrIndexSplitter.java
@@ -34,6 +34,7 @@ import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.CharsRef;
+import org.apache.lucene.util.CharsRefBuilder;
import org.apache.lucene.util.FixedBitSet;
import org.apache.lucene.util.IOUtils;
import org.apache.solr.common.cloud.CompositeIdRouter;
@@ -167,7 +168,7 @@ public class SolrIndexSplitter {
BytesRef term = null;
DocsEnum docsEnum = null;
- CharsRef idRef = new CharsRef(100);
+ CharsRefBuilder idRef = new CharsRefBuilder();
for (;;) {
term = termsEnum.next();
if (term == null) break;
@@ -176,7 +177,7 @@ public class SolrIndexSplitter {
// FUTURE: if conversion to strings costs too much, we could
// specialize and use the hash function that can work over bytes.
- idRef = field.getType().indexedToReadable(term, idRef);
+ field.getType().indexedToReadable(term, idRef);
String idString = idRef.toString();
if (splitKey != null) {
diff --git a/solr/core/src/java/org/apache/solr/update/processor/DistributedUpdateProcessor.java b/solr/core/src/java/org/apache/solr/update/processor/DistributedUpdateProcessor.java
index 4f7b52d98ec..80aeb06dbb6 100644
--- a/solr/core/src/java/org/apache/solr/update/processor/DistributedUpdateProcessor.java
+++ b/solr/core/src/java/org/apache/solr/update/processor/DistributedUpdateProcessor.java
@@ -36,7 +36,9 @@ import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.CharsRef;
+import org.apache.lucene.util.CharsRefBuilder;
import org.apache.solr.client.solrj.request.UpdateRequest;
import org.apache.solr.cloud.CloudDescriptor;
import org.apache.solr.cloud.DistributedQueue;
@@ -238,7 +240,7 @@ public class DistributedUpdateProcessor extends UpdateRequestProcessor {
private NamedList addsResponse = null;
private NamedList deleteResponse = null;
private NamedList deleteByQueryResponse = null;
- private CharsRef scratch;
+ private CharsRefBuilder scratch;
private final SchemaField idField;
@@ -747,7 +749,7 @@ public class DistributedUpdateProcessor extends UpdateRequestProcessor {
addsResponse = new NamedList<String>();
rsp.add("adds",addsResponse);
}
- if (scratch == null) scratch = new CharsRef();
+ if (scratch == null) scratch = new CharsRefBuilder();
idField.getType().indexedToReadable(cmd.getIndexedId(), scratch);
addsResponse.add(scratch.toString(), cmd.getVersion());
}
@@ -1121,9 +1123,9 @@ public class DistributedUpdateProcessor extends UpdateRequestProcessor {
// TODO: fieldtype needs externalToObject?
String oldValS = numericField.getFirstValue().toString();
SchemaField sf = schema.getField(sif.getName());
- BytesRef term = new BytesRef();
+ BytesRefBuilder term = new BytesRefBuilder();
sf.getType().readableToIndexed(oldValS, term);
- Object oldVal = sf.getType().toObject(sf, term);
+ Object oldVal = sf.getType().toObject(sf, term.get());
String fieldValS = fieldVal.toString();
Number result;
@@ -1233,7 +1235,7 @@ public class DistributedUpdateProcessor extends UpdateRequestProcessor {
deleteResponse = new NamedList<String>();
rsp.add("deletes",deleteResponse);
}
- if (scratch == null) scratch = new CharsRef();
+ if (scratch == null) scratch = new CharsRefBuilder();
idField.getType().indexedToReadable(cmd.getIndexedId(), scratch);
deleteResponse.add(scratch.toString(), cmd.getVersion()); // we're returning the version of the delete.. not the version of the doc we deleted.
}
diff --git a/solr/core/src/java/org/apache/solr/update/processor/DocBasedVersionConstraintsProcessorFactory.java b/solr/core/src/java/org/apache/solr/update/processor/DocBasedVersionConstraintsProcessorFactory.java
index 2b0e05d68f7..fcade66c07c 100755
--- a/solr/core/src/java/org/apache/solr/update/processor/DocBasedVersionConstraintsProcessorFactory.java
+++ b/solr/core/src/java/org/apache/solr/update/processor/DocBasedVersionConstraintsProcessorFactory.java
@@ -20,6 +20,7 @@ package org.apache.solr.update.processor;
import org.apache.lucene.queries.function.FunctionValues;
import org.apache.lucene.queries.function.ValueSource;
import org.apache.lucene.util.BytesRef;
+import org.apache.lucene.util.BytesRefBuilder;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.util.NamedList;
@@ -230,9 +231,9 @@ public class DocBasedVersionConstraintsProcessorFactory extends UpdateRequestPro
// in theory, the FieldType might still be CharSequence based,
// but in that case trust it to do an identiy conversion...
FieldType fieldType = userVersionField.getType();
- BytesRef term = new BytesRef();
+ BytesRefBuilder term = new BytesRefBuilder();
fieldType.readableToIndexed((CharSequence)rawValue, term);
- return fieldType.toObject(userVersionField, term);
+ return fieldType.toObject(userVersionField, term.get());
}
// else...
return rawValue;