-
Notifications
You must be signed in to change notification settings - Fork 54
Expand file tree
/
Copy pathSDocumentWriter.cpp
More file actions
1577 lines (1342 loc) · 55.1 KB
/
SDocumentWriter.cpp
File metadata and controls
1577 lines (1342 loc) · 55.1 KB
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
//
// Created by 姜凯 on 2022/9/16.
//
#include "SDocumentWriter.h"
#include "IndexWriter.h"
#include "CLucene/analysis/AnalysisHeader.h"
#include "CLucene/document/Document.h"
#include "CLucene/search/Similarity.h"
#include "CLucene/util/CLStreams.h"
#include "CLucene/util/Misc.h"
#include "CLucene/util/stringUtil.h"
#include "CLucene/util/PFORUtil.h"
#include "CLucene/index/CodeMode.h"
#include "_FieldsWriter.h"
#include "_TermInfosWriter.h"
#include "_SkipListWriter.h"
#include "_IndexFileNames.h"
#include "_SegmentMerger.h"
#include <algorithm>
#include <vector>
#include <iostream>
CL_NS_USE(util)
CL_NS_USE(store)
CL_NS_USE(analysis)
CL_NS_USE(document)
CL_NS_DEF(index)
template<typename T>
const uint8_t SDocumentsWriter<T>::defaultNorm = search::Similarity::encodeNorm(1);
template<typename T>
const int32_t SDocumentsWriter<T>::BYTE_BLOCK_SHIFT = 15;
template<typename T>
const int32_t SDocumentsWriter<T>::BYTE_BLOCK_SIZE = 1 << BYTE_BLOCK_SHIFT;//(int32_t) pow(2.0, BYTE_BLOCK_SHIFT);
template<typename T>
const int32_t SDocumentsWriter<T>::BYTE_BLOCK_MASK = BYTE_BLOCK_SIZE - 1;
template<typename T>
const int32_t SDocumentsWriter<T>::BYTE_BLOCK_NOT_MASK = ~BYTE_BLOCK_MASK;
template<typename T>
const int32_t SDocumentsWriter<T>::CHAR_BLOCK_SHIFT = 14;
template<typename T>
const int32_t SDocumentsWriter<T>::CHAR_BLOCK_SIZE = (int32_t) pow(2.0, CHAR_BLOCK_SHIFT);
template<typename T>
const int32_t SDocumentsWriter<T>::CHAR_BLOCK_MASK = CHAR_BLOCK_SIZE - 1;
template<typename T>
const int32_t SDocumentsWriter<T>::nextLevelArray[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 9};
template<typename T>
const int32_t SDocumentsWriter<T>::levelSizeArray[10] = {5, 14, 20, 30, 40, 40, 80, 80, 120, 200};
template<typename T>
const int32_t SDocumentsWriter<T>::POINTER_NUM_BYTE = 4;
template<typename T>
const int32_t SDocumentsWriter<T>::INT_NUM_BYTE = 4;
template<typename T>
const int32_t SDocumentsWriter<T>::CHAR_NUM_BYTE = 2;//TODO: adjust for c++...
template<typename T>
const int32_t SDocumentsWriter<T>::SCHAR_NUM_BYTE = 1;//TODO: adjust for c++...
template<typename T>
int32_t SDocumentsWriter<T>::OBJECT_HEADER_BYTES = 8;
template<typename T>
const int32_t SDocumentsWriter<T>::POSTING_NUM_BYTE = OBJECT_HEADER_BYTES + 9 * INT_NUM_BYTE + 5 * POINTER_NUM_BYTE;
template<typename T>
SDocumentsWriter<T>::ThreadState::ThreadState(SDocumentsWriter *p) : postingsFreeListTS(ValueArray<Posting *>(256)),
vectorFieldPointers(ValueArray<int64_t>(10)),
vectorFieldNumbers(ValueArray<int32_t>(10)),
fieldDataArray(ValueArray<FieldData *>(8)),
fieldDataHash(ValueArray<FieldData *>(16)),
postingsPool(_CLNEW ByteBlockPool(true, p)),
scharPool(_CLNEW SCharBlockPool(p)),
allFieldDataArray(ValueArray<FieldData *>(10)),
_parent(p) {
fieldDataHashMask = 15;
postingsFreeCountTS = 0;
stringReader = _CLNEW ReusableStringReader(_T(""), 0, false);
numThreads = 1;
this->docBoost = 0.0;
this->fieldGen = this->posUpto = this->numStoredFields = 0;
this->numAllFieldData = this->docID = 0;
this->numFieldData = numVectorFields = this->proxUpto = this->freqUpto = this->offsetUpto = 0;
this->maxTermPrefix = nullptr;
this->p = nullptr;
this->prox = nullptr;
this->offsets = nullptr;
this->pos = nullptr;
this->freq = nullptr;
this->doFlushAfter = false;
}
template<typename T>
SDocumentsWriter<T>::~SDocumentsWriter() {
if (skipListWriter!=nullptr) {
_CLDELETE(skipListWriter);
}
if (fieldInfos != nullptr) {
_CLDELETE(fieldInfos);
}
if (threadState != nullptr) {
_CLDELETE(threadState);
}
if (_files != nullptr) {
_CLDELETE(_files);
}
// Make sure unused posting slots aren't attempted delete on
if (this->postingsFreeListDW.values) {
if (this->postingsFreeCountDW < this->postingsFreeListDW.length) {
memset(this->postingsFreeListDW.values + this->postingsFreeCountDW, 0, sizeof(Posting *));
}
postingsFreeListDW.deleteUntilNULL();
}
}
template<typename T>
SDocumentsWriter<T>::ThreadState::~ThreadState() {
_CLDELETE(postingsPool);
_CLDELETE(scharPool);
_CLDELETE(stringReader);
for (size_t i = 0; i < allFieldDataArray.length; i++)
_CLDELETE(allFieldDataArray.values[i]);
}
template<typename T>
void SDocumentsWriter<T>::ThreadState::resetCurrentFieldData(Document *doc) {
const Document::FieldsType &docFields = *doc->getFields();
const int32_t numDocFields = docFields.size();
if (FieldData* fp = fieldDataArray.values[0]; fp && numDocFields > 0) {
numFieldData = 1;
// reset fp for new fields
fp->fieldCount = 0;
// delete values is not make length reset to 0, so resize can not make sure new docFields values
fp->docFields.deleteValues();
fp->docFields.length = 0;
fp->docFields.resize(1);
for (int32_t i = 0; i < numDocFields; i++) {
Field *field = docFields[i];
if (fp->fieldCount == fp->docFields.length) {
fp->docFields.resize(fp->docFields.length * 2);
}
fp->docFields.values[fp->fieldCount++] = field;
}
}
return;
}
template<typename T>
typename SDocumentsWriter<T>::ThreadState *SDocumentsWriter<T>::getThreadState(Document *doc) {
if (threadState == nullptr) {
threadState = _CLNEW ThreadState(this);
}
if (segment.empty()) {
segment = writer->newSegmentName();
threadState->init(doc, nextDocID);
} else if (doc->getNeedResetFieldData()) {
threadState->resetCurrentFieldData(doc);
}
threadState->docID = nextDocID;
// Only increment nextDocID & numDocsInRAM on successful init
nextDocID++;
numDocsInRAM++;
// We must at this point commit to flushing to ensure we
// always get N docs when we flush by doc count, even if
// > 1 thread is adding documents:
if (!flushPending && maxBufferedDocs != IndexWriter::DISABLE_AUTO_FLUSH && numDocsInRAM >= maxBufferedDocs) {
flushPending = true;
threadState->doFlushAfter = true;
}
return threadState;
}
template<typename T>
void SDocumentsWriter<T>::ThreadState::init(Document *doc, int32_t doc_id) {
this->docID = doc_id;
docBoost = doc->getBoost();
numStoredFields = 0;
numFieldData = 0;
numVectorFields = 0;
maxTermPrefix = nullptr;
const int32_t thisFieldGen = fieldGen++;
const Document::FieldsType &docFields = *doc->getFields();
const int32_t numDocFields = docFields.size();
for (int32_t i = 0; i < numDocFields; i++) {
Field *field = docFields[i];
FieldInfo *fi = _parent->fieldInfos->add(field->name(), field->isIndexed(), field->isTermVectorStored(),
field->isStorePositionWithTermVector(), field->isStoreOffsetWithTermVector(),
field->getOmitNorms(), !field->getOmitTermFreqAndPositions(), false);
fi->setIndexVersion(field->getIndexVersion());
fi->setFlags(field->getFlags());
if (fi->isIndexed && !fi->omitNorms) {
// Maybe grow our buffered norms
if (_parent->norms.length <= fi->number) {
auto newSize = (int32_t) ((1 + fi->number) * 1.25);
_parent->norms.resize(newSize);
}
if (_parent->norms[fi->number] == NULL)
_parent->norms.values[fi->number] = _CLNEW BufferedNorms();
_parent->hasNorms = true;
}
// Make sure we have a FieldData allocated
int32_t hashPos = Misc::thashCode(fi->name) & fieldDataHashMask;//TODO: put hash in fieldinfo
FieldData *fp = fieldDataHash[hashPos];
while (fp != nullptr && _tcscmp(fp->fieldInfo->name, fi->name) != 0)
fp = fp->next;
if (fp == nullptr) {
fp = _CLNEW FieldData(_parent, this, fi);
fp->next = fieldDataHash[hashPos];
fieldDataHash.values[hashPos] = fp;
if (numAllFieldData == allFieldDataArray.length) {
allFieldDataArray.resize((int32_t) (allFieldDataArray.length * 1.5));
ValueArray<FieldData *> newHashArray(fieldDataHash.length * 2);
// Rehash
fieldDataHashMask = allFieldDataArray.length - 1;
for (size_t j = 0; j < fieldDataHash.length; j++) {
FieldData *fp0 = fieldDataHash[j];
while (fp0 != nullptr) {
//todo: put hash code into fieldinfo to reduce number of hashes necessary
hashPos = Misc::thashCode(fp0->fieldInfo->name) & fieldDataHashMask;
FieldData *nextFP0 = fp0->next;
fp0->next = newHashArray[hashPos];
newHashArray.values[hashPos] = fp0;
fp0 = nextFP0;
}
}
fieldDataHash.resize(newHashArray.length);
memcpy(fieldDataHash.values, newHashArray.values, newHashArray.length * sizeof(FieldData *));
}
allFieldDataArray.values[numAllFieldData++] = fp;
} else {
assert(fp->fieldInfo == fi);
}
if (thisFieldGen != fp->lastGen) {
// First time we're seeing this field for this doc
fp->lastGen = thisFieldGen;
fp->fieldCount = 0;
fp->doNorms = fi->isIndexed && !fi->omitNorms;
if (numFieldData == fieldDataArray.length) {
fieldDataArray.resize(fieldDataArray.length * 2);
}
fieldDataArray.values[numFieldData++] = fp;
}
if (fp->fieldCount == fp->docFields.length) {
fp->docFields.resize(fp->docFields.length * 2);
}
// Lazily allocate arrays for postings:
if (field->isIndexed() && fp->postingsHash.values == nullptr)
fp->initPostingArrays();
fp->docFields.values[fp->fieldCount++] = field;
}
_parent->hasProx_ = _parent->fieldInfos->hasProx();
_parent->indexVersion_ = _parent->fieldInfos->getIndexVersion();
_parent->flags_ = _parent->fieldInfos->getFlags();
}
template<typename T>
void SDocumentsWriter<T>::ThreadState::writeDocument() {
// If we hit an exception while appending to the
// stored fields or term vectors files, we have to
// abort all documents since we last flushed because
// it means those files are possibly inconsistent.
try {
//_parent->numDocsInStore++;
// Append norms for the fields we saw:
for (int32_t i = 0; i < numFieldData; i++) {
FieldData *fp = fieldDataArray[i];
if (fp->doNorms) {
BufferedNorms *bn = _parent->norms[fp->fieldInfo->number];
assert(bn != nullptr);
assert(bn->upto <= docID);
bn->fill(docID);
bn->add(fp->length);
}
}
} catch (CLuceneError &t) {
throw;
}
if (_parent->bufferIsFull && !_parent->flushPending) {
_parent->flushPending = true;
doFlushAfter = true;
}
}
template<typename T>
void SDocumentsWriter<T>::ThreadState::FieldData::initPostingArrays() {
// Target hash fill factor of <= 50%
// NOTE: must be a power of two for hash collision
// strategy to work correctly
postingsHashSize = 4;
postingsHashHalfSize = 2;
postingsHashMask = postingsHashSize - 1;
postingsHash.resize(postingsHashSize);
}
template<typename T>
void SDocumentsWriter<T>::ThreadState::FieldData::processField(Analyzer *sanalyzer) {
length = 0;
position = 0;
offset = 0;
boost = threadState->docBoost;
const int32_t maxFieldLength = _parent->writer->getMaxFieldLength();
const int32_t limit = fieldCount;
const ArrayBase<Field *> &docFieldsFinal = docFields;
try {
for (int32_t j = 0; j < limit; j++) {
Field *field = docFieldsFinal[j];
if (field->isIndexed()) {
invertField(field, sanalyzer, maxFieldLength);
}
if (field->isStored()) {
threadState->numStoredFields++;
}
// docFieldsFinal.values[j] = NULL;
}
} catch (CLuceneError& ae) {
throw ae;
}
}
template<typename T>
void SDocumentsWriter<T>::ThreadState::FieldData::rehashPostings(const int32_t newSize) {
const int32_t newMask = newSize - 1;
ValueArray<Posting *> newHash(newSize);
int32_t hashPos, code;
const T *_pos = nullptr;
const T *start = nullptr;
Posting *p0;
for (int32_t i = 0; i < postingsHashSize; i++) {
p0 = postingsHash[i];
if (p0 != nullptr) {
start = threadState->scharPool->buffers[p0->textStart >> CHAR_BLOCK_SHIFT] + (p0->textStart & CHAR_BLOCK_MASK);
_pos = start;
while (*_pos != CLUCENE_END_OF_WORD)
_pos++;
code = 0;
while (_pos > start)
code = (code * 31) + *start++;
//code = (code * 31) + *--_pos;
hashPos = code & newMask;
assert(hashPos >= 0);
if (newHash[hashPos] != NULL) {
const int32_t inc = ((code >> 8) + code) | 1;
do {
code += inc;
hashPos = code & newMask;
} while (newHash[hashPos] != NULL);
}
newHash.values[hashPos] = p0;
}
}
postingsHashMask = newMask;
postingsHash.deleteArray();
postingsHash.length = newHash.length;
postingsHash.values = newHash.takeArray();
postingsHashSize = newSize;
postingsHashHalfSize = newSize >> 1;
}
template<typename T>
bool SDocumentsWriter<T>::ThreadState::postingEquals(const T *tokenText, const int32_t tokenTextLen) {
if (p->textLen != tokenTextLen) {
return false;
}
const T *text = scharPool->buffers[p->textStart >> CHAR_BLOCK_SHIFT];
assert(text != nullptr);
int32_t position = p->textStart & CHAR_BLOCK_MASK;
int32_t tokenPos = 0;
for (; tokenPos < tokenTextLen; position++, tokenPos++) {
if (tokenText[tokenPos] != text[position])
return false;
}
return CLUCENE_END_OF_WORD == text[position];
}
template<typename T>
void SDocumentsWriter<T>::ThreadState::writeFreqVInt(int32_t vi) {
uint32_t i = vi;
while ((i & ~0x7F) != 0) {
writeFreqByte((uint8_t) ((i & 0x7f) | 0x80));
i >>= 7;//unsigned shift...
}
writeFreqByte((uint8_t) i);
}
template<typename T>
void SDocumentsWriter<T>::ThreadState::writeProxVInt(int32_t vi) {
uint32_t i = vi;
while ((i & ~0x7F) != 0) {
writeProxByte((uint8_t) ((i & 0x7f) | 0x80));
i >>= 7;//unsigned shift...
}
writeProxByte((uint8_t) i);
}
template<typename T>
void SDocumentsWriter<T>::ThreadState::writeFreqByte(uint8_t b) {
assert(freq != nullptr);
if (freq[freqUpto] != 0) {
freqUpto = postingsPool->allocSlice(freq, freqUpto);
freq = postingsPool->buffer;
p->freqUpto = postingsPool->tOffset;
}
freq[freqUpto++] = b;
}
template<typename T>
void SDocumentsWriter<T>::ThreadState::writeProxByte(uint8_t b) {
assert(prox != nullptr);
if (prox[proxUpto] != 0) {
proxUpto = postingsPool->allocSlice(prox, proxUpto);
prox = postingsPool->buffer;
p->proxUpto = postingsPool->tOffset;
assert(prox != nullptr);
}
prox[proxUpto++] = b;
assert(proxUpto != SDocumentsWriter::BYTE_BLOCK_SIZE);
}
template<typename T>
void SDocumentsWriter<T>::ThreadState::writeProxBytes(const uint8_t *b, int32_t offset, int32_t len) {
const int32_t offsetEnd = offset + len;
while (offset < offsetEnd) {
if (prox[proxUpto] != 0) {
// End marker
proxUpto = postingsPool->allocSlice(prox, proxUpto);
prox = postingsPool->buffer;
//p->proxUpto = postingsPool->tOffset;
}
prox[proxUpto++] = b[offset++];
assert(proxUpto != SDocumentsWriter::BYTE_BLOCK_SIZE);
}
}
template <typename T>
inline bool eq(const std::basic_string_view<T>& a, const std::basic_string_view<T>& b) {
if constexpr (std::is_same_v<T, char>) {
#if defined(__SSE2__)
if (a.size() != b.size()) {
return false;
}
return StringUtil::memequalSSE2Wide(a.data(), b.data(), a.size());
#endif
}
return a == b;
}
template<typename T>
void SDocumentsWriter<T>::ThreadState::FieldData::addPosition(Token *token) {
const T *tokenText = token->termBuffer<T>();
const int32_t tokenTextLen = token->termLength<T>();
std::basic_string_view<T> term(tokenText, tokenTextLen);
// if constexpr (std::is_same_v<T, char>) {
// std::cout << term << std::endl;
// }
uint32_t code = 0;
// Compute hashcode
//int32_t downto = tokenTextLen;
int32_t upto = 0;
//while (downto > 0)
while (upto < tokenTextLen && tokenText[upto] != CLUCENE_END_OF_WORD)
code = (code * 31) + tokenText[upto++];
uint32_t hashPos = code & postingsHashMask;
if (upto < tokenTextLen) {
for (int32_t i = upto; i < tokenTextLen; i++) {
if (tokenText[i] != CLUCENE_END_OF_WORD) {
char error_msg[512];
if constexpr (std::is_same_v<T, char>) {
snprintf(error_msg, sizeof(error_msg),
"Inverted index does not support terms with null byte (\\0) in the "
"middle. "
"Found null at position %d, but non-null character at position %d. "
"Term prefix: '%.*s'.",
upto, i, std::min(upto, 50), tokenText);
} else {
snprintf(error_msg, sizeof(error_msg),
"Term contains null character in the middle at position %d.", upto);
}
_CLTHROWA(CL_ERR_IllegalArgument, error_msg);
}
}
}
assert(!postingsCompacted);
// Locate Posting in hash
threadState->p = postingsHash[hashPos];
if (threadState->p != nullptr && !eq(threadState->p->term_, term)) {
const uint32_t inc = ((code >> 8) + code) | 1;
do {
postingsHashConflicts++;
code += inc;
hashPos = code & postingsHashMask;
threadState->p = postingsHash[hashPos];
} while (threadState->p != nullptr && !eq(threadState->p->term_, term));
}
int32_t proxCode = 0;
try {
if (threadState->p != nullptr) { // term seen since last flush
if (threadState->docID != threadState->p->lastDocID) {// term not yet seen in this doc
// Now that we know doc freq for previous doc,
// write it & lastDocCode
threadState->freqUpto = threadState->p->freqUpto & BYTE_BLOCK_MASK;
threadState->freq = threadState->postingsPool->buffers[threadState->p->freqUpto >> BYTE_BLOCK_SHIFT];
if (fieldInfo->hasProx) {
if (1 == threadState->p->docFreq)
threadState->writeFreqVInt(threadState->p->lastDocCode | 1);
else {
threadState->writeFreqVInt(threadState->p->lastDocCode);
threadState->writeFreqVInt(threadState->p->docFreq);
}
} else {
threadState->writeFreqVInt(threadState->p->lastDocCode | 1);
}
threadState->p->freqUpto = threadState->freqUpto + (threadState->p->freqUpto & BYTE_BLOCK_NOT_MASK);
if (fieldInfo->hasProx) {
proxCode = position;
threadState->p->docFreq = 1;
}
// Store code so we can write this after we're
// done with this new doc
threadState->p->lastDocCode = (threadState->docID - threadState->p->lastDocID) << 1;
threadState->p->lastDocID = threadState->docID;
} else {// term already seen in this doc
if (fieldInfo->hasProx) {
threadState->p->docFreq++;
proxCode = position - threadState->p->lastPosition;
}
}
} else {// term not seen before
if (0 == threadState->postingsFreeCountTS) {
_parent->getPostings(threadState->postingsFreeListTS);
threadState->postingsFreeCountTS = threadState->postingsFreeListTS.length;
}
const int32_t textLen1 = 1 + tokenTextLen;
if (textLen1 + threadState->scharPool->tUpto > CHAR_BLOCK_SIZE) {
if (textLen1 > CHAR_BLOCK_SIZE) {
std::string errmsg = "bytes can be at most " +
std::to_string(CHAR_BLOCK_SIZE - 1) +
" in length; got " + std::to_string(tokenTextLen);
_CLTHROWA(CL_ERR_MaxBytesLength, errmsg.c_str());
}
threadState->scharPool->nextBuffer();
}
T *text = threadState->scharPool->buffer;
T *textUpto = text + threadState->scharPool->tUpto;
// Pull next free Posting from free list
threadState->p = threadState->postingsFreeListTS[--threadState->postingsFreeCountTS];
assert(threadState->p != nullptr);
threadState->p->textStart = textUpto + threadState->scharPool->tOffset - text;
threadState->p->textLen = tokenTextLen;
threadState->scharPool->tUpto += textLen1;
memcpy(textUpto, tokenText, tokenTextLen * sizeof(T));
threadState->p->term_ = std::basic_string_view<T>(textUpto, term.size());
textUpto[tokenTextLen] = CLUCENE_END_OF_WORD;
assert(postingsHash[hashPos] == NULL);
postingsHash.values[hashPos] = threadState->p;
numPostings++;
if (numPostings == postingsHashHalfSize)
rehashPostings(2 * postingsHashSize);
// Init first slice for freq & prox streams
const int32_t firstSize = levelSizeArray[0];
const int32_t upto1 = threadState->postingsPool->newSlice(firstSize);
threadState->p->freqStart = threadState->p->freqUpto = threadState->postingsPool->tOffset + upto1;
if (fieldInfo->hasProx) {
const int32_t upto2 = threadState->postingsPool->newSlice(firstSize);
threadState->p->proxStart = threadState->p->proxUpto = threadState->postingsPool->tOffset + upto2;
}
threadState->p->lastDocCode = threadState->docID << 1;
threadState->p->lastDocID = threadState->docID;
if (fieldInfo->hasProx) {
threadState->p->docFreq = 1;
proxCode = position;
}
}
threadState->proxUpto = threadState->p->proxUpto & BYTE_BLOCK_MASK;
threadState->prox = threadState->postingsPool->buffers[threadState->p->proxUpto >> BYTE_BLOCK_SHIFT];
assert(threadState->prox != nullptr);
if (fieldInfo->hasProx) {
threadState->writeProxVInt(proxCode << 1);
threadState->p->proxUpto = threadState->proxUpto + (threadState->p->proxUpto & BYTE_BLOCK_NOT_MASK);
threadState->p->lastPosition = position++;
}
} catch (CLuceneError &t) {
throw;
}
}
template<typename T>
void SDocumentsWriter<T>::ThreadState::FieldData::invertField(Field *field, Analyzer *sanalyzer, const int32_t maxFieldLength) {
if (!field->isTokenized()) {// un-tokenized field
const T *stringValue = (T *) field->rawStringValue();
const size_t valueLength = field->getFieldDataLength();
Token *token = localSToken;
token->clear();
token->setText(stringValue, valueLength);
token->setStartOffset(offset);
token->setEndOffset(offset + valueLength);
addPosition(token);
offset += valueLength;
length++;
} else {// tokenized field
if (length > 0) {
position += sanalyzer->getPositionIncrementGap(fieldInfo->name);
}
TokenStream *stream;
TokenStream *streamValue = field->tokenStreamValue();
if (streamValue != nullptr)
stream = streamValue;
else {
// not support by now
_CLTHROWA(CL_ERR_IllegalArgument, "field must have only STokenStream");
}
// reset the TokenStream to the first token
stream->reset();
try {
offsetEnd = offset - 1;
for (;;) {
Token *token = stream->next(localSToken);
if (token == nullptr) break;
position += (token->getPositionIncrement() - 1);
addPosition(token);
++length;
}
offset = offsetEnd + 1;
}
_CLFINALLY(
stream->close();//don't delete, this stream is re-used
)
}
boost *= field->getBoost();
}
template<typename T>
void SDocumentsWriter<T>::ThreadState::processDocument(Analyzer *sanalyzer) {
const int32_t numFields = numFieldData;
// We process the document one field at a time
for (int32_t i = 0; i < numFields; i++)
fieldDataArray[i]->processField(sanalyzer);
if (_parent->ramBufferSize != -1 && _parent->numBytesUsed > 0.95 * _parent->ramBufferSize)
_parent->balanceRAM();
}
template<typename T>
void SDocumentsWriter<T>::ThreadState::trimFields() {
int32_t upto = 0;
for (int32_t i = 0; i < numAllFieldData; i++) {
FieldData *fp = allFieldDataArray[i];
if (fp->lastGen == -1) {
// This field was not seen since the previous
// flush, so, free up its resources now
// Unhash
const int32_t hashPos = Misc::thashCode(fp->fieldInfo->name) & fieldDataHashMask;
FieldData *last = nullptr;
FieldData *fp0 = fieldDataHash[hashPos];
while (fp0 != fp) {
last = fp0;
fp0 = fp0->next;
}
assert(fp0 != nullptr);
if (last == nullptr)
fieldDataHash.values[hashPos] = fp->next;
else
last->next = fp->next;
_CLDELETE(fp);
} else {
// Reset
fp->lastGen = -1;
allFieldDataArray.values[upto++] = fp;
if (fp->numPostings > 0 && ((float_t) fp->numPostings) / fp->postingsHashSize < 0.2) {
int32_t hashSize = fp->postingsHashSize;
// Reduce hash so it's between 25-50% full
while (fp->numPostings < (hashSize >> 1) && hashSize >= 2)
hashSize >>= 1;
hashSize <<= 1;
if (hashSize != fp->postingsHash.length)
fp->rehashPostings(hashSize);
}
}
}
//delete everything after up to in allFieldDataArray
for (size_t i = upto; i < allFieldDataArray.length; i++) {
allFieldDataArray[i] = NULL;
}
// If we didn't see any norms for this field since
// last flush, free it
for (size_t i = 0; i < _parent->norms.length; i++) {
BufferedNorms *n = _parent->norms[i];
if (n != nullptr && n->upto == 0) {
_CLLDELETE(n);
_parent->norms.values[i] = NULL;
}
}
numAllFieldData = upto;
}
template<typename T>
void SDocumentsWriter<T>::ThreadState::resetPostings() {
fieldGen = 0;
doFlushAfter = false;
postingsPool->reset();
scharPool->reset();
_parent->recyclePostings(this->postingsFreeListTS, this->postingsFreeCountTS);
this->postingsFreeCountTS = 0;
for (int32_t i = 0; i < numAllFieldData; i++) {
FieldData *fp = allFieldDataArray[i];
fp->lastGen = -1;
if (fp->numPostings > 0)
fp->resetPostingArrays();
}
}
template<typename T>
int32_t SDocumentsWriter<T>::ThreadState::comparePostings(Posting *p1, Posting *p2) {
const T *pos1 = scharPool->buffers[p1->textStart >> CHAR_BLOCK_SHIFT] + (p1->textStart & CHAR_BLOCK_MASK);
const T *pos2 = scharPool->buffers[p2->textStart >> CHAR_BLOCK_SHIFT] + (p2->textStart & CHAR_BLOCK_MASK);
while (true) {
const auto c1 = static_cast<typename std::make_unsigned<T>::type>(*pos1++);
const auto c2 = static_cast<typename std::make_unsigned<T>::type>(*pos2++);
if (c1 < c2)
if (CLUCENE_END_OF_WORD == c2)
return 1;
else
return -1;
else if (c2 < c1)
if (CLUCENE_END_OF_WORD == c1)
return -1;
else
return 1;
else if (CLUCENE_END_OF_WORD == c1)
return 0;
}
}
template<typename T>
void SDocumentsWriter<T>::ThreadState::quickSort(Posting **postings, int32_t lo, int32_t hi) {
if (lo >= hi)
return;
int32_t mid = ((uint32_t) (lo + hi)) >> 1;//unsigned shift...
if (comparePostings(postings[lo], postings[mid]) > 0) {
Posting *tmp = postings[lo];
postings[lo] = postings[mid];
postings[mid] = tmp;
}
if (comparePostings(postings[mid], postings[hi]) > 0) {
Posting *tmp = postings[mid];
postings[mid] = postings[hi];
postings[hi] = tmp;
if (comparePostings(postings[lo], postings[mid]) > 0) {
Posting *tmp2 = postings[lo];
postings[lo] = postings[mid];
postings[mid] = tmp2;
}
}
int32_t left = lo + 1;
int32_t right = hi - 1;
if (left >= right)
return;
Posting *partition = postings[mid];
for (;;) {
while (comparePostings(postings[right], partition) > 0)
--right;
while (left < right && comparePostings(postings[left], partition) <= 0)
++left;
if (left < right) {
Posting *tmp = postings[left];
postings[left] = postings[right];
postings[right] = tmp;
--right;
} else {
break;
}
}
quickSort(postings, lo, left);
quickSort(postings, left + 1, hi);
}
template<typename T>
void SDocumentsWriter<T>::finishDocument(ThreadState *state) {
// Now write the indexed document to the real files.
if (nextWriteDocID == state->docID) {
// It's my turn, so write everything now:
nextWriteDocID++;
state->writeDocument();
} else {
// No other choices.
}
}
template<typename T>
bool SDocumentsWriter<T>::updateDocument(Document *doc, Analyzer *sanalyzer) {
ThreadState *state = getThreadState(doc);
try {
bool success = false;
try {
try {
state->processDocument(sanalyzer);
}
_CLFINALLY(
finishDocument(state);)
success = true;
}
_CLFINALLY(
if (!success) {
// If this thread state had decided to flush, we
// must clear it so another thread can flush
if (state->doFlushAfter) {
state->doFlushAfter = false;
flushPending = false;
}
})
} catch (CLuceneError& ae) {
throw ae;
}
return state->doFlushAfter;
}
template<typename T>
bool SDocumentsWriter<T>::updateNullDocument(Document *doc) {
ThreadState *state = getThreadState(doc);
if (nextWriteDocID == state->docID) {
nextWriteDocID++;
}
return true;
}
template<>
TCHAR *SDocumentsWriter<TCHAR>::getSCharBlock() {
const size_t size = freeSCharBlocks.size();
TCHAR *c;
if (0 == size) {
numBytesAlloc += CHAR_BLOCK_SIZE * CHAR_NUM_BYTE;
c = _CL_NEWARRAY(TCHAR, CHAR_BLOCK_SIZE);
memset(c, 0, sizeof(TCHAR) * CHAR_BLOCK_SIZE);
} else {
c = *freeSCharBlocks.begin();
freeSCharBlocks.remove(freeSCharBlocks.begin(), true);
}
numBytesUsed += CHAR_BLOCK_SIZE * CHAR_NUM_BYTE;
return c;
}
template<>
char *SDocumentsWriter<char>::getSCharBlock() {
const size_t size = freeSCharBlocks.size();
char *c;
if (0 == size) {
numBytesAlloc += CHAR_BLOCK_SIZE * SCHAR_NUM_BYTE;
balanceRAM();
c = _CL_NEWARRAY(char, CHAR_BLOCK_SIZE);
memset(c, 0, sizeof(char) * CHAR_BLOCK_SIZE);
} else {
c = *freeSCharBlocks.begin();
freeSCharBlocks.remove(freeSCharBlocks.begin(), true);
}
numBytesUsed += CHAR_BLOCK_SIZE * SCHAR_NUM_BYTE;
return c;
}
template<typename T>
void SDocumentsWriter<T>::recycleSCharBlocks(ArrayBase<T *> &blocks, int32_t start, int32_t numBlocks) {
for (int32_t i = start; i < numBlocks; i++) {
freeSCharBlocks.push_back(blocks[i]);
blocks.values[i] = NULL;
}
}
template<typename T>
void SDocumentsWriter<T>::getPostings(ValueArray<Posting *> &postings) {
numBytesUsed += postings.length * POSTING_NUM_BYTE;
int32_t numToCopy;
if (this->postingsFreeCountDW < postings.length)
numToCopy = this->postingsFreeCountDW;
else
numToCopy = postings.length;
const int32_t start = this->postingsFreeCountDW - numToCopy;
if (numToCopy > 0) {
memcpy(postings.values, this->postingsFreeListDW.values + start, sizeof(Posting *) * numToCopy);
}
this->postingsFreeCountDW -= numToCopy;
// Directly allocate the remainder if any
if (numToCopy < postings.length) {
const int32_t extra = postings.length - numToCopy;
const int32_t newPostingsAllocCount = this->postingsAllocCountDW + extra;
if (newPostingsAllocCount > this->postingsFreeListDW.length)
this->postingsFreeListDW.resize((int32_t) (1.25 * newPostingsAllocCount));
balanceRAM();
for (size_t i = numToCopy; i < postings.length; i++) {
postings.values[i] = _CLNEW Posting();
numBytesAlloc += POSTING_NUM_BYTE;
this->postingsAllocCountDW++;
}
}
}
template<typename T>
void SDocumentsWriter<T>::writeNorms(const std::string &segmentName, int32_t totalNumDoc) {
IndexOutput *normsOut = directory->createOutput((segmentName + "." + IndexFileNames::NORMS_EXTENSION).c_str());
try {
normsOut->writeBytes(SegmentMerger::NORMS_HEADER, SegmentMerger::NORMS_HEADER_length);
const int32_t numField = fieldInfos->size();
for (int32_t fieldIdx = 0; fieldIdx < numField; fieldIdx++) {
FieldInfo *fi = fieldInfos->fieldInfo(fieldIdx);