forked from goldendict/goldendict
-
Notifications
You must be signed in to change notification settings - Fork 0
/
btreeidx.cc
1566 lines (1227 loc) · 41.9 KB
/
btreeidx.cc
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
/* This file is (c) 2008-2012 Konstantin Isakov <ikm@goldendict.org>
* Part of GoldenDict. Licensed under GPLv3 or later, see the LICENSE file */
#include "btreeidx.hh"
#include "folding.hh"
#include "utf8.hh"
#include <QRunnable>
#include <QThreadPool>
#include <QSemaphore>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include "gddebug.hh"
#include "wstring_qt.hh"
#include "qt4x5.hh"
#if QT_VERSION >= QT_VERSION_CHECK( 5, 0, 0 )
#include <QRegularExpression>
#include "wildcard.hh"
#endif
//#define __BTREE_USE_LZO
// LZO mode is experimental and unsupported. Tests didn't show any substantial
// speed improvements.
#ifdef __BTREE_USE_LZO
#include <lzo/lzo1x.h>
namespace {
struct __LzoInit
{
__LzoInit()
{
lzo_init();
}
} __lzoInit;
}
#else
#include <zlib.h>
#endif
namespace BtreeIndexing {
using gd::wstring;
using gd::wchar;
using std::pair;
enum
{
BtreeMinElements = 64,
BtreeMaxElements = 8192
};
BtreeIndex::BtreeIndex():
idxFile( 0 ), rootNodeLoaded( false )
{
}
BtreeDictionary::BtreeDictionary( string const & id,
vector< string > const & dictionaryFiles ):
Dictionary::Class( id, dictionaryFiles )
{
}
string const & BtreeDictionary::ensureInitDone()
{
static string empty;
return empty;
}
void BtreeIndex::openIndex( IndexInfo const & indexInfo,
File::Class & file, Mutex & mutex )
{
indexNodeSize = indexInfo.btreeMaxElements;
rootOffset = indexInfo.rootOffset;
idxFile = &file;
idxFileMutex = &mutex;
rootNodeLoaded = false;
rootNode.clear();
}
vector< WordArticleLink > BtreeIndex::findArticles( wstring const & word, bool ignoreDiacritics )
{
vector< WordArticleLink > result;
try
{
wstring folded = Folding::apply( word );
if( folded.empty() )
folded = Folding::applyWhitespaceOnly( word );
bool exactMatch;
vector< char > leaf;
uint32_t nextLeaf;
char const * leafEnd;
char const * chainOffset = findChainOffsetExactOrPrefix( folded, exactMatch,
leaf, nextLeaf,
leafEnd );
if ( chainOffset && exactMatch )
{
result = readChain( chainOffset );
antialias( word, result, ignoreDiacritics );
}
}
catch( std::exception & e )
{
gdWarning( "Articles searching failed, error: %s\n", e.what() );
result.clear();
}
catch(...)
{
qWarning( "Articles searching failed\n" );
result.clear();
}
return result;
}
class BtreeWordSearchRunnable: public QRunnable
{
BtreeWordSearchRequest & r;
QSemaphore & hasExited;
public:
BtreeWordSearchRunnable( BtreeWordSearchRequest & r_,
QSemaphore & hasExited_ ): r( r_ ),
hasExited( hasExited_ )
{}
~BtreeWordSearchRunnable()
{
hasExited.release();
}
virtual void run();
};
void BtreeWordSearchRunnable::run()
{
r.run();
}
BtreeWordSearchRequest::BtreeWordSearchRequest( BtreeDictionary & dict_,
wstring const & str_,
unsigned minLength_,
int maxSuffixVariation_,
bool allowMiddleMatches_,
unsigned long maxResults_,
bool startRunnable ):
dict( dict_ ), str( str_ ),
maxResults( maxResults_ ),
minLength( minLength_ ),
maxSuffixVariation( maxSuffixVariation_ ),
allowMiddleMatches( allowMiddleMatches_ )
{
if( startRunnable )
{
QThreadPool::globalInstance()->start(
new BtreeWordSearchRunnable( *this, hasExited ) );
}
}
void BtreeWordSearchRequest::findMatches()
{
if ( Qt4x5::AtomicInt::loadAcquire( isCancelled ) )
{
finish();
return;
}
if ( dict.ensureInitDone().size() )
{
setErrorString( QString::fromUtf8( dict.ensureInitDone().c_str() ) );
finish();
return;
}
#if QT_VERSION >= QT_VERSION_CHECK( 5, 0, 0 )
QRegularExpression regexp;
#else
QRegExp regexp;
#endif
bool useWildcards = false;
if( allowMiddleMatches )
useWildcards = ( str.find( '*' ) != wstring::npos ||
str.find( '?' ) != wstring::npos ||
str.find( '[' ) != wstring::npos ||
str.find( ']' ) != wstring::npos );
wstring folded = Folding::apply( str );
int minMatchLength = 0;
if( useWildcards )
{
#if QT_VERSION >= QT_VERSION_CHECK( 5, 0, 0 )
regexp.setPattern( wildcardsToRegexp( gd::toQString( Folding::applyDiacriticsOnly( Folding::applySimpleCaseOnly( str ) ) ) ) );
if( !regexp.isValid() )
regexp.setPattern( QRegularExpression::escape( regexp.pattern() ) );
regexp.setPatternOptions( QRegularExpression::CaseInsensitiveOption );
#else
regexp.setPattern( gd::toQString( Folding::applyDiacriticsOnly( Folding::applySimpleCaseOnly( str ) ) ) );
regexp.setPatternSyntax( QRegExp::WildcardUnix );
regexp.setCaseSensitivity( Qt::CaseInsensitive );
#endif
bool bNoLetters = folded.empty();
wstring foldedWithWildcards;
if( bNoLetters )
foldedWithWildcards = Folding::applyWhitespaceOnly( str );
else
foldedWithWildcards = Folding::apply( str, useWildcards );
// Calculate minimum match length
bool insideSet = false;
bool escaped = false;
for( wstring::size_type x = 0; x < foldedWithWildcards.size(); x++ )
{
wchar ch = foldedWithWildcards[ x ];
if( ch == L'\\' && !escaped )
{
escaped = true;
continue;
}
if( ch == L']' && !escaped )
{
insideSet = false;
continue;
}
if( insideSet )
{
escaped = false;
continue;
}
if( ch == L'[' && !escaped )
{
minMatchLength += 1;
insideSet = true;
continue;
}
if( ch == L'*' && !escaped )
continue;
escaped = false;
minMatchLength += 1;
}
// Fill first match chars
folded.clear();
folded.reserve( foldedWithWildcards.size() );
escaped = false;
for( wstring::size_type x = 0; x < foldedWithWildcards.size(); x++ )
{
wchar ch = foldedWithWildcards[ x ];
if( escaped )
{
if( bNoLetters || ( ch != L'*' && ch != L'?' && ch != L'[' && ch != L']' ) )
folded.push_back( ch );
escaped = false;
continue;
}
if( ch == L'\\' )
{
if( bNoLetters || folded.empty() )
{
escaped = true;
continue;
}
else
break;
}
if( ch == '*' || ch == '?' || ch == '[' || ch == ']' )
break;
folded.push_back( ch );
}
}
else
{
if( folded.empty() )
folded = Folding::applyWhitespaceOnly( str );
}
int initialFoldedSize = folded.size();
int charsLeftToChop = 0;
if ( maxSuffixVariation >= 0 )
{
charsLeftToChop = initialFoldedSize - (int)minLength;
if ( charsLeftToChop < 0 )
charsLeftToChop = 0;
else
if ( charsLeftToChop > maxSuffixVariation )
charsLeftToChop = maxSuffixVariation;
}
try
{
for( ; ; )
{
bool exactMatch;
vector< char > leaf;
uint32_t nextLeaf;
char const * leafEnd;
char const * chainOffset = dict.findChainOffsetExactOrPrefix( folded, exactMatch,
leaf, nextLeaf,
leafEnd );
if ( chainOffset )
for( ; ; )
{
if ( Qt4x5::AtomicInt::loadAcquire( isCancelled ) )
break;
//DPRINTF( "offset = %u, size = %u\n", chainOffset - &leaf.front(), leaf.size() );
vector< WordArticleLink > chain = dict.readChain( chainOffset );
wstring chainHead = Utf8::decode( chain[ 0 ].word );
wstring resultFolded = Folding::apply( chainHead );
if( resultFolded.empty() )
resultFolded = Folding::applyWhitespaceOnly( chainHead );
if ( ( useWildcards && folded.empty() ) ||
( resultFolded.size() >= folded.size()
&& !resultFolded.compare( 0, folded.size(), folded ) ) )
{
// Exact or prefix match
Mutex::Lock _( dataMutex );
for( unsigned x = 0; x < chain.size(); ++x )
{
if( useWildcards )
{
wstring word = Utf8::decode( chain[ x ].prefix + chain[ x ].word );
wstring result = Folding::applyDiacriticsOnly( word );
#if QT_VERSION >= QT_VERSION_CHECK( 5, 0, 0 )
if( result.size() >= (wstring::size_type)minMatchLength )
{
QRegularExpressionMatch match = regexp.match( gd::toQString( result ) );
if( match.hasMatch() && match.capturedStart() == 0 )
{
addMatch( word );
}
}
#else
if( result.size() >= (wstring::size_type)minMatchLength
&& regexp.indexIn( gd::toQString( result ) ) == 0
&& regexp.matchedLength() >= minMatchLength )
{
addMatch( word );
}
#endif
}
else
{
// Skip middle matches, if requested. If suffix variation is specified,
// make sure the string isn't larger than requested.
if ( ( allowMiddleMatches || Folding::apply( Utf8::decode( chain[ x ].prefix ) ).empty() ) &&
( maxSuffixVariation < 0 || (int)resultFolded.size() - initialFoldedSize <= maxSuffixVariation ) )
addMatch( Utf8::decode( chain[ x ].prefix + chain[ x ].word ) );
}
}
if( Qt4x5::AtomicInt::loadAcquire( isCancelled ) )
break;
if ( matches.size() >= maxResults )
{
// For now we actually allow more than maxResults if the last
// chain yield more than one result. That's ok and maybe even more
// desirable.
break;
}
}
else
// Neither exact nor a prefix match, end this
break;
// Fetch new leaf if we're out of chains here
if ( chainOffset >= leafEnd )
{
// We're past the current leaf, fetch the next one
//DPRINTF( "advancing\n" );
if ( nextLeaf )
{
Mutex::Lock _( *dict.idxFileMutex );
dict.readNode( nextLeaf, leaf );
leafEnd = &leaf.front() + leaf.size();
nextLeaf = dict.idxFile->read< uint32_t >();
chainOffset = &leaf.front() + sizeof( uint32_t );
uint32_t leafEntries = *(uint32_t *)&leaf.front();
if ( leafEntries == 0xffffFFFF )
{
//DPRINTF( "bah!\n" );
exit( 1 );
}
}
else
break; // That was the last leaf
}
}
if ( charsLeftToChop && !Qt4x5::AtomicInt::loadAcquire( isCancelled ) )
{
--charsLeftToChop;
folded.resize( folded.size() - 1 );
}
else
break;
}
}
catch( std::exception & e )
{
qWarning( "Index searching failed: \"%s\", error: %s\n",
dict.getName().c_str(), e.what() );
}
catch(...)
{
gdWarning( "Index searching failed: \"%s\"\n", dict.getName().c_str() );
}
}
void BtreeWordSearchRequest::run()
{
if ( Qt4x5::AtomicInt::loadAcquire( isCancelled ) )
{
finish();
return;
}
if ( dict.ensureInitDone().size() )
{
setErrorString( QString::fromUtf8( dict.ensureInitDone().c_str() ) );
finish();
return;
}
findMatches();
finish();
}
BtreeWordSearchRequest::~BtreeWordSearchRequest()
{
isCancelled.ref();
hasExited.acquire();
}
sptr< Dictionary::WordSearchRequest > BtreeDictionary::prefixMatch(
wstring const & str, unsigned long maxResults )
THROW_SPEC( std::exception )
{
return new BtreeWordSearchRequest( *this, str, 0, -1, true, maxResults );
}
sptr< Dictionary::WordSearchRequest > BtreeDictionary::stemmedMatch(
wstring const & str, unsigned minLength, unsigned maxSuffixVariation,
unsigned long maxResults )
THROW_SPEC( std::exception )
{
return new BtreeWordSearchRequest( *this, str, minLength, (int)maxSuffixVariation,
false, maxResults );
}
void BtreeIndex::readNode( uint32_t offset, vector< char > & out )
{
idxFile->seek( offset );
uint32_t uncompressedSize = idxFile->read< uint32_t >();
uint32_t compressedSize = idxFile->read< uint32_t >();
//DPRINTF( "%x,%x\n", uncompressedSize, compressedSize );
out.resize( uncompressedSize );
vector< unsigned char > compressedData( compressedSize );
idxFile->read( &compressedData.front(), compressedData.size() );
#ifdef __BTREE_USE_LZO
lzo_uint decompressedLength = out.size();
if ( lzo1x_decompress( &compressedData.front(), compressedData.size(),
(unsigned char *)&out.front(), &decompressedLength, 0 )
!= LZO_E_OK || decompressedLength != out.size() )
throw exFailedToDecompressNode();
#else
unsigned long decompressedLength = out.size();
if ( uncompress( (unsigned char *)&out.front(),
&decompressedLength,
&compressedData.front(),
compressedData.size() ) != Z_OK ||
decompressedLength != out.size() )
throw exFailedToDecompressNode();
#endif
}
char const * BtreeIndex::findChainOffsetExactOrPrefix( wstring const & target,
bool & exactMatch,
vector< char > & extLeaf,
uint32_t & nextLeaf,
char const * & leafEnd )
{
if ( !idxFile )
throw exIndexWasNotOpened();
Mutex::Lock _( *idxFileMutex );
// Lookup the index by traversing the index btree
vector< wchar > wcharBuffer;
exactMatch = false;
// Read a node
uint32_t currentNodeOffset = rootOffset;
if ( !rootNodeLoaded )
{
// Time to load our root node. We do it only once, at the first request.
readNode( rootOffset, rootNode );
rootNodeLoaded = true;
}
char const * leaf = &rootNode.front();
leafEnd = leaf + rootNode.size();
if( target.empty() )
{
//For empty target string we return first chain in index
for( ; ; )
{
uint32_t leafEntries = *(uint32_t *)leaf;
if ( leafEntries == 0xffffFFFF )
{
// A node
currentNodeOffset = *( (uint32_t *)leaf + 1 );
readNode( currentNodeOffset, extLeaf );
leaf = &extLeaf.front();
leafEnd = leaf + extLeaf.size();
nextLeaf = idxFile->read< uint32_t >();
}
else
{
// A leaf
if( currentNodeOffset == rootOffset )
{
// Only one leaf in index, there's no next leaf
nextLeaf = 0;
}
if( !leafEntries )
return 0;
return leaf + sizeof( uint32_t );
}
}
}
for( ; ; )
{
// Is it a leaf or a node?
uint32_t leafEntries = *(uint32_t *)leaf;
if ( leafEntries == 0xffffFFFF )
{
// A node
//DPRINTF( "=>a node\n" );
uint32_t const * offsets = (uint32_t *)leaf + 1;
char const * ptr = leaf + sizeof( uint32_t ) +
( indexNodeSize + 1 ) * sizeof( uint32_t );
// ptr now points to a span of zero-separated strings, up to leafEnd.
// We find our match using a binary search.
char const * closestString;
int compareResult;
char const * window = ptr;
unsigned windowSize = leafEnd - ptr;
for( ; ; )
{
// We boldly shoot in the middle of the whole mess, and then adjust
// to the beginning of the string that we've hit.
char const * testPoint = window + windowSize/2;
closestString = testPoint;
while( closestString > ptr && closestString[ -1 ] )
--closestString;
size_t wordSize = strlen( closestString );
if ( wcharBuffer.size() <= wordSize )
wcharBuffer.resize( wordSize + 1 );
long result = Utf8::decode( closestString, wordSize, &wcharBuffer.front() );
if ( result < 0 )
throw Utf8::exCantDecode( closestString );
wcharBuffer[ result ] = 0;
//DPRINTF( "Checking against %s\n", closestString );
compareResult = target.compare( &wcharBuffer.front() );
if ( !compareResult )
{
// The target string matches the current one. Finish the search.
break;
}
if ( compareResult < 0 )
{
// The target string is smaller than the current one.
// Go to the left.
windowSize = closestString - window;
if ( !windowSize )
break;
}
else
{
// The target string is larger than the current one.
// Go to the right.
windowSize -= ( closestString - window ) + wordSize + 1;
window = closestString + wordSize + 1;
if ( !windowSize )
break;
}
}
#if 0
DPRINTF( "The winner is %s, compareResult = %d\n", closestString, compareResult );
if ( closestString != ptr )
{
char const * left = closestString -1;
while( left != ptr && left[ -1 ] )
--left;
DPRINTF( "To the left: %s\n", left );
}
else
DPRINTF( "To the lest -- nothing\n" );
char const * right = closestString + strlen( closestString ) + 1;
if ( right != leafEnd )
{
DPRINTF( "To the right: %s\n", right );
}
else
DPRINTF( "To the right -- nothing\n" );
#endif
// Now, whatever the outcome (compareResult) is, we need to find
// entry number for the closestMatch string.
unsigned entry = 0;
for( char const * next = ptr; next != closestString;
next += strlen( next ) + 1, ++entry ) ;
// Ok, now check the outcome
if ( !compareResult )
{
// The target string matches the one found.
// Go to the right, since it's there where we store such results.
currentNodeOffset = offsets[ entry + 1 ];
}
if ( compareResult < 0 )
{
// The target string is smaller than the one found.
// Go to the left.
currentNodeOffset = offsets[ entry ];
}
else
{
// The target string is larger than the one found.
// Go to the right.
currentNodeOffset = offsets[ entry + 1 ];
}
//DPRINTF( "reading node at %x\n", currentNodeOffset );
readNode( currentNodeOffset, extLeaf );
leaf = &extLeaf.front();
leafEnd = leaf + extLeaf.size();
}
else
{
//DPRINTF( "=>a leaf\n" );
// A leaf
// If this leaf is the root, there's no next leaf, it just can't be.
// We do this check because the file's position indicator just won't
// be in the right place for root node anyway, since we precache it.
nextLeaf = ( currentNodeOffset != rootOffset ? idxFile->read< uint32_t >() : 0 );
if ( !leafEntries )
{
// Empty leaf? This may only be possible for entirely empty trees only.
if ( currentNodeOffset != rootOffset )
throw exCorruptedChainData();
else
return 0; // No match
}
// Build an array containing all chain pointers
char const * ptr = leaf + sizeof( uint32_t );
uint32_t chainSize;
vector< char const * > chainOffsets( leafEntries );
{
char const ** nextOffset = &chainOffsets.front();
while( leafEntries-- )
{
*nextOffset++ = ptr;
memcpy( &chainSize, ptr, sizeof( uint32_t ) );
//DPRINTF( "%s + %s\n", ptr + sizeof( uint32_t ), ptr + sizeof( uint32_t ) + strlen( ptr + sizeof( uint32_t ) ) + 1 );
ptr += sizeof( uint32_t ) + chainSize;
}
}
// Now do a binary search in it, aiming to find where our target
// string lands.
char const ** window = &chainOffsets.front();
unsigned windowSize = chainOffsets.size();
for( ; ; )
{
//DPRINTF( "window = %u, ws = %u\n", window - &chainOffsets.front(), windowSize );
char const ** chainToCheck = window + windowSize/2;
ptr = *chainToCheck;
memcpy( &chainSize, ptr, sizeof( uint32_t ) );
ptr += sizeof( uint32_t );
size_t wordSize = strlen( ptr );
if ( wcharBuffer.size() <= wordSize )
wcharBuffer.resize( wordSize + 1 );
//DPRINTF( "checking against word %s, left = %u\n", ptr, leafEntries );
long result = Utf8::decode( ptr, wordSize, &wcharBuffer.front() );
if ( result < 0 )
throw Utf8::exCantDecode( ptr );
wcharBuffer[ result ] = 0;
wstring foldedWord = Folding::apply( &wcharBuffer.front() );
if( foldedWord.empty() )
foldedWord = Folding::applyWhitespaceOnly( &wcharBuffer.front() );
int compareResult = target.compare( foldedWord );
if ( !compareResult )
{
// Exact match -- return and be done
exactMatch = true;
return ptr - sizeof( uint32_t );
}
else
if ( compareResult < 0 )
{
// The target string is smaller than the current one.
// Go to the first half
windowSize /= 2;
if ( !windowSize )
{
// That finishes our search. Since our target string
// landed before the last tested chain, we return a possible
// prefix match against that chain.
return ptr - sizeof( uint32_t );
}
}
else
{
// The target string is larger than the current one.
// Go to the second half
windowSize -= windowSize/2 + 1;
if ( !windowSize )
{
// That finishes our search. Since our target string
// landed after the last tested chain, we return the next
// chain. If there's no next chain in this leaf, this
// would mean the first element in the next leaf.
if ( chainToCheck == &chainOffsets.back() )
{
if ( nextLeaf )
{
readNode( nextLeaf, extLeaf );
leafEnd = &extLeaf.front() + extLeaf.size();
nextLeaf = idxFile->read< uint32_t >();
return &extLeaf.front() + sizeof( uint32_t );
}
else
return 0; // This was the last leaf
}
else
return chainToCheck[ 1 ];
}
window = chainToCheck + 1;
}
}
}
}
}
vector< WordArticleLink > BtreeIndex::readChain( char const * & ptr )
{
uint32_t chainSize;
memcpy( &chainSize, ptr, sizeof( uint32_t ) );
ptr += sizeof( uint32_t );
vector< WordArticleLink > result;
while( chainSize )
{
string str = ptr;
ptr += str.size() + 1;
string prefix = ptr;
ptr += prefix.size() + 1;
uint32_t articleOffset;
memcpy( &articleOffset, ptr, sizeof( uint32_t ) );
ptr += sizeof( uint32_t );
result.push_back( WordArticleLink( str, articleOffset, prefix ) );
if ( chainSize < str.size() + 1 + prefix.size() + 1 + sizeof( uint32_t ) )
throw exCorruptedChainData();
else
chainSize -= str.size() + 1 + prefix.size() + 1 + sizeof( uint32_t );
}
return result;
}
void BtreeIndex::antialias( wstring const & str,
vector< WordArticleLink > & chain,
bool ignoreDiacritics )
{
wstring caseFolded = Folding::applySimpleCaseOnly( gd::normalize( str ) );
if( ignoreDiacritics )
caseFolded = Folding::applyDiacriticsOnly( caseFolded );
for( unsigned x = chain.size(); x--; )
{
// If after applying case folding to each word they wouldn't match, we
// drop the entry.
wstring entry = Folding::applySimpleCaseOnly( gd::normalize( Utf8::decode( chain[ x ].prefix + chain[ x ].word ) ) );
if( ignoreDiacritics )
entry = Folding::applyDiacriticsOnly( entry );
if ( entry != caseFolded )
chain.erase( chain.begin() + x );
else
if ( chain[ x ].prefix.size() ) // If there's a prefix, merge it with the word,
// since it's what dictionaries expect
{
chain[ x ].word.insert( 0, chain[ x ].prefix );
chain[ x ].prefix.clear();
}
}
}
/// A function which recursively creates btree node.
/// The nextIndex iterator is being iterated over and increased when building
/// leaf nodes.
static uint32_t buildBtreeNode( IndexedWords::const_iterator & nextIndex,
size_t indexSize,
File::Class & file, size_t maxElements,
uint32_t & lastLeafLinkOffset )
{
// We compress all the node data. This buffer would hold it.
vector< unsigned char > uncompressedData;
bool isLeaf = indexSize <= maxElements;
if ( isLeaf )
{
// A leaf.
uint32_t totalChainsLength = 0;
IndexedWords::const_iterator nextWord = nextIndex;
for( unsigned x = indexSize; x--; ++nextWord )
{
totalChainsLength += sizeof( uint32_t );
vector< WordArticleLink > const & chain = nextWord->second;
for( unsigned y = 0; y < chain.size(); ++y )
totalChainsLength += chain[ y ].word.size() + 1 + chain[ y ].prefix.size() + 1 + sizeof( uint32_t );
}
uncompressedData.resize( sizeof( uint32_t ) + totalChainsLength );
// First uint32_t indicates that this is a leaf.
*(uint32_t *)&uncompressedData.front() = indexSize;
unsigned char * ptr = &uncompressedData.front() + sizeof( uint32_t );
for( unsigned x = indexSize; x--; ++nextIndex )
{
vector< WordArticleLink > const & chain = nextIndex->second;
unsigned char * saveSizeHere = ptr;
ptr += sizeof( uint32_t );
uint32_t size = 0;
for( unsigned y = 0; y < chain.size(); ++y )
{
memcpy( ptr, chain[ y ].word.c_str(), chain[ y ].word.size() + 1 );
ptr += chain[ y ].word.size() + 1;
memcpy( ptr, chain[ y ].prefix.c_str(), chain[ y ].prefix.size() + 1 );
ptr += chain[ y ].prefix.size() + 1;
memcpy( ptr, &(chain[ y ].articleOffset), sizeof( uint32_t ) );
ptr += sizeof( uint32_t );
size += chain[ y ].word.size() + 1 + chain[ y ].prefix.size() + 1 + sizeof( uint32_t );