-
Notifications
You must be signed in to change notification settings - Fork 623
/
DirectPostingsFormat.cs
2618 lines (2313 loc) · 102 KB
/
DirectPostingsFormat.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using J2N.Numerics;
using Lucene.Net.Diagnostics;
using Lucene.Net.Index;
using Lucene.Net.Support;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using JCG = J2N.Collections.Generic;
namespace Lucene.Net.Codecs.Memory
{
/*
* 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.
*/
using ArrayUtil = Util.ArrayUtil;
using BytesRef = Util.BytesRef;
using CompiledAutomaton = Util.Automaton.CompiledAutomaton;
using DocsAndPositionsEnum = Index.DocsAndPositionsEnum;
using DocsEnum = Index.DocsEnum;
using FieldInfo = Index.FieldInfo;
using Fields = Index.Fields;
using IBits = Util.IBits;
using IndexOptions = Index.IndexOptions;
using IOContext = Store.IOContext;
using OrdTermState = Index.OrdTermState;
using RAMOutputStream = Store.RAMOutputStream;
using RamUsageEstimator = Util.RamUsageEstimator;
using RunAutomaton = Util.Automaton.RunAutomaton;
using SegmentReadState = Index.SegmentReadState;
using SegmentWriteState = Index.SegmentWriteState;
using Terms = Index.Terms;
using TermsEnum = Index.TermsEnum;
using TermState = Index.TermState;
using Transition = Util.Automaton.Transition;
// TODO:
// - build depth-N prefix hash?
// - or: longer dense skip lists than just next byte?
/// <summary>
/// Wraps <see cref="Lucene41.Lucene41PostingsFormat"/> format for on-disk
/// storage, but then at read time loads and stores all
/// terms & postings directly in RAM as byte[], int[].
///
/// <para><b>WARNING</b>: This is
/// exceptionally RAM intensive: it makes no effort to
/// compress the postings data, storing terms as separate
/// byte[] and postings as separate int[], but as a result it
/// gives substantial increase in search performance.
///
/// </para>
/// <para>This postings format supports <see cref="TermsEnum.Ord"/>
/// and <see cref="TermsEnum.SeekExact(long)"/>.
///
/// </para>
/// <para>Because this holds all term bytes as a single
/// byte[], you cannot have more than 2.1GB worth of term
/// bytes in a single segment.
/// </para>
/// @lucene.experimental
/// </summary>
[PostingsFormatName("Direct")] // LUCENENET specific - using PostingsFormatName attribute to ensure the default name passed from subclasses is the same as this class name
public sealed class DirectPostingsFormat : PostingsFormat
{
private readonly int _minSkipCount;
private readonly int _lowFreqCutoff;
private const int DEFAULT_MIN_SKIP_COUNT = 8;
private const int DEFAULT_LOW_FREQ_CUTOFF = 32;
// TODO: allow passing/wrapping arbitrary postings format?
public DirectPostingsFormat()
: this(DEFAULT_MIN_SKIP_COUNT, DEFAULT_LOW_FREQ_CUTOFF)
{
}
/// <summary>
/// <paramref name="minSkipCount"/> is how many terms in a row must have the
/// same prefix before we put a skip pointer down. Terms
/// with docFreq less than or equal <paramref name="lowFreqCutoff"/> will use a single int[]
/// to hold all docs, freqs, position and offsets; terms
/// with higher docFreq will use separate arrays.
/// </summary>
public DirectPostingsFormat(int minSkipCount, int lowFreqCutoff)
: base()
{
_minSkipCount = minSkipCount;
_lowFreqCutoff = lowFreqCutoff;
}
public override FieldsConsumer FieldsConsumer(SegmentWriteState state)
{
return ForName("Lucene41").FieldsConsumer(state);
}
public override FieldsProducer FieldsProducer(SegmentReadState state)
{
var postings = ForName("Lucene41").FieldsProducer(state);
if (state.Context.Context != IOContext.UsageContext.MERGE)
{
FieldsProducer loadedPostings;
try
{
postings.CheckIntegrity();
loadedPostings = new DirectFields(state, postings, _minSkipCount, _lowFreqCutoff);
}
finally
{
postings.Dispose();
}
return loadedPostings;
}
else
{
// Don't load postings for merge:
return postings;
}
}
private sealed class DirectFields : FieldsProducer
{
// LUCENENET specific: Use StringComparer.Ordinal to get the same ordering as Java
private readonly IDictionary<string, DirectField> fields = new JCG.SortedDictionary<string, DirectField>(StringComparer.Ordinal);
public DirectFields(SegmentReadState state, Fields fields, int minSkipCount, int lowFreqCutoff)
{
foreach (string field in fields)
{
this.fields[field] = new DirectField(state, field, fields.GetTerms(field), minSkipCount, lowFreqCutoff);
}
}
public override IEnumerator<string> GetEnumerator()
{
return fields.Keys.GetEnumerator(); // LUCENENET NOTE: enumerators are not writable in .NET
}
public override Terms GetTerms(string field)
{
fields.TryGetValue(field, out DirectField result);
return result;
}
public override int Count => fields.Count;
[Obsolete("iterate fields and add their Count instead.")]
public override long UniqueTermCount
{
get
{
long numTerms = 0;
foreach (DirectField field in fields.Values)
{
numTerms += field.terms.Length;
}
return numTerms;
}
}
protected override void Dispose(bool disposing)
{
}
public override long RamBytesUsed()
{
long sizeInBytes = 0;
foreach (KeyValuePair<string, DirectField> entry in fields)
{
sizeInBytes += entry.Key.Length* RamUsageEstimator.NUM_BYTES_CHAR;
sizeInBytes += entry.Value.RamBytesUsed();
}
return sizeInBytes;
}
public override void CheckIntegrity()
{
// if we read entirely into ram, we already validated.
// otherwise returned the raw postings reader
}
}
private sealed class DirectField : Terms
{
internal abstract class TermAndSkip
{
[WritableArray]
[SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")]
public int[] Skips
{
get => skips;
set => skips = value;
}
private int[] skips;
/// <summary>
/// Returns the approximate number of RAM bytes used. </summary>
public abstract long RamBytesUsed();
}
private sealed class LowFreqTerm : TermAndSkip
{
[WritableArray]
[SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")]
public int[] Postings => postings;
private readonly int[] postings;
[WritableArray]
[SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")]
public byte[] Payloads => payloads;
private readonly byte[] payloads;
public int DocFreq => docFreq;
private readonly int docFreq;
public int TotalTermFreq => totalTermFreq;
private readonly int totalTermFreq;
public LowFreqTerm(int[] postings, byte[] payloads, int docFreq, int totalTermFreq)
{
this.postings = postings;
this.payloads = payloads;
this.docFreq = docFreq;
this.totalTermFreq = totalTermFreq;
}
public override long RamBytesUsed()
{
return ((postings != null) ? RamUsageEstimator.SizeOf(postings) : 0) +
((payloads != null) ? RamUsageEstimator.SizeOf(payloads) : 0);
}
}
// TODO: maybe specialize into prx/no-prx/no-frq cases?
private sealed class HighFreqTerm : TermAndSkip
{
public long TotalTermFreq => totalTermFreq;
private readonly long totalTermFreq;
[WritableArray]
[SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")]
public int[] DocIDs => docIDs;
private readonly int[] docIDs;
[WritableArray]
[SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")]
public int[] Freqs => freqs;
private readonly int[] freqs;
[WritableArray]
[SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")]
public int[][] Positions => positions;
private readonly int[][] positions;
[WritableArray]
[SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")]
public byte[][][] Payloads => payloads;
private readonly byte[][][] payloads;
public HighFreqTerm(int[] docIDs, int[] freqs, int[][] positions, byte[][][] payloads,
long totalTermFreq)
{
this.docIDs = docIDs;
this.freqs = freqs;
this.positions = positions;
this.payloads = payloads;
this.totalTermFreq = totalTermFreq;
}
public override long RamBytesUsed()
{
long sizeInBytes = 0;
sizeInBytes += (docIDs != null) ? RamUsageEstimator.SizeOf(docIDs) : 0;
sizeInBytes += (freqs != null) ? RamUsageEstimator.SizeOf(freqs) : 0;
if (positions != null)
{
foreach (int[] position in positions)
{
sizeInBytes += (position != null) ? RamUsageEstimator.SizeOf(position) : 0;
}
}
if (payloads != null)
{
foreach (var payload in payloads)
{
if (payload != null)
{
foreach (var pload in payload)
{
sizeInBytes += (pload != null) ? RamUsageEstimator.SizeOf(pload) : 0;
}
}
}
}
return sizeInBytes;
}
}
private readonly byte[] termBytes;
private readonly int[] termOffsets;
private readonly int[] skips;
private readonly int[] skipOffsets;
internal readonly TermAndSkip[] terms;
private readonly bool hasFreq;
private readonly bool hasPos;
private readonly bool hasOffsets;
private readonly bool hasPayloads;
private readonly long sumTotalTermFreq;
private readonly int docCount;
private readonly long sumDocFreq;
private int skipCount;
// TODO: maybe make a separate builder? These are only
// used during load:
private readonly int count;
private int[] sameCounts = new int[10];
private readonly int minSkipCount;
/// <summary>
/// NOTE: This was IntArrayWriter in Lucene.
/// </summary>
private sealed class Int32ArrayWriter
{
private int[] ints = new int[10];
private int upto;
public void Add(int value)
{
if (ints.Length == upto)
{
ints = ArrayUtil.Grow(ints);
}
ints[upto++] = value;
}
public int[] Get()
{
var arr = new int[upto];
Array.Copy(ints, 0, arr, 0, upto);
upto = 0;
return arr;
}
}
public DirectField(SegmentReadState state, string field, Terms termsIn, int minSkipCount, int lowFreqCutoff)
{
FieldInfo fieldInfo = state.FieldInfos.FieldInfo(field);
sumTotalTermFreq = termsIn.SumTotalTermFreq;
sumDocFreq = termsIn.SumDocFreq;
docCount = termsIn.DocCount;
int numTerms = (int) termsIn.Count;
if (numTerms == -1)
{
throw new ArgumentException("codec does not provide Terms.size()");
}
terms = new TermAndSkip[numTerms];
termOffsets = new int[1 + numTerms];
byte[] termBytes = new byte[1024];
this.minSkipCount = minSkipCount;
// LUCENENET specific - to avoid boxing, changed from CompareTo() to IndexOptionsComparer.Compare()
hasFreq = IndexOptionsComparer.Default.Compare(fieldInfo.IndexOptions, IndexOptions.DOCS_ONLY) > 0;
hasPos = IndexOptionsComparer.Default.Compare(fieldInfo.IndexOptions, IndexOptions.DOCS_AND_FREQS) > 0;
hasOffsets = IndexOptionsComparer.Default.Compare(fieldInfo.IndexOptions, IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) > 0;
hasPayloads = fieldInfo.HasPayloads;
BytesRef term;
DocsEnum docsEnum = null;
DocsAndPositionsEnum docsAndPositionsEnum = null;
TermsEnum termsEnum = termsIn.GetEnumerator();
int termOffset = 0;
Int32ArrayWriter scratch = new Int32ArrayWriter();
// Used for payloads, if any:
RAMOutputStream ros = new RAMOutputStream();
// if (DEBUG) {
// System.out.println("\nLOAD terms seg=" + state.segmentInfo.name + " field=" + field + " hasOffsets=" + hasOffsets + " hasFreq=" + hasFreq + " hasPos=" + hasPos + " hasPayloads=" + hasPayloads);
// }
while (termsEnum.MoveNext())
{
term = termsEnum.Term;
int docFreq = termsEnum.DocFreq;
long totalTermFreq = termsEnum.TotalTermFreq;
// if (DEBUG) {
// System.out.println(" term=" + term.utf8ToString());
// }
termOffsets[count] = termOffset;
if (termBytes.Length < (termOffset + term.Length))
{
termBytes = ArrayUtil.Grow(termBytes, termOffset + term.Length);
}
Array.Copy(term.Bytes, term.Offset, termBytes, termOffset, term.Length);
termOffset += term.Length;
termOffsets[count + 1] = termOffset;
if (hasPos)
{
docsAndPositionsEnum = termsEnum.DocsAndPositions(null, docsAndPositionsEnum);
}
else
{
docsEnum = termsEnum.Docs(null, docsEnum);
}
TermAndSkip ent;
DocsEnum docsEnum2;
docsEnum2 = hasPos ? docsAndPositionsEnum : docsEnum;
int docID;
if (docFreq <= lowFreqCutoff)
{
ros.Reset();
// Pack postings for low-freq terms into a single int[]:
while ((docID = docsEnum2.NextDoc()) != DocsEnum.NO_MORE_DOCS)
{
scratch.Add(docID);
if (hasFreq)
{
int freq = docsEnum2.Freq;
scratch.Add(freq);
if (hasPos)
{
for (int pos = 0; pos < freq; pos++)
{
scratch.Add(docsAndPositionsEnum.NextPosition());
if (hasOffsets)
{
scratch.Add(docsAndPositionsEnum.StartOffset);
scratch.Add(docsAndPositionsEnum.EndOffset);
}
if (hasPayloads)
{
BytesRef payload = docsAndPositionsEnum.GetPayload();
if (payload != null)
{
scratch.Add(payload.Length);
ros.WriteBytes(payload.Bytes, payload.Offset, payload.Length);
}
else
{
scratch.Add(0);
}
}
}
}
}
}
byte[] payloads;
if (hasPayloads)
{
ros.Flush();
payloads = new byte[(int) ros.Length];
ros.WriteTo(payloads, 0);
}
else
{
payloads = null;
}
int[] postings = scratch.Get();
ent = new LowFreqTerm(postings, payloads, docFreq, (int) totalTermFreq);
}
else
{
var docs = new int[docFreq];
int[] freqs;
int[][] positions;
byte[][][] payloads;
if (hasFreq)
{
freqs = new int[docFreq];
if (hasPos)
{
positions = new int[docFreq][];
if (hasPayloads)
{
payloads = new byte[docFreq][][];
}
else
{
payloads = null;
}
}
else
{
positions = null;
payloads = null;
}
}
else
{
freqs = null;
positions = null;
payloads = null;
}
// Use separate int[] for the postings for high-freq
// terms:
int upto = 0;
while ((docID = docsEnum2.NextDoc()) != DocsEnum.NO_MORE_DOCS)
{
docs[upto] = docID;
if (hasFreq)
{
int freq = docsEnum2.Freq;
freqs[upto] = freq;
if (hasPos)
{
int mult;
if (hasOffsets)
{
mult = 3;
}
else
{
mult = 1;
}
if (hasPayloads)
{
payloads[upto] = new byte[freq][];
}
positions[upto] = new int[mult*freq];
int posUpto = 0;
for (int pos = 0; pos < freq; pos++)
{
positions[upto][posUpto] = docsAndPositionsEnum.NextPosition();
if (hasPayloads)
{
BytesRef payload = docsAndPositionsEnum.GetPayload();
if (payload != null)
{
var payloadBytes = new byte[payload.Length];
Array.Copy(payload.Bytes, payload.Offset, payloadBytes, 0,
payload.Length);
payloads[upto][pos] = payloadBytes;
}
}
posUpto++;
if (hasOffsets)
{
positions[upto][posUpto++] = docsAndPositionsEnum.StartOffset;
positions[upto][posUpto++] = docsAndPositionsEnum.EndOffset;
}
}
}
}
upto++;
}
if (Debugging.AssertsEnabled) Debugging.Assert(upto == docFreq);
ent = new HighFreqTerm(docs, freqs, positions, payloads, totalTermFreq);
}
terms[count] = ent;
SetSkips(count, termBytes);
count++;
}
// End sentinel:
termOffsets[count] = termOffset;
FinishSkips();
//System.out.println(skipCount + " skips: " + field);
this.termBytes = new byte[termOffset];
Array.Copy(termBytes, 0, this.termBytes, 0, termOffset);
// Pack skips:
this.skips = new int[skipCount];
this.skipOffsets = new int[1 + numTerms];
int skipOffset = 0;
for (int i = 0; i < numTerms; i++)
{
int[] termSkips = terms[i].Skips;
skipOffsets[i] = skipOffset;
if (termSkips != null)
{
Array.Copy(termSkips, 0, skips, skipOffset, termSkips.Length);
skipOffset += termSkips.Length;
terms[i].Skips = null;
}
}
this.skipOffsets[numTerms] = skipOffset;
if (Debugging.AssertsEnabled) Debugging.Assert(skipOffset == skipCount);
}
/// <summary>Returns approximate RAM bytes used. </summary>
public long RamBytesUsed()
{
long sizeInBytes = 0;
sizeInBytes += ((termBytes != null) ? RamUsageEstimator.SizeOf(termBytes) : 0);
sizeInBytes += ((termOffsets != null) ? RamUsageEstimator.SizeOf(termOffsets) : 0);
sizeInBytes += ((skips != null) ? RamUsageEstimator.SizeOf(skips) : 0);
sizeInBytes += ((skipOffsets != null) ? RamUsageEstimator.SizeOf(skipOffsets) : 0);
sizeInBytes += ((sameCounts != null) ? RamUsageEstimator.SizeOf(sameCounts) : 0);
if (terms != null)
{
foreach (TermAndSkip termAndSkip in terms)
{
sizeInBytes += (termAndSkip != null) ? termAndSkip.RamBytesUsed() : 0;
}
}
return sizeInBytes;
}
// Compares in unicode (UTF8) order:
private int Compare(int ord, BytesRef other)
{
byte[] otherBytes = other.Bytes;
int upto = termOffsets[ord];
int termLen = termOffsets[1 + ord] - upto;
int otherUpto = other.Offset;
int stop = upto + Math.Min(termLen, other.Length);
while (upto < stop)
{
int diff = (termBytes[upto++] & 0xFF) - (otherBytes[otherUpto++] & 0xFF);
if (diff != 0)
{
return diff;
}
}
// One is a prefix of the other, or, they are equal:
return termLen - other.Length;
}
private void SetSkips(int termOrd, byte[] termBytes)
{
int termLength = termOffsets[termOrd + 1] - termOffsets[termOrd];
if (sameCounts.Length < termLength)
{
sameCounts = ArrayUtil.Grow(sameCounts, termLength);
}
// Update skip pointers:
if (termOrd > 0)
{
int lastTermLength = termOffsets[termOrd] - termOffsets[termOrd - 1];
int limit = Math.Min(termLength, lastTermLength);
int lastTermOffset = termOffsets[termOrd - 1];
int termOffset = termOffsets[termOrd];
int i = 0;
for (; i < limit; i++)
{
if (termBytes[lastTermOffset++] == termBytes[termOffset++])
{
sameCounts[i]++;
}
else
{
for (; i < limit; i++)
{
if (sameCounts[i] >= minSkipCount)
{
// Go back and add a skip pointer:
SaveSkip(termOrd, sameCounts[i]);
}
sameCounts[i] = 1;
}
break;
}
}
for (; i < lastTermLength; i++)
{
if (sameCounts[i] >= minSkipCount)
{
// Go back and add a skip pointer:
SaveSkip(termOrd, sameCounts[i]);
}
sameCounts[i] = 0;
}
for (int j = limit; j < termLength; j++)
{
sameCounts[j] = 1;
}
}
else
{
for (int i = 0; i < termLength; i++)
{
sameCounts[i]++;
}
}
}
private void FinishSkips()
{
if (Debugging.AssertsEnabled) Debugging.Assert(count == terms.Length);
int lastTermOffset = termOffsets[count - 1];
int lastTermLength = termOffsets[count] - lastTermOffset;
for (int i = 0; i < lastTermLength; i++)
{
if (sameCounts[i] >= minSkipCount)
{
// Go back and add a skip pointer:
SaveSkip(count, sameCounts[i]);
}
}
// Reverse the skip pointers so they are "nested":
for (int termID = 0; termID < terms.Length; termID++)
{
TermAndSkip term = terms[termID];
if (term.Skips != null && term.Skips.Length > 1)
{
for (int pos = 0; pos < term.Skips.Length/2; pos++)
{
int otherPos = term.Skips.Length - pos - 1;
int temp = term.Skips[pos];
term.Skips[pos] = term.Skips[otherPos];
term.Skips[otherPos] = temp;
}
}
}
}
private void SaveSkip(int ord, int backCount)
{
TermAndSkip term = terms[ord - backCount];
skipCount++;
if (term.Skips == null)
{
term.Skips = new int[] {ord};
}
else
{
// Normally we'd grow at a slight exponential... but
// given that the skips themselves are already log(N)
// we can grow by only 1 and still have amortized
// linear time:
int[] newSkips = new int[term.Skips.Length + 1];
Array.Copy(term.Skips, 0, newSkips, 0, term.Skips.Length);
term.Skips = newSkips;
term.Skips[term.Skips.Length - 1] = ord;
}
}
public override TermsEnum GetEnumerator()
{
var termsEnum = new DirectTermsEnum(this);
termsEnum.Reset();
return termsEnum;
}
public override TermsEnum GetEnumerator(TermsEnum reuse)
{
if (!(reuse is DirectTermsEnum termsEnum) || !termsEnum.CanReuse(terms))
termsEnum = new DirectTermsEnum(this);
termsEnum.Reset();
return termsEnum;
}
public override TermsEnum Intersect(CompiledAutomaton compiled, BytesRef startTerm)
{
return new DirectIntersectTermsEnum(this, compiled, startTerm);
}
public override long Count => terms.Length;
public override long SumTotalTermFreq => sumTotalTermFreq;
public override long SumDocFreq => sumDocFreq;
public override int DocCount => docCount;
public override IComparer<BytesRef> Comparer => BytesRef.UTF8SortedAsUnicodeComparer;
public override bool HasFreqs => hasFreq;
public override bool HasOffsets => hasOffsets;
public override bool HasPositions => hasPos;
public override bool HasPayloads => hasPayloads;
private sealed class DirectTermsEnum : TermsEnum
{
private readonly DirectPostingsFormat.DirectField outerInstance;
private readonly BytesRef scratch = new BytesRef();
private int termOrd;
public DirectTermsEnum(DirectPostingsFormat.DirectField outerInstance)
{
this.outerInstance = outerInstance;
}
internal bool CanReuse(TermAndSkip[] other)
{
return outerInstance.terms == other;
}
internal BytesRef SetTerm()
{
scratch.Bytes = outerInstance.termBytes;
scratch.Offset = outerInstance.termOffsets[termOrd];
scratch.Length = outerInstance.termOffsets[termOrd + 1] - outerInstance.termOffsets[termOrd];
return scratch;
}
public void Reset()
{
termOrd = -1;
}
public override IComparer<BytesRef> Comparer => BytesRef.UTF8SortedAsUnicodeComparer;
public override bool MoveNext()
{
termOrd++;
if (termOrd < outerInstance.terms.Length)
{
SetTerm();
return true;
}
else
{
return false;
}
}
[Obsolete("Use MoveNext() and Term instead. This method will be removed in 4.8.0 release candidate."), System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public override BytesRef Next()
{
if (MoveNext())
return scratch;
return null;
}
public override TermState GetTermState()
{
OrdTermState state = new OrdTermState();
state.Ord = termOrd;
return state;
}
// If non-negative, exact match; else, -ord-1, where ord
// is where you would insert the term.
private int FindTerm(BytesRef term)
{
// Just do binary search: should be (constant factor)
// faster than using the skip list:
int low = 0;
int high = outerInstance.terms.Length - 1;
while (low <= high)
{
int mid = (low + high).TripleShift(1);
int cmp = outerInstance.Compare(mid, term);
if (cmp < 0)
{
low = mid + 1;
}
else if (cmp > 0)
{
high = mid - 1;
}
else
{
return mid; // key found
}
}
return -(low + 1); // key not found.
}
public override SeekStatus SeekCeil(BytesRef term)
{
// TODO: we should use the skip pointers; should be
// faster than bin search; we should also hold
// & reuse current state so seeking forwards is
// faster
int ord = FindTerm(term);
// if (DEBUG) {
// System.out.println(" find term=" + term.utf8ToString() + " ord=" + ord);
// }
if (ord >= 0)
{
termOrd = ord;
SetTerm();
return SeekStatus.FOUND;
}
else if (ord == -outerInstance.terms.Length - 1)
{
return SeekStatus.END;
}
else
{
termOrd = -ord - 1;
SetTerm();
return SeekStatus.NOT_FOUND;
}
}
public override bool SeekExact(BytesRef term)
{
// TODO: we should use the skip pointers; should be
// faster than bin search; we should also hold
// & reuse current state so seeking forwards is
// faster
int ord = FindTerm(term);
if (ord >= 0)
{
termOrd = ord;
SetTerm();
return true;
}
else
{
return false;
}
}
public override void SeekExact(long ord)
{
termOrd = (int) ord;
SetTerm();
}
public override void SeekExact(BytesRef term, TermState state)
{
termOrd = (int) ((OrdTermState) state).Ord;
SetTerm();
if (Debugging.AssertsEnabled) Debugging.Assert(term.Equals(scratch));
}
public override BytesRef Term => scratch;
public override long Ord => termOrd;
public override int DocFreq =>
outerInstance.terms[termOrd] is LowFreqTerm lowFreqTerm ?
lowFreqTerm.DocFreq :
((HighFreqTerm)outerInstance.terms[termOrd]).DocIDs.Length;
public override long TotalTermFreq =>
outerInstance.terms[termOrd] is LowFreqTerm lowFreqTerm ?
lowFreqTerm.TotalTermFreq :
((HighFreqTerm)outerInstance.terms[termOrd]).TotalTermFreq;