forked from gnustep/libs-corebase
-
Notifications
You must be signed in to change notification settings - Fork 5
/
CFBurstTrie.c
2076 lines (1839 loc) · 78.9 KB
/
CFBurstTrie.c
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
/*
* Copyright (c) 2015 Apple Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
/* CFBurstTrie.c
Copyright (c) 2008-2014, Apple Inc. All rights reserved.
Responsibility: Jennifer Moore
*/
#include "CFInternal.h"
#include "CFBurstTrie.h"
#include "CFByteOrder.h"
#include "CFNumber.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <limits.h>
#if DEPLOYMENT_TARGET_MACOSX || DEPLOYMENT_TARGET_EMBEDDED || DEPLOYMENT_TARGET_EMBEDDED_MINI || DEPLOYMENT_TARGET_LINUX
#include <unistd.h>
#include <sys/param.h>
#include <sys/mman.h>
#endif
#include <errno.h>
#include <assert.h>
#if DEPLOYMENT_TARGET_WINDOWS
#define open _NS_open
#define statinfo _stat
#define stat(x,y) _NS_stat(x,y)
#define __builtin_memcmp(x, y, z) memcmp(x, y, z)
#define __builtin_popcountll(x) popcountll(x)
#define bzero(dst, size) ZeroMemory(dst, size)
#define S_IWUSR 0
#define S_IRUSR 0
static int pwrite(int fd, const void *buf, size_t nbyte, off_t offset) {
// Get where we are
long pos = _tell(fd);
// Move to new offset
_lseek(fd, offset, SEEK_SET);
// Write data
int res = _write(fd, buf, nbyte);
// Return to previous offset
_lseek(fd, pos, SEEK_SET);
return res;
}
#else
#define statinfo stat
#endif
#if 0
#pragma mark Types and Utilities
#endif
#define MAX_STRING_ALLOCATION_SIZE 342
#define MAX_STRING_SIZE 1024
#define MAX_KEY_LENGTH MAX_STRING_SIZE * 4
#define CHARACTER_SET_SIZE 256
#define MAX_LIST_SIZE 256 // 64
#define MAX_BITMAP_SIZE 200
#define MAX_BUFFER_SIZE (4096<<2)
#define NextTrie_GetPtr(p) (p & ((~(uintptr_t)0)-3))
#define NextTrie_GetKind(p) (p & 3)
#define NextTrie_SetKind(p, kind) (p |= (3&kind))
#define DiskNextTrie_GetPtr(map,offset) (((uintptr_t)map) + (uintptr_t)(offset & ((~(uintptr_t)0)-3)))
#define DiskNextTrie_GetKind(p) (p & 3)
#define DiskNextTrie_SetKind(p, kind) (p |= (3&kind))
// Use this macro to avoid forgetting to check the pointer before assigning value to it.
#define SetPayload(pointer, value) do { if (pointer) *pointer = value; } while (0)
enum { Nothing = 0, TrieKind = 1, ListKind = 2, CompactTrieKind = 3 };
typedef enum { FailedInsert = 0, NewTerm = 1, ExistingTerm = 2 } CFBTInsertCode;
#pragma pack (1)
typedef uintptr_t NextTrie;
typedef struct _TrieLevel {
NextTrie slots[CHARACTER_SET_SIZE];
uint32_t weight;
uint32_t payload;
} TrieLevel;
typedef TrieLevel *TrieLevelRef;
typedef struct _MapTrieLevel {
uint32_t slots[CHARACTER_SET_SIZE];
uint32_t payload;
} MapTrieLevel;
typedef MapTrieLevel *MapTrieLevelRef;
typedef struct _CompactMapTrieLevel {
uint64_t bitmap[CHARACTER_SET_SIZE / 64];
uint32_t payload;
uint32_t slots[];
} CompactMapTrieLevel;
typedef CompactMapTrieLevel *CompactMapTrieLevelRef;
typedef struct _ListNode {
struct _ListNode *next;
uint32_t weight;
uint32_t payload;
uint16_t length;
UInt8 string[];
}* ListNodeRef;
typedef struct _Page {
uint32_t length;
char data[];
} Page;
typedef struct _PageEntryPacked {
uint8_t pfxLen;
uint16_t strlen;
uint32_t payload;
UInt8 string[];
} PageEntryPacked;
typedef struct _PageEntry {
uint16_t strlen;
uint32_t payload;
UInt8 string[];
} PageEntry;
typedef struct _TrieHeader {
uint32_t signature;
uint32_t rootOffset;
uint32_t count;
uint32_t size;
uint32_t flags;
uint64_t reserved[16];
} TrieHeader;
typedef struct _TrieCursor {
uint64_t signature;
uint64_t counter;
NextTrie next;
uint32_t keylen;
uint32_t prefixlen;
const uint8_t *prefix;
uint8_t key[MAX_KEY_LENGTH];
} TrieCursor;
typedef struct _MapCursor {
uint64_t signature;
TrieHeader *header;
uint32_t next;
uint32_t prefixlen;
uint32_t keylen;
const uint8_t *prefix;
uint8_t key[MAX_STRING_SIZE*4];
} MapCursor;
typedef struct _CompactMapCursor {
uint32_t next;
uint32_t entryOffsetInPage;
uint32_t offsetInEntry;
uint32_t payload;
// On a page, the first entry could has 0 strlen. So we need this variable to tell us whether
// the cursor is merely pointing at the beginning of the page, or the first entry.
// For example, if the trie contains "ab" and "abc", where "a" is stored on an array level,
// while "b" and "bc" are stored on a page level. If we creat a cursor for string "a", this cursor
// will point at the beginning of the page, but not at any particular key. The both entryOffsetInPage and
// offsetInEntry fields of the cursor are set to 0 in this case. Now if we add "a" to the
// trie. the page level will actually contains three entries. The first entry corresponds to string "a".
// That entry has 0 strlen value. If we creat a cursor for string "a" again, this cursor will
// point at the first entry on the page. But the entryOffsetInPage and offsetInEntry fields are still
// set to 0s. So we need an additional variable to make distinction between these two situations.
BOOL isOnPage;
} CompactMapCursor;
typedef struct _CompactMapCursor *MapCursorRef;
enum {
_kCFBurstTrieCursorTrieType = 0,
_kCFBurstTrieCursorMapType
};
typedef struct _CFBurstTrieCursor {
CompactMapCursor mapCursor;
CFIndex cursorType;
CFBurstTrieRef trie;
} _CFBurstTrieCursor;
// ** Legacy
typedef struct _DiskTrieLevel {
uint32_t slots[CHARACTER_SET_SIZE];
uint32_t weight;
uint32_t payload;
} DiskTrieLevel;
typedef DiskTrieLevel *DiskTrieLevelRef;
typedef struct _CompactDiskTrieLevel {
uint64_t bitmap[CHARACTER_SET_SIZE / 64]; // CHARACTER_SET_SIZE / 64bits per word
uint32_t weight;
uint32_t payload;
uint32_t slots[];
} CompactDiskTrieLevel;
typedef CompactDiskTrieLevel *CompactDiskTrieLevelRef;
typedef struct _StringPage {
uint32_t length;
char data[];
} StringPage;
typedef struct _StringPageEntryPacked {
uint8_t pfxLen;
uint16_t strlen; // make uint8_t if possible
uint32_t payload;
char string[];
} StringPageEntryPacked;
typedef struct _StringPageEntry {
uint16_t strlen; // make uint8_t if possible
uint32_t payload;
char string[];
} StringPageEntry;
typedef struct _fileHeader {
uint32_t signature;
uint32_t rootOffset;
uint32_t count;
uint32_t size;
uint32_t flags;
} fileHeader;
// **
#pragma pack()
struct _CFBurstTrie {
union {
TrieLevel root;
DiskTrieLevel diskRoot;
MapTrieLevel maproot;
};
char *mapBase;
uint32_t mapSize;
uint32_t mapOffset;
uint32_t cflags;
uint32_t count;
uint32_t containerSize;
int retain;
#if DEPLOYMENT_TARGET_WINDOWS
HANDLE mapHandle;
HANDLE mappedFileHandle;
#endif
};
#if 0
#pragma mark -
#pragma mark Forward declarations
#endif
typedef struct _TraverseContext {
void *context;
void (*callback)(void*, const UInt8*, uint32_t, uint32_t);
} TraverseContext;
static bool foundKey(void *context, const uint8_t *key, uint32_t payload, bool exact)
{
if (context != NULL) {
TraverseContext *ctx = (TraverseContext *)context;
if (ctx->context && ctx->callback) {
ctx->callback(ctx->context, key, 1, payload);
}
}
return false;
}
void CFBurstTrieTraverseWithCursor(CFBurstTrieRef trie, const uint8_t *prefix, uint32_t prefixLen, void **cursor, void *ctx, bool (*callback)(void *, const uint8_t *, uint32_t, bool));
static CFBTInsertCode addCFBurstTrieLevel(CFBurstTrieRef trie, TrieLevelRef root, const uint8_t *key, uint32_t keylen, uint32_t weight, uint32_t payload);
static void findCFBurstTrieLevel(CFBurstTrieRef trie, TrieCursor *cursor, bool exactmatch, void *ctx, bool (*callback)(void*, const uint8_t*, uint32_t, bool));
static void findCFBurstTrieMappedLevel(CFBurstTrieRef trie, MapCursor *cursor, bool exactmatch, void *ctx, bool (*callback)(void*, const uint8_t*, uint32_t, bool));
static void traverseCFBurstTrieLevel(CFBurstTrieRef trie, TrieLevelRef root, TrieCursor *cursor, bool exactmatch, void *ctx, bool (*callback)(void *, const uint8_t *, uint32_t, bool));
static void traverseCFBurstTrieMappedLevel(CFBurstTrieRef trie, MapTrieLevelRef root, MapCursor *cursor, bool exactmatch, void *ctx, bool (*callback)(void *, const uint8_t *, uint32_t, bool));
static void traverseCFBurstTrieCompactMappedLevel(CFBurstTrieRef trie, CompactMapTrieLevelRef root, MapCursor *cursor, bool exactmatch, void *ctx, bool (*callback)(void *, const uint8_t *, uint32_t, bool));
static void traverseCFBurstTrieWithCursor(CFBurstTrieRef trie, const uint8_t *prefix, uint32_t prefixLen, void **cursor, bool exactmatch, void *ctx, bool (*callback)(void *, const uint8_t *, uint32_t, bool));
static size_t serializeCFBurstTrie(CFBurstTrieRef trie, size_t start_offset, int fd);
static Boolean burstTrieMappedFind(DiskTrieLevelRef trie, char *map, const UInt8 *key, uint32_t length, uint32_t *payload, bool prefix);
static Boolean burstTrieMappedPageFind(StringPage *page, const UInt8 *key, uint32_t length, uint32_t *payload, bool prefix);
static Boolean burstTrieCompactTrieMappedFind(CompactDiskTrieLevelRef trie, char *map, const UInt8 *key, uint32_t length, uint32_t *payload, bool prefix);
static void destroyCFBurstTrie(CFBurstTrieRef trie);
static void finalizeCFBurstTrie(TrieLevelRef trie);
static void finalizeCFBurstTrieList(ListNodeRef node);
static int nodeWeightCompare(const void *a, const void *b);
static int nodeStringCompare(const void *a, const void *b);
static bool foundKey(void *context, const uint8_t *key, uint32_t payload, bool exact);
static bool containsKey(void *context, const uint8_t *key, uint32_t payload, bool exact);
static CFIndex burstTrieConvertCharactersToUTF8(UniChar *chars, CFIndex numChars, UInt8 *buffer);
static Boolean advanceMapCursor(CFBurstTrieRef trie, CompactMapCursor *cursor, const UInt8* bytes, CFIndex length);
static Boolean getMapCursorPayload(CFBurstTrieRef trie, const CompactMapCursor *cursor, uint32_t *payload);
static void copyMapCursor(const CompactMapCursor *source, CompactMapCursor* destination);
static Boolean areMapCursorsEqual(const CompactMapCursor *lhs, const CompactMapCursor *rhs);
static void traverseFromMapCursor(CFBurstTrieRef trie, CompactMapCursor *cursor, UInt8* bytes, uint32_t capacity, uint32_t length, Boolean *stop, void *ctx, CFBurstTrieTraversalCallback callback);
static Boolean getMapCursorPayloadFromPackedPageEntry(PageEntryPacked *entry, const CompactMapCursor *cursor, uint32_t *payload);
static Boolean getMapCursorPayloadFromPageEntry(PageEntry *entry, const CompactMapCursor *cursor, uint32_t *payload);
CFBurstTrieRef CFBurstTrieCreateWithOptions(CFDictionaryRef options) {
CFBurstTrieRef trie = NULL;
trie = (CFBurstTrieRef) calloc(1, sizeof(struct _CFBurstTrie));
trie->containerSize = MAX_LIST_SIZE;
CFNumberRef valueAsCFNumber;
if (CFDictionaryGetValueIfPresent(options, kCFBurstTrieCreationOptionNameContainerSize, (const void **)&valueAsCFNumber)) {
int value;
CFNumberGetValue(valueAsCFNumber, kCFNumberIntType, &value);
trie->containerSize = value > 2 && value < 4096 ? value : MAX_LIST_SIZE;
}
trie->retain = 1;
return trie;
}
CFBurstTrieRef CFBurstTrieCreate() {
CFBurstTrieRef trie = NULL;
int listSize = MAX_LIST_SIZE;
CFNumberRef value = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &listSize);
CFMutableDictionaryRef options = CFDictionaryCreateMutable(kCFAllocatorDefault, 1, NULL, NULL);
CFDictionarySetValue(options, kCFBurstTrieCreationOptionNameContainerSize, value);
trie = CFBurstTrieCreateWithOptions(options);
CFRelease(value);
CFRelease(options);
return trie;
}
CFBurstTrieRef CFBurstTrieCreateFromFile(CFStringRef path) {
struct statinfo sb;
char filename[PATH_MAX];
int fd;
/* Check valid path name */
if (!CFStringGetCString(path, filename, PATH_MAX, kCFStringEncodingUTF8)) return NULL;
/* Check if file exists */
if (stat(filename, &sb) != 0) return NULL;
/* Check if file can be opened */
if ((fd=open(filename, CF_OPENFLGS|O_RDONLY)) < 0) return NULL;
#if DEPLOYMENT_TARGET_WINDOWS
HANDLE mappedFileHandle = (HANDLE)_get_osfhandle(fd);
if (!mappedFileHandle) return NULL;
HANDLE mapHandle = CreateFileMapping(mappedFileHandle, NULL, PAGE_READONLY, 0, 0, NULL);
if (!mapHandle) return NULL;
char *map = (char *)MapViewOfFile(mapHandle, FILE_MAP_READ, 0, 0, sb.st_size);
if (!map) return NULL;
#else
char *map = mmap(0, sb.st_size, PROT_READ, MAP_FILE|MAP_SHARED, fd, 0);
#endif
CFBurstTrieRef trie = NULL;
TrieHeader *header = (TrieHeader *)map;
if (((uint32_t*)map)[0] == 0xbabeface) {
trie = (CFBurstTrieRef) calloc(1, sizeof(struct _CFBurstTrie));
trie->mapBase = map;
trie->mapSize = CFSwapInt32LittleToHost(sb.st_size);
trie->mapOffset = CFSwapInt32LittleToHost(((fileHeader*)trie->mapBase)->rootOffset);
trie->cflags = CFSwapInt32LittleToHost(((fileHeader*)trie->mapBase)->flags);
trie->count = CFSwapInt32LittleToHost(((fileHeader*)trie->mapBase)->count);
trie->retain = 1;
#if DEPLOYMENT_TARGET_WINDOWS
trie->mappedFileHandle = mappedFileHandle;
trie->mapHandle = mapHandle;
#else
// On Windows, the file being mapped must stay open as long as the map exists. Don't close it early. Other platforms close it here.
close(fd);
#endif
} else if (header->signature == 0xcafebabe || header->signature == 0x0ddba11) {
trie = (CFBurstTrieRef) calloc(1, sizeof(struct _CFBurstTrie));
trie->mapBase = map;
trie->mapSize = CFSwapInt32LittleToHost(sb.st_size);
trie->cflags = CFSwapInt32LittleToHost(header->flags);
trie->count = CFSwapInt32LittleToHost(header->count);
trie->retain = 1;
#if DEPLOYMENT_TARGET_WINDOWS
trie->mappedFileHandle = mappedFileHandle;
trie->mapHandle = mapHandle;
#else
// On Windows, the file being mapped must stay open as long as the map exists. Don't close it early. Other platforms close it here.
close(fd);
#endif
} else {
close(fd);
}
return trie;
}
CFBurstTrieRef CFBurstTrieCreateFromMapBytes(char *mapBase) {
CFBurstTrieRef trie = NULL;
TrieHeader *header = (TrieHeader *)mapBase;
if (mapBase && ((uint32_t*)mapBase)[0] == 0xbabeface) {
trie = (CFBurstTrieRef) malloc(sizeof(struct _CFBurstTrie));
trie->mapBase = mapBase;
trie->mapSize = CFSwapInt32LittleToHost(((fileHeader*)trie->mapBase)->size);
trie->mapOffset = CFSwapInt32LittleToHost(((fileHeader*)trie->mapBase)->rootOffset);
trie->cflags = CFSwapInt32LittleToHost(((fileHeader*)trie->mapBase)->flags);
trie->count = CFSwapInt32LittleToHost(((fileHeader*)trie->mapBase)->count);
trie->retain = 1;
} else if (mapBase && (header->signature == 0xcafebabe || header->signature == 0x0ddba11)) {
trie = (CFBurstTrieRef) malloc(sizeof(struct _CFBurstTrie));
trie->mapBase = mapBase;
trie->mapSize = CFSwapInt32LittleToHost(header->size);
trie->cflags = CFSwapInt32LittleToHost(header->flags);
trie->count = CFSwapInt32LittleToHost(header->count);
trie->retain = 1;
}
return trie;
}
Boolean CFBurstTrieInsert(CFBurstTrieRef trie, CFStringRef term, CFRange termRange, CFIndex payload) {
return CFBurstTrieAddWithWeight(trie, term, termRange, 1, (uint32_t)payload);
}
Boolean CFBurstTrieAdd(CFBurstTrieRef trie, CFStringRef term, CFRange termRange, uint32_t payload) {
return CFBurstTrieAddWithWeight(trie, term, termRange, 1, payload);
}
Boolean CFBurstTrieInsertCharacters(CFBurstTrieRef trie, UniChar *chars, CFIndex numChars, CFIndex payload) {
return CFBurstTrieAddCharactersWithWeight(trie, chars, numChars, 1, (uint32_t)payload);
}
Boolean CFBurstTrieAddCharacters(CFBurstTrieRef trie, UniChar *chars, CFIndex numChars, uint32_t payload) {
return CFBurstTrieAddCharactersWithWeight(trie, chars, numChars, 1, payload);
}
Boolean CFBurstTrieInsertUTF8String(CFBurstTrieRef trie, UInt8 *chars, CFIndex numChars, CFIndex payload) {
return CFBurstTrieAddUTF8StringWithWeight(trie, chars, numChars, 1, (uint32_t)payload);
}
Boolean CFBurstTrieAddUTF8String(CFBurstTrieRef trie, UInt8 *chars, CFIndex numChars, uint32_t payload) {
return CFBurstTrieAddUTF8StringWithWeight(trie, chars, numChars, 1, payload);
}
Boolean CFBurstTrieInsertWithWeight(CFBurstTrieRef trie, CFStringRef term, CFRange termRange, CFIndex weight, CFIndex payload) {
return CFBurstTrieAddWithWeight(trie, term, termRange, weight, (uint32_t)payload);
}
Boolean CFBurstTrieAddWithWeight(CFBurstTrieRef trie, CFStringRef term, CFRange termRange, uint32_t weight, uint32_t payload) {
Boolean success = false;
CFIndex size = MAX_STRING_ALLOCATION_SIZE;
CFIndex bytesize = termRange.length * 4; //** 4-byte max character size
if (!trie->mapBase && termRange.length < MAX_STRING_SIZE && payload > 0) {
CFIndex length;
UInt8 buffer[MAX_STRING_ALLOCATION_SIZE + 1];
UInt8 *key = buffer;
if (bytesize >= size) {
size = bytesize;
key = (UInt8 *) malloc(sizeof(UInt8) * size + 1);
}
CFStringGetBytes(term, termRange, kCFStringEncodingUTF8, (UInt8)'-', (Boolean)0, key, size, &length);
key[length] = 0;
success = CFBurstTrieAddUTF8StringWithWeight(trie, key, length, weight, payload);
if (buffer != key) free(key);
}
return success;
}
Boolean CFBurstTrieInsertCharactersWithWeight(CFBurstTrieRef trie, UniChar *chars, CFIndex numChars, CFIndex weight, CFIndex payload) {
return CFBurstTrieAddCharactersWithWeight(trie, chars, numChars, weight, (uint32_t)payload);
}
Boolean CFBurstTrieAddCharactersWithWeight(CFBurstTrieRef trie, UniChar *chars, CFIndex numChars, uint32_t weight, uint32_t payload) {
Boolean success = false;
CFIndex size = MAX_STRING_ALLOCATION_SIZE;
CFIndex bytesize = numChars * 4; //** 4-byte max character size
if (!trie->mapBase && numChars < MAX_STRING_SIZE && payload > 0) {
CFIndex length;
UInt8 buffer[MAX_STRING_ALLOCATION_SIZE + 1];
UInt8 *key = buffer;
if (bytesize >= size) {
size = bytesize;
key = (UInt8 *) malloc(sizeof(UInt8) * size + 1);
}
length = burstTrieConvertCharactersToUTF8(chars, numChars, key);
key[length] = 0;
success = CFBurstTrieAddUTF8StringWithWeight(trie, key, length, weight, payload);
if (buffer != key) free(key);
}
return success;
}
Boolean CFBurstTrieInsertUTF8StringWithWeight(CFBurstTrieRef trie, UInt8 *chars, CFIndex numChars, CFIndex weight, CFIndex payload) {
return CFBurstTrieAddUTF8StringWithWeight(trie, chars, numChars, weight, (uint32_t)payload);
}
Boolean CFBurstTrieAddUTF8StringWithWeight(CFBurstTrieRef trie, UInt8 *chars, CFIndex numChars, uint32_t weight, uint32_t payload) {
CFBTInsertCode code = FailedInsert;
if (!trie->mapBase && numChars < MAX_STRING_SIZE*4 && payload > 0) {
code = addCFBurstTrieLevel(trie, &trie->root, chars, numChars, weight, payload);
if (code == NewTerm) trie->count++;
}
return code > FailedInsert;
}
Boolean CFBurstTrieFind(CFBurstTrieRef trie, CFStringRef term, CFRange termRange, CFIndex *payload) {
uint32_t p;
if (CFBurstTrieContains(trie, term, termRange, &p)) {
SetPayload(payload, p);
return true;
}
return false;
}
Boolean CFBurstTrieContains(CFBurstTrieRef trie, CFStringRef term, CFRange termRange, uint32_t *payload) {
Boolean success = false;
CFIndex size = MAX_STRING_ALLOCATION_SIZE;
CFIndex bytesize = termRange.length * 4; //** 4-byte max character size
if (termRange.length < MAX_STRING_SIZE) {
CFIndex length;
UInt8 buffer[MAX_STRING_ALLOCATION_SIZE+1];
UInt8 *key = buffer;
if (bytesize >= size) {
size = bytesize;
key = (UInt8 *) malloc(sizeof(UInt8) * size + 1);
}
CFStringGetBytes(term, termRange, kCFStringEncodingUTF8, (UInt8)'-', (Boolean)0, key, size, &length);
key[length] = 0;
success = CFBurstTrieContainsUTF8String(trie, key, length, payload);
if (buffer != key) free(key);
}
return success;
}
Boolean CFBurstTrieFindCharacters(CFBurstTrieRef trie, UniChar *chars, CFIndex numChars, CFIndex *payload) {
uint32_t p;
if (CFBurstTrieContainsCharacters(trie, chars, numChars, &p)) {
SetPayload(payload, p);
return true;
}
return false;
}
Boolean CFBurstTrieContainsCharacters(CFBurstTrieRef trie, UniChar *chars, CFIndex numChars, uint32_t *payload) {
Boolean success = false;
CFIndex size = MAX_STRING_ALLOCATION_SIZE;
CFIndex bytesize = numChars * 4; //** 4-byte max character size
if (numChars < MAX_STRING_SIZE) {
CFIndex length;
UInt8 buffer[MAX_STRING_ALLOCATION_SIZE + 1];
UInt8 *key = buffer;
if (bytesize >= size) {
size = bytesize;
key = (UInt8 *) malloc(sizeof(UInt8) * size + 1);
}
length = burstTrieConvertCharactersToUTF8(chars, numChars, key);
key[length] = 0;
success = CFBurstTrieContainsUTF8String(trie, key, length, payload);
if (buffer != key) free(key);
}
return success;
}
Boolean CFBurstTrieFindUTF8String(CFBurstTrieRef trie, UInt8 *key, CFIndex length, CFIndex *payload) {
uint32_t p;
if (CFBurstTrieContainsUTF8String(trie, key, length, &p)) {
SetPayload(payload, p);
return true;
}
return false;
}
Boolean CFBurstTrieContainsUTF8String(CFBurstTrieRef trie, UInt8 *key, CFIndex length, uint32_t *payload) {
Boolean success = false;
if (length < MAX_STRING_SIZE) {
if (trie->mapBase && ((fileHeader *)trie->mapBase)->signature == 0xbabeface) {
bool prefix = (trie->cflags & kCFBurstTriePrefixCompression);
success = burstTrieMappedFind((DiskTrieLevelRef)(trie->mapBase+CFSwapInt32LittleToHost((((uint32_t*)trie->mapBase)[1]))), trie->mapBase, key, length, payload, prefix);
} else if (trie->mapBase && trie->cflags & (kCFBurstTriePrefixCompression | kCFBurstTrieSortByKey)) {
_CFBurstTrieCursor cursor;
if (!CFBurstTrieSetCursorForBytes(trie, &cursor, key, length))
return FALSE;
return CFBurstTrieCursorGetPayload(&cursor, payload);
} else {
uint32_t found = 0;
void *cursor = 0;
traverseCFBurstTrieWithCursor(trie, key, length, &cursor, true, &found, containsKey);
if (found) SetPayload(payload, found);
success = found > 0;
}
}
return success;
}
Boolean CFBurstTrieSerialize(CFBurstTrieRef trie, CFStringRef path, CFBurstTrieOpts opts) {
Boolean success = false;
if (trie->mapBase) {
return success;
} else {
int fd;
char filename[PATH_MAX];
/* Check valid path name */
if (!CFStringGetCString(path, filename, PATH_MAX, kCFStringEncodingUTF8)) return success;
/* Check if file can be opened */
if ((fd=open(filename, CF_OPENFLGS|O_RDWR|O_CREAT|O_TRUNC, S_IRUSR|S_IWUSR)) < 0) return success;
if (CFBurstTrieSerializeWithFileDescriptor(trie, fd, opts)) success = true;
close(fd);
}
return success;
}
Boolean CFBurstTrieSerializeWithFileDescriptor(CFBurstTrieRef trie, int fd, CFBurstTrieOpts opts) {
Boolean success = false;
if (!trie->mapBase && fd >= 0) {
off_t start_offset = lseek(fd, 0, SEEK_END);
trie->cflags = opts;
trie->mapSize = serializeCFBurstTrie(trie, start_offset, fd);
#if DEPLOYMENT_TARGET_WINDOWS
HANDLE mappedFileHandle = (HANDLE)_get_osfhandle(fd);
// We need to make sure we have our own handle to keep this file open as long as the mmap lasts
DuplicateHandle(GetCurrentProcess(), mappedFileHandle, GetCurrentProcess(), &mappedFileHandle, 0, 0, DUPLICATE_SAME_ACCESS);
HANDLE mapHandle = CreateFileMapping(mappedFileHandle, NULL, PAGE_READONLY, 0, 0, NULL);
if (!mapHandle) return NULL;
char *map = (char *)MapViewOfFile(mapHandle, FILE_MAP_READ, 0, start_offset, trie->mapSize);
if (!map) return NULL;
trie->mapBase = map;
trie->mapHandle = mapHandle;
trie->mappedFileHandle = mappedFileHandle;
#else
trie->mapBase = mmap(0, trie->mapSize, PROT_READ, MAP_FILE|MAP_SHARED, fd, start_offset);
#endif
success = true;
}
return success;
}
void CFBurstTrieTraverse(CFBurstTrieRef trie, void *ctx, void (*callback)(void*, const UInt8*, uint32_t, uint32_t)) {
TrieHeader *header = (TrieHeader *)trie->mapBase;
if (!trie->mapBase || (header->signature == 0xcafebabe || header->signature == 0x0ddba11)) {
void *cursor = 0;
TraverseContext context;
context.context = ctx;
context.callback = callback;
traverseCFBurstTrieWithCursor(trie, (const uint8_t *)"", 0, &cursor, false, &context, foundKey);
}
}
void CFBurstTrieTraverseWithCursor(CFBurstTrieRef trie, const uint8_t *prefix, uint32_t prefixLen, void **cursor, void *ctx, bool (*callback)(void *, const uint8_t *, uint32_t, bool))
{
traverseCFBurstTrieWithCursor(trie, prefix, prefixLen, cursor, false, ctx, callback);
}
void CFBurstTriePrint(CFBurstTrieRef trie) {
}
CFIndex CFBurstTrieGetCount(CFBurstTrieRef trie) {
return trie->count;
}
CFBurstTrieRef CFBurstTrieRetain(CFBurstTrieRef trie) {
trie->retain++;
return trie;
}
void CFBurstTrieRelease(CFBurstTrieRef trie) {
trie->retain--;
if (trie->retain == 0) destroyCFBurstTrie(trie);
return;
}
Boolean CFBurstTrieSetCursorForBytes(CFBurstTrieRef trie, CFBurstTrieCursorRef cursor, const UInt8* bytes, CFIndex length)
{
if (!trie->mapBase || !(trie->cflags & (kCFBurstTriePrefixCompression | kCFBurstTrieSortByKey))) {
//fprintf(stderr, "CFBurstTrieCreateCursorForBytes() only support file based trie in prefix compression format.\n");
return FALSE;
}
TrieHeader *header = (TrieHeader*)trie->mapBase;
if (length < 0 || !trie)
return FALSE;
cursor->trie = trie;
if (trie->mapBase) {
cursor->cursorType = _kCFBurstTrieCursorMapType;
cursor->mapCursor.next = header->rootOffset;
cursor->mapCursor.isOnPage = FALSE;
cursor->mapCursor.entryOffsetInPage = 0;
cursor->mapCursor.offsetInEntry = 0;
cursor->mapCursor.payload = 0;
} else
assert(false);
if (!bytes || length == 0)
return TRUE;
return CFBurstTrieCursorAdvanceForBytes(cursor, bytes, length);
}
CFBurstTrieCursorRef CFBurstTrieCreateCursorForBytes(CFBurstTrieRef trie, const UInt8* bytes, CFIndex length)
{
CFBurstTrieCursorRef cursor = (CFBurstTrieCursorRef)calloc(sizeof(_CFBurstTrieCursor), 1);
if (!CFBurstTrieSetCursorForBytes(trie, cursor, bytes, length)) {
CFBurstTrieCursorRelease(cursor);
return NULL;
}
return cursor;
}
CFBurstTrieCursorRef CFBurstTrieCursorCreateByCopy(CFBurstTrieCursorRef cursor)
{
if (!cursor)
return NULL;
CFBurstTrieCursorRef newCursor = (CFBurstTrieCursorRef)calloc(sizeof(_CFBurstTrieCursor), 1);
switch (cursor->cursorType) {
case _kCFBurstTrieCursorMapType:
copyMapCursor(&cursor->mapCursor, &newCursor->mapCursor);
break;
case _kCFBurstTrieCursorTrieType:
assert(false);
break;
}
newCursor->cursorType = cursor->cursorType;
newCursor->trie = cursor->trie;
return newCursor;
}
Boolean CFBurstTrieCursorIsEqual(CFBurstTrieCursorRef lhs, CFBurstTrieCursorRef rhs)
{
if (lhs->trie != rhs->trie || lhs->cursorType != rhs->cursorType)
return FALSE;
if (lhs->cursorType == _kCFBurstTrieCursorMapType)
return areMapCursorsEqual(&lhs->mapCursor, &rhs->mapCursor);
else
return FALSE;
}
Boolean CFBurstTrieCursorAdvanceForBytes(CFBurstTrieCursorRef cursor, const UInt8* bytes, CFIndex length)
{
switch (cursor->cursorType) {
case _kCFBurstTrieCursorMapType: {
CompactMapCursor tempCursor;
copyMapCursor(&cursor->mapCursor, &tempCursor);
if (advanceMapCursor(cursor->trie, (CompactMapCursor*)&cursor->mapCursor, bytes, length))
return TRUE;
else {
copyMapCursor(&tempCursor, &cursor->mapCursor);
return FALSE;
}
}
case _kCFBurstTrieCursorTrieType:
return FALSE;
}
return FALSE;
}
Boolean CFBurstTrieCursorGetPayload(CFBurstTrieCursorRef cursor, uint32_t *payload)
{
switch (cursor->cursorType) {
case _kCFBurstTrieCursorMapType:
return getMapCursorPayload(cursor->trie, (CompactMapCursor*)&cursor->mapCursor, payload);
case _kCFBurstTrieCursorTrieType:
return FALSE;
}
return FALSE;
}
void CFBurstTrieCursorRelease(CFBurstTrieCursorRef cursor)
{
if (!cursor)
return;
free(cursor);
}
void CFBurstTrieTraverseFromCursor(CFBurstTrieCursorRef cursor, void *ctx, CFBurstTrieTraversalCallback callback)
{
if (!cursor)
return;
UInt8 *bytes = (UInt8*)calloc(1, MAX_KEY_LENGTH);
uint32_t capacity = MAX_KEY_LENGTH;
uint32_t length = 0;
Boolean stop = FALSE;
switch (cursor->cursorType) {
case _kCFBurstTrieCursorMapType: {
CompactMapCursor tempCursor;
copyMapCursor(&cursor->mapCursor, &tempCursor);
traverseFromMapCursor(cursor->trie, &tempCursor, bytes, capacity,length, &stop, ctx, callback);
break;
}
case _kCFBurstTrieCursorTrieType:
break;
}
free(bytes);
}
#if 0
#pragma mark -
#pragma mark Insertion
#endif
static ListNodeRef makeCFBurstTrieListNode(const uint8_t *key, uint32_t keylen, uint32_t weight, uint32_t payload) {
ListNodeRef node = (ListNodeRef) calloc(1, sizeof(*node) + keylen + 1);
memcpy(node->string, key, keylen);
node->string[keylen] = 0;
node->next = 0;
node->length = keylen;
node->weight = weight;
node->payload = payload;
return node;
}
static void addCFBurstTrieBurstLevel(CFBurstTrieRef trie, TrieLevelRef root, const uint8_t *key, uint32_t keylen, uint32_t weight, uint32_t payload) {
if (keylen) {
NextTrie next = root->slots[*key];
ListNodeRef newNode = makeCFBurstTrieListNode(key+1, keylen-1, weight, payload);
newNode->weight = weight;
newNode->next = (ListNodeRef) NextTrie_GetPtr(next);
next = (uintptr_t) newNode;
NextTrie_SetKind(next, ListKind);
root->slots[*key] = next;
} else {
// ** Handle payload.
root->weight = weight;
root->payload = payload;
}
}
static TrieLevelRef burstCFBurstTrieLevel(CFBurstTrieRef trie, ListNodeRef list, uint32_t listCount) {
TrieLevelRef newLevel = (TrieLevelRef) calloc(1, sizeof(struct _TrieLevel));
while (list) {
addCFBurstTrieBurstLevel(trie, newLevel, list->string, list->length, list->weight, list->payload);
ListNodeRef temp = list;
list = list->next;
free(temp);
}
return newLevel;
}
static CFBTInsertCode addCFBurstTrieListNode(CFBurstTrieRef trie, ListNodeRef list, const uint8_t *key, uint32_t keylen, uint32_t weight, uint32_t payload, uint32_t *listCount)
{
CFBTInsertCode code = FailedInsert;
uint32_t count = 1;
ListNodeRef last = list;
while (list) {
if (list->length == keylen && memcmp(key, list->string, keylen) == 0) {
list->weight += weight;
list->payload = payload;
code = ExistingTerm;
break;
} else {
count++;
last = list;
list = list->next;
}
}
if (!list) {
last->next = makeCFBurstTrieListNode(key, keylen, weight, payload);
code = NewTerm;
}
*listCount = count;
return code;
}
static CFBTInsertCode addCFBurstTrieLevel(CFBurstTrieRef trie, TrieLevelRef root, const uint8_t *key, uint32_t keylen, uint32_t weight, uint32_t payload)
{
CFBTInsertCode code = FailedInsert;
if (keylen) {
NextTrie next = root->slots[*key];
if (NextTrie_GetKind(next) == TrieKind) {
TrieLevelRef nextLevel = (TrieLevelRef) NextTrie_GetPtr(next);
code = addCFBurstTrieLevel(trie, nextLevel, key+1, keylen-1, weight, payload);
} else {
if (NextTrie_GetKind(next) == ListKind) {
uint32_t listCount;
ListNodeRef listNode = (ListNodeRef) NextTrie_GetPtr(next);
code = addCFBurstTrieListNode(trie, listNode, key+1, keylen-1, weight, payload, &listCount);
if (listCount > trie->containerSize) {
next = (uintptr_t) burstCFBurstTrieLevel(trie, listNode, listCount);
NextTrie_SetKind(next, TrieKind);
}
} else {
// ** Make a new list node
next = (uintptr_t) makeCFBurstTrieListNode(key+1, keylen-1, weight, payload);
NextTrie_SetKind(next, ListKind);
code = NewTerm;
}
root->slots[*key] = next;
}
} else {
// ** Handle payload
if (!root->weight) code = NewTerm;
else code = ExistingTerm;
root->weight += weight;
root->payload = payload;
}
return code;
}
#if 0
#pragma mark -
#pragma mark Searching
#endif
static void findCFBurstTrieList(CFBurstTrieRef trie, TrieCursor *cursor, void *ctx, bool (*callback)(void*, const uint8_t*, uint32_t, bool))
{
ListNodeRef list = (ListNodeRef)NextTrie_GetPtr(cursor->next);
int len = cursor->prefixlen-cursor->keylen;
len = len <= 0 ? 0 : len;
while (list) {
int lencompare = list->length-len;
if (list->length >= len &&
(len == 0 || memcmp(list->string, cursor->prefix+cursor->keylen, len) == 0)) {
memcpy(cursor->key+cursor->keylen, list->string, list->length);
cursor->key[cursor->keylen+list->length] = 0;
cursor->next = (NextTrie)list;
if (list->payload && callback(ctx, cursor->key, list->payload, lencompare==0)) return;
}
list = list->next;
}
}
static void findCFBurstTrieMappedPage(CFBurstTrieRef trie, MapCursor *cursor, void *ctx, bool (*callback)(void*, const uint8_t*, uint32_t, bool))
{
Page *page = (Page *)DiskNextTrie_GetPtr(trie->mapBase, cursor->next);
uint32_t end = page->length;
uint32_t cur = 0;
int len = cursor->prefixlen-cursor->keylen;
len = len <= 0 ? 0 : len;
if (trie->cflags & kCFBurstTriePrefixCompression) {
uint8_t pfx[CHARACTER_SET_SIZE];
PageEntryPacked *lastEntry = 0;
while (cur < end) {
PageEntryPacked *entry = (PageEntryPacked *)&page->data[cur];
int lencompare = (entry->strlen+entry->pfxLen)-len;
if (lastEntry && entry->pfxLen>lastEntry->pfxLen) memcpy(pfx+lastEntry->pfxLen, lastEntry->string, entry->pfxLen-lastEntry->pfxLen);
if (lencompare >= 0 &&
(len == 0 || (__builtin_memcmp(pfx, cursor->prefix+cursor->keylen, entry->pfxLen) == 0 &&
__builtin_memcmp(entry->string, cursor->prefix+cursor->keylen+entry->pfxLen, cursor->prefixlen-cursor->keylen-entry->pfxLen) == 0))) {
memcpy(cursor->key+cursor->keylen, pfx, entry->pfxLen);
memcpy(cursor->key+cursor->keylen+entry->pfxLen, entry->string, entry->strlen);
cursor->key[cursor->keylen+entry->pfxLen+entry->strlen] = 0;
if (entry->payload && callback(ctx, (const uint8_t *)cursor->key, entry->payload, lencompare==0)) return;
}
lastEntry = entry;
cur += sizeof(*entry) + entry->strlen;
}
} else {
while (cur < end) {
PageEntry *entry = (PageEntry *)&page->data[cur];
int lencompare = entry->strlen-len;
if (lencompare >= 0 && __builtin_memcmp(entry->string, cursor->prefix+cursor->keylen, len) == 0) {
memcpy(cursor->key+cursor->keylen, entry->string, entry->strlen);
cursor->key[cursor->keylen+entry->strlen] = 0;
if (entry->payload && callback(ctx, (const uint8_t *)cursor->key, entry->payload, lencompare==0)) return;