/
pathdirectory.cpp
1618 lines (1397 loc) · 49 KB
/
pathdirectory.cpp
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
/**
* @file pathdirectory.cpp
* @ingroup base
*
* @authors Copyright © 2003-2012 Jaakko Keränen <jaakko.keranen@iki.fi>
* @authors Copyright © 2006-2012 Daniel Swanson <danij@dengine.net>
*
* @par License
* GPL: http://www.gnu.org/licenses/gpl.html
*
* <small>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version. This program is distributed in the hope that it
* will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details. You should have received a copy of the GNU
* General Public License along with this program; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA</small>
*/
#include <ctype.h>
//#include "de_console.h"
#include <de/Error>
#include <de/Log>
#include <de/stringpool.h>
#include <de/memory.h>
#include "blockset.h"
#include "m_misc.h" // For M_NumDigits()
#if 0
#include "de_system.h"
#endif
#include "pathdirectory.h"
#if 0
static volatile uint pathDirectoryInstanceCount;
/// A mutex is used to prevent Data races in the node allocator.
static mutex_t nodeAllocator_Mutex;
/// Threaded access to the following Data is protected by nodeAllocator_Mutex:
/// Nodes are block-allocated from this set.
static blockset_t* NodeBlockSet;
/// Linked list of used directory nodes for re-use. Linked with de::PathDirectoryNode::next
static de::PathDirectoryNode* UsedNodes;
#endif
#ifdef LIBDENG_STACK_MONITOR
static void* stackStart;
static size_t maxStackDepth;
#endif
typedef struct pathconstructorparams_s {
de::PathDirectory* pd;
size_t length;
Str* dest;
char delimiter;
size_t delimiterLen;
} pathconstructorparams_t;
/**
* Recursive path constructor. First finds the root and the full length of the
* path (when descending), then allocates memory for the string, and finally
* copies each fragment with the delimiters (on the way out).
*/
static void pathConstructor(pathconstructorparams_t* parm, const de::PathDirectoryNode* trav)
{
DENG2_ASSERT(parm);
const Str* fragment = parm->pd->pathFragment(trav);
#ifdef LIBDENG_STACK_MONITOR
maxStackDepth = MAX_OF(maxStackDepth, stackStart - (void*)&fragment);
#endif
parm->length += Str_Length(fragment);
if(trav->parent())
{
// There also needs to be a separator.
parm->length += parm->delimiterLen;
// Descend to parent level.
pathConstructor(parm, trav->parent());
// Append the separator.
if(parm->delimiter)
Str_AppendCharWithoutAllocs(parm->dest, parm->delimiter);
}
else
{
// We've arrived at the deepest level. The full length is now known.
// Ensure there's enough memory for the string.
Str_ReserveNotPreserving(parm->dest, parm->length);
}
// Assemble the path by appending the fragment.
Str_AppendWithoutAllocs(parm->dest, fragment);
}
struct de::PathDirectory::Instance
{
de::PathDirectory* self;
/// Path name fragment intern pool.
StringPool* stringPool;
int flags; /// @see pathDirectoryFlags
/// Path node hashes.
de::PathDirectory::NodeHash* pathLeafHash;
de::PathDirectory::NodeHash* pathBranchHash;
/// Total number of unique paths in the directory.
uint size;
Instance(de::PathDirectory* d, int flags_)
: self(d), stringPool(0), flags(flags_), pathLeafHash(0), pathBranchHash(0), size(0)
{
#if 0
// We'll block-allocate nodes and maintain a list of unused ones
// to accelerate directory construction/population.
if(!nodeAllocator_Mutex)
{
nodeAllocator_Mutex = Sys_CreateMutex("PathDirectoryNodeAllocator_MUTEX");
Sys_Lock(nodeAllocator_Mutex);
NodeBlockSet = BlockSet_New(sizeof(de::PathDirectoryNode), 128);
UsedNodes = NULL;
Sys_Unlock(nodeAllocator_Mutex);
}
pathDirectoryInstanceCount += 1;
#endif
}
~Instance()
{
if(pathLeafHash)
{
delete pathLeafHash;
}
if(pathBranchHash)
{
delete pathBranchHash;
}
#if 0
if(--pathDirectoryInstanceCount == 0)
{
Sys_Lock(nodeAllocator_Mutex);
BlockSet_Delete(NodeBlockSet);
NodeBlockSet = NULL;
UsedNodes = NULL;
Sys_DestroyMutex(nodeAllocator_Mutex);
nodeAllocator_Mutex = 0;
}
#endif
}
void clearInternPool()
{
if(stringPool)
{
StringPool_Delete(stringPool);
stringPool = NULL;
}
}
de::PathDirectoryNode* findNode(de::PathDirectoryNode* parent,
pathdirectorynode_type_t nodeType, StringPoolId internId)
{
de::PathDirectory::NodeHash* ph = (nodeType == PT_LEAF? pathLeafHash : pathBranchHash);
if(ph)
{
ushort hash = StringPool_UserValue(stringPool, internId);
de::PathDirectory::NodeHash::const_iterator i = ph->find(hash);
while(i != ph->end() && i.key() == hash)
{
if(parent == (*i)->parent() && internId == (*i)->internId())
{
return *i;
}
++i;
}
}
return 0; // Not found.
}
StringPoolId internNameAndUpdateIdHashMap(const ddstring_t* name, ushort hash)
{
if(!stringPool)
{
stringPool = StringPool_New();
}
StringPoolId internId = StringPool_Intern(stringPool, name);
StringPool_SetUserValue(stringPool, internId, hash);
return internId;
}
/**
* @return [ a new | the ] directory node that matches the name and type and
* which has the specified parent node.
*/
de::PathDirectoryNode* direcNode(de::PathDirectoryNode* parent,
pathdirectorynode_type_t nodeType, const ddstring_t* name, char delimiter,
void* userData)
{
DENG2_ASSERT(name);
// Have we already encountered this?
StringPoolId internId = 0;
if(stringPool)
{
internId = StringPool_IsInterned(stringPool, name);
if(internId)
{
// The name is known. Perhaps we have.
de::PathDirectoryNode* node = findNode(parent, nodeType, internId);
if(node)
{
if(nodeType == PT_BRANCH || !(flags & PDF_ALLOW_DUPLICATE_LEAF))
return node;
}
}
}
/**
* A new node is needed.
*/
// Do we need a new name identifier (and hash)?
ushort hash;
if(!internId)
{
hash = hashPathFragment(Str_Text(name), Str_Length(name), delimiter);
internId = internNameAndUpdateIdHashMap(name, hash);
}
else
{
hash = self->hashForInternId(internId);
}
// Are we out of name indices?
if(!internId) return NULL;
de::PathDirectoryNode* node = newNode(self, nodeType, parent, internId, userData);
// Insert the new node into the path hash.
if(nodeType == PT_LEAF)
{
// Do we need to init the path hash?
if(!pathLeafHash)
{
pathLeafHash = new NodeHash;
}
pathLeafHash->insert(hash, node);
}
else // PT_BRANCH
{
// Do we need to init the path hash?
if(!pathBranchHash)
{
pathBranchHash = new NodeHash;
}
pathBranchHash->insert(hash, node);
}
return node;
}
/**
* The path is split into as many nodes as necessary. Parent links are set.
*
* @return The node that identifies the given path.
*/
de::PathDirectoryNode* buildDirecNodes(const char* path, char delimiter)
{
DENG2_ASSERT(path);
de::PathDirectoryNode* node = NULL, *parent = NULL;
// Continue splitting as long as there are parts.
AutoStr* part = AutoStr_NewStd();
const char* p = path;
while((p = Str_CopyDelim2(part, p, delimiter, CDF_OMIT_DELIMITER))) // Get the next part.
{
node = direcNode(parent, PT_BRANCH, part, delimiter, NULL);
/// @todo Do not error here. If we're out of storage undo this action and return.
if(!node)
{
throw de::Error("PathDirectory::buildDirecNodes",
de::String("Exhausted storage while attempting to insert nodes for path \"%1\".")
.arg(path));
}
parent = node;
}
if(!Str_IsEmpty(part))
{
node = direcNode(parent, PT_LEAF, part, delimiter, NULL);
/// @todo Do not error here. If we're out of storage undo this action and return.
if(!node)
{
throw de::Error("PathDirectory::buildDirecNodes",
de::String("Exhausted storage while attempting to insert nodes for path \"%1\".")
.arg(path));
}
}
return node;
}
/**
* @param node Node whose path to construct.
* @param constructedPath The constructed path is written here. Previous contents discarded.
* @param delimiter Character to use for separating fragments.
*
* @return @a constructedPath
*
* @todo This is a good candidate for result caching: the constructed path
* could be saved and returned on subsequent calls. Are there any circumstances
* in which the cached result becomes obsolete? -jk
*/
ddstring_t* constructPath(const de::PathDirectoryNode* node,
ddstring_t* constructedPath, char delimiter)
{
pathconstructorparams_t parm;
#ifdef LIBDENG_STACK_MONITOR
stackStart = &parm;
#endif
DENG2_ASSERT(node && constructedPath);
parm.dest = constructedPath;
parm.length = 0;
parm.pd = self;
parm.delimiter = delimiter;
parm.delimiterLen = (delimiter? 1 : 0);
// Include a terminating path separator for branches (directories).
if(node->type() == PT_BRANCH)
parm.length += parm.delimiterLen;
// Recursively construct the path from fragments and delimiters.
Str_Clear(constructedPath);
pathConstructor(&parm, node);
// Terminating delimiter for branches.
if(delimiter && node->type() == PT_BRANCH)
Str_AppendCharWithoutAllocs(constructedPath, delimiter);
DENG2_ASSERT(Str_Length(constructedPath) == parm.length);
#ifdef LIBDENG_STACK_MONITOR
LOG_AS("pathConstructor");
LOG_INFO("Max stack depth: %1 bytes") << maxStackDepth;
#endif
return constructedPath;
}
static de::PathDirectoryNode*
newNode(de::PathDirectory* directory, pathdirectorynode_type_t type,
de::PathDirectoryNode* parent, StringPoolId internId, void* userData)
{
de::PathDirectoryNode* node;
DENG2_ASSERT(directory);
#if 0
// Acquire a new node, either from the used list or the block allocator.
Sys_Lock(nodeAllocator_Mutex);
if(UsedNodes)
{
node = UsedNodes;
UsedNodes = node->next;
// Reconfigure the node.
node->next = NULL;
node->directory_ = directory;
node->type_ = type;
node->parent_ = parent;
node->pair.internId = internId;
node->pair.data = userData;
}
else
#endif
{
//void* element = BlockSet_Allocate(NodeBlockSet);
node = /*new (element)*/ new de::PathDirectoryNode(*directory, type, parent,
internId, userData);
}
#if 0
Sys_Unlock(nodeAllocator_Mutex);
#endif
return node;
}
static void collectPathsInHash(de::PathDirectory::NodeHash& ph, char delimiter,
ddstring_t** pathListAdr)
{
DENG2_FOR_EACH(i, ph, de::PathDirectory::NodeHash::const_iterator)
{
Str_Init(*pathListAdr);
(*i)->directory()->composePath(*i, (*pathListAdr), NULL, delimiter);
(*pathListAdr)++;
}
}
static void clearPathHash(de::PathDirectory::NodeHash& ph)
{
DENG2_FOR_EACH(i, ph, de::PathDirectory::NodeHash::iterator)
{
#if _DEBUG
if((*i)->userData())
{
LOG_AS("PathDirectory::clearPathHash");
LOG_ERROR("Node %p has non-NULL user data.") << (void*)(*i);
}
#endif
delete (*i);
}
ph.clear();
}
};
ushort de::PathDirectory::hashPathFragment(const char* fragment, size_t len, char delimiter)
{
ushort key = 0;
DENG2_ASSERT(fragment);
// Skip over any trailing delimiters.
const char* c = fragment + len - 1;
while(c >= fragment && *c && *c == delimiter) c--;
// Compose the hash.
int op = 0;
for(; c >= fragment && *c && *c != delimiter; c--)
{
switch(op)
{
case 0: key ^= tolower(*c); ++op; break;
case 1: key *= tolower(*c); ++op; break;
case 2: key -= tolower(*c); op=0; break;
}
}
return key % PATHDIRECTORY_PATHHASH_SIZE;
}
ushort de::PathDirectory::hashForInternId(StringPoolId internId)
{
DENG2_ASSERT(internId > 0);
return StringPool_UserValue(d->stringPool, internId);
}
de::PathDirectoryNode*
de::PathDirectory::insert(const char* path, char delimiter, void* userData)
{
de::PathDirectoryNode* node = d->buildDirecNodes(path, delimiter);
if(node)
{
// There is now one more unique path in the directory.
d->size += 1;
if(userData)
{
node->attachUserData(userData);
}
}
return node;
}
de::PathDirectory::PathDirectory(int flags)
{
d = new Instance(this, flags);
}
de::PathDirectory::~PathDirectory()
{
clear();
delete d;
}
uint de::PathDirectory::size() const
{
return d->size;
}
void de::PathDirectory::clear()
{
if(d->pathLeafHash)
{
d->clearPathHash(*d->pathLeafHash);
}
if(d->pathBranchHash)
{
d->clearPathHash(*d->pathBranchHash);
}
d->clearInternPool();
d->size = 0;
}
de::PathDirectoryNode* de::PathDirectory::find(int flags,
const char* searchPath, char delimiter)
{
PathDirectoryNode* foundNode = NULL;
if(searchPath && searchPath[0] && d->size)
{
PathMap mappedSearchPath;
PathMap_Initialize2(&mappedSearchPath, PathDirectory_HashPathFragment, searchPath, delimiter);
ushort hash = PathMap_Fragment(&mappedSearchPath, 0)->hash;
if(!(flags & PCF_NO_LEAF) && d->pathLeafHash)
{
de::PathDirectory::NodeHash* nodes = d->pathLeafHash;
de::PathDirectory::NodeHash::iterator i = nodes->find(hash);
for(; i != nodes->end() && i.key() == hash; ++i)
{
if((*i)->matchDirectory(flags, &mappedSearchPath))
{
// This is the node we're looking for - stop iteration.
foundNode = *i;
break;
}
}
}
if(!foundNode)
if(!(flags & PCF_NO_BRANCH) && d->pathBranchHash)
{
de::PathDirectory::NodeHash* nodes = d->pathBranchHash;
de::PathDirectory::NodeHash::iterator i = nodes->find(hash);
for(; i != nodes->end() && i.key() == hash; ++i)
{
if((*i)->matchDirectory(flags, &mappedSearchPath))
{
// This is the node we're looking for - stop iteration.
foundNode = *i;
break;
}
}
}
PathMap_Destroy(&mappedSearchPath);
}
return foundNode;
}
/**
* C wrapper API:
*/
#define D_TOINTERNAL(inst) \
(inst) != 0? reinterpret_cast<de::PathDirectory*>(inst) : NULL
#define D_TOINTERNAL_CONST(inst) \
(inst) != 0? reinterpret_cast<const de::PathDirectory*>(inst) : NULL
#define D_SELF(inst) \
DENG2_ASSERT(inst); \
de::PathDirectory* self = D_TOINTERNAL(inst)
#define D_SELF_CONST(inst) \
DENG2_ASSERT(inst); \
const de::PathDirectory* self = D_TOINTERNAL_CONST(inst)
PathDirectory* PathDirectory_NewWithFlags(int flags)
{
return reinterpret_cast<PathDirectory*>(new de::PathDirectory(flags));
}
PathDirectory* PathDirectory_New(void)
{
return reinterpret_cast<PathDirectory*>(new de::PathDirectory());
}
void PathDirectory_Delete(PathDirectory* pd)
{
if(pd)
{
D_SELF(pd);
delete self;
}
}
uint PathDirectory_Size(PathDirectory* pd)
{
D_SELF(pd);
return self->size();
}
void PathDirectory_Clear(PathDirectory* pd)
{
D_SELF(pd);
self->clear();
}
PathDirectoryNode* PathDirectory_Insert2(PathDirectory* pd, const char* path, char delimiter, void* userData)
{
D_SELF(pd);
return reinterpret_cast<PathDirectoryNode*>(self->insert(path, delimiter, userData));
}
PathDirectoryNode* PathDirectory_Insert(PathDirectory* pd, const char* path, char delimiter)
{
D_SELF(pd);
return reinterpret_cast<PathDirectoryNode*>(self->insert(path, delimiter));
}
static int iteratePathsInHash(PathDirectory* pd,
ushort hash, pathdirectorynode_type_t type, int flags, PathDirectoryNode* parent_,
int (*callback) (PathDirectoryNode* node, void* parameters), void* parameters)
{
int result = 0;
D_SELF(pd);
if(hash != PATHDIRECTORY_NOHASH && hash >= PATHDIRECTORY_PATHHASH_SIZE)
{
throw de::Error("iteratePathsInHash",
de::String("Invalid hash %1 (valid range is [0..%2]).")
.arg(hash).arg(PATHDIRECTORY_PATHHASH_SIZE-1));
}
de::PathDirectory::NodeHash* nodes = self->nodeHash(type);
if(nodes)
{
de::PathDirectoryNode* parent = reinterpret_cast<de::PathDirectoryNode*>(parent_);
// Are we iterating nodes with a known hash?
if(hash != PATHDIRECTORY_NOHASH)
{
// Yes.
de::PathDirectory::NodeHash::iterator i = nodes->find(hash);
for(; i != nodes->end() && i.key() == hash; ++i)
{
if(!((flags & PCF_MATCH_PARENT) && parent != (*i)->parent()))
{
result = callback(reinterpret_cast<PathDirectoryNode*>(*i), parameters);
if(result) break;
}
}
}
else
{
// No - iterate all nodes.
DENG2_FOR_EACH(i, *nodes, de::PathDirectory::NodeHash::iterator)
{
if(!((flags & PCF_MATCH_PARENT) && parent != (*i)->parent()))
{
result = callback(reinterpret_cast<PathDirectoryNode*>(*i), parameters);
if(result) break;
}
}
}
}
return result;
}
static int iteratePathsInHash_Const(const PathDirectory* pd,
ushort hash, pathdirectorynode_type_t type, int flags, const PathDirectoryNode* parent_,
int (*callback) (const PathDirectoryNode* node, void* parameters), void* parameters)
{
int result = 0;
D_SELF_CONST(pd);
if(hash != PATHDIRECTORY_NOHASH && hash >= PATHDIRECTORY_PATHHASH_SIZE)
{
throw de::Error("iteratePathsInHash_Const",
de::String("Invalid hash %1 (valid range is [0..%2]).")
.arg(hash).arg(PATHDIRECTORY_PATHHASH_SIZE-1));
}
const de::PathDirectory::NodeHash* nodes = self->nodeHash(type);
if(nodes)
{
const de::PathDirectoryNode* parent = reinterpret_cast<const de::PathDirectoryNode*>(parent_);
// Are we iterating nodes with a known hash?
if(hash != PATHDIRECTORY_NOHASH)
{
// Yes.
de::PathDirectory::NodeHash::const_iterator i = nodes->find(hash);
for(; i != nodes->end() && i.key() == hash; ++i)
{
if(!((flags & PCF_MATCH_PARENT) && parent != (*i)->parent()))
{
result = callback(reinterpret_cast<const PathDirectoryNode*>(*i), parameters);
if(result) break;
}
}
}
else
{
// No - iterate all nodes.
DENG2_FOR_EACH(i, *nodes, de::PathDirectory::NodeHash::const_iterator)
{
if(!((flags & PCF_MATCH_PARENT) && parent != (*i)->parent()))
{
result = callback(reinterpret_cast<const PathDirectoryNode*>(*i), parameters);
if(result) break;
}
}
}
}
return result;
}
int PathDirectory_Iterate2(PathDirectory* pd, int flags, PathDirectoryNode* parent,
ushort hash, pathdirectory_iteratecallback_t callback, void* parameters)
{
int result = 0;
if(callback)
{
if(!(flags & PCF_NO_LEAF))
result = iteratePathsInHash(pd, hash, PT_LEAF, flags, parent,
callback, parameters);
if(!result && !(flags & PCF_NO_BRANCH))
result = iteratePathsInHash(pd, hash, PT_BRANCH, flags, parent,
callback, parameters);
}
return result;
}
int PathDirectory_Iterate(PathDirectory* pd, int flags, PathDirectoryNode* parent,
ushort hash, pathdirectory_iteratecallback_t callback)
{
return PathDirectory_Iterate2(pd, flags, parent, hash, callback, NULL);
}
int PathDirectory_Iterate2_Const(const PathDirectory* pd, int flags, const PathDirectoryNode* parent,
ushort hash, pathdirectory_iterateconstcallback_t callback, void* parameters)
{
int result = 0;
if(callback)
{
if(!(flags & PCF_NO_LEAF))
result = iteratePathsInHash_Const(pd, hash, PT_LEAF, flags, parent,
callback, parameters);
if(!result && !(flags & PCF_NO_BRANCH))
result = iteratePathsInHash_Const(pd, hash, PT_BRANCH, flags, parent,
callback, parameters);
}
return result;
}
int PathDirectory_Iterate_Const(const PathDirectory* pd, int flags, const PathDirectoryNode* parent,
ushort hash, pathdirectory_iterateconstcallback_t callback)
{
return PathDirectory_Iterate2_Const(pd, flags, parent, hash, callback, NULL);
}
ddstring_t* PathDirectory_ComposePath(PathDirectory* pd, const PathDirectoryNode* node,
ddstring_t* path, int* length, char delimiter)
{
D_SELF(pd);
return self->composePath(reinterpret_cast<const de::PathDirectoryNode*>(node), path, length, delimiter);
}
const ddstring_t* PathDirectory_GetFragment(PathDirectory* pd, const PathDirectoryNode* node)
{
D_SELF(pd);
return self->pathFragment(reinterpret_cast<const de::PathDirectoryNode*>(node));
}
ddstring_t* PathDirectory_CollectPaths(PathDirectory* pd, int flags, char delimiter, size_t* count)
{
D_SELF(pd);
return self->collectPaths(flags, delimiter, count);
}
typedef struct {
int flags; /// @see pathComparisonFlags
PathMap* mappedSearchPath;
void* parameters;
pathdirectory_searchcallback_t callback;
PathDirectoryNode* foundNode;
} pathdirectorysearchworker_params_t;
static int PathDirectory_SearchWorker(PathDirectoryNode* node, void* parameters)
{
pathdirectorysearchworker_params_t* p = (pathdirectorysearchworker_params_t*)parameters;
DENG2_ASSERT(node && parameters);
if(p->callback(node, p->flags, p->mappedSearchPath, p->parameters))
{
p->foundNode = node;
return 1; // Stop iteration.
}
return 0; // Continue iteration.
}
PathDirectoryNode* PathDirectory_Search2(PathDirectory* pd, int flags,
PathMap* mappedSearchPath, pathdirectory_searchcallback_t callback, void* parameters)
{
DENG2_ASSERT(pd);
if(callback)
{
pathdirectorysearchworker_params_t p;
p.flags = flags;
p.mappedSearchPath = mappedSearchPath;
p.parameters = parameters;
p.callback = callback;
p.foundNode = NULL;
ushort hash = PathMap_Fragment(mappedSearchPath, 0)->hash;
if(!(flags & PCF_NO_LEAF))
{
if(iteratePathsInHash(pd, hash, PT_LEAF, flags, NULL,
PathDirectory_SearchWorker, (void*)&p))
{
return p.foundNode;
}
}
if(!(flags & PCF_NO_BRANCH))
{
if(iteratePathsInHash(pd, hash, PT_BRANCH, flags, NULL,
PathDirectory_SearchWorker, (void*)&p))
{
return p.foundNode;
}
}
}
return 0; // Not found.
}
PathDirectoryNode* PathDirectory_Search(PathDirectory* pd, int flags,
PathMap* mappedSearchPath, pathdirectory_searchcallback_t callback)
{
return PathDirectory_Search2(pd, flags, mappedSearchPath, callback, NULL);
}
PathDirectoryNode* PathDirectory_Find(PathDirectory* pd, int flags,
const char* searchPath, char delimiter)
{
D_SELF(pd);
return reinterpret_cast<PathDirectoryNode*>(self->find(flags, searchPath, delimiter));
}
ushort PathDirectory_HashPathFragment(const char* path, size_t len, char delimiter)
{
return de::PathDirectory::hashPathFragment(path, len, delimiter);
}
#if _DEBUG
void PathDirectory_DebugPrint(PathDirectory* pd, char delimiter)
{
if(!pd) return;
de::PathDirectory::debugPrint(D_TOINTERNAL(pd), delimiter);
}
#endif
const ddstring_t* de::PathDirectory::pathFragment(const de::PathDirectoryNode* node)
{
DENG2_ASSERT(node);
return StringPool_String(d->stringPool, node->internId());
}
ddstring_t* de::PathDirectory::composePath(const de::PathDirectoryNode* node,
ddstring_t* foundPath, int* length, char delimiter)
{
if(!foundPath)
{
if(length) composePath(node, NULL, length, delimiter);
return 0;
}
return d->constructPath(node, foundPath, delimiter);
}
de::PathDirectory::NodeHash*
de::PathDirectory::nodeHash(pathdirectorynode_type_t type) const
{
return (type == PT_LEAF? d->pathLeafHash : d->pathBranchHash);
}
ddstring_t* de::PathDirectory::collectPaths(int flags, char delimiter, size_t* retCount)
{
ddstring_t* paths = NULL;
size_t count = 0;
if(!(flags & PCF_NO_LEAF))
count += (d->pathLeafHash ? d->pathLeafHash->size() : 0);
if(!(flags & PCF_NO_BRANCH))
count += (d->pathBranchHash? d->pathBranchHash->size() : 0);
if(count)
{
// Uses malloc here because this is returned with the C wrapper.
paths = static_cast<ddstring_t*>(M_Malloc(sizeof *paths * count));
if(!paths)
{
throw de::Error("PathDirectory::collectPaths:",
de::String("Failed on allocation of %1 bytes for new path list.")
.arg(sizeof *paths * count));
}
ddstring_t* pathPtr = paths;
if(!(flags & PCF_NO_BRANCH) && d->pathBranchHash)
Instance::collectPathsInHash(*d->pathBranchHash, delimiter, &pathPtr);
if(!(flags & PCF_NO_LEAF) && d->pathLeafHash)
Instance::collectPathsInHash(*d->pathLeafHash, delimiter, &pathPtr);
}
if(retCount) *retCount = count;
return paths;
}
#if _DEBUG
static int C_DECL comparePaths(const void* a, const void* b)
{
return qstricmp(Str_Text((Str*)a), Str_Text((Str*)b));
}
void de::PathDirectory::debugPrint(de::PathDirectory* pd, char delimiter)
{
if(!pd) return;
LOG_AS("PathDirectory");
LOG_INFO("Directory [%p]:") << (void*)pd;
size_t numLeafs;
ddstring_t* pathList = pd->collectPaths(PT_LEAF, delimiter, &numLeafs);
if(pathList)
{
size_t n = 0;
qsort(pathList, numLeafs, sizeof *pathList, comparePaths);
do
{
LOG_INFO(" %s") << Str_Text(pathList + n);
Str_Free(pathList + n);
} while(++n < numLeafs);
M_Free(pathList);
}
LOG_INFO(" %lu %s in directory.") << numLeafs << (numLeafs==1? "path":"paths");
}
static void printDistributionOverviewElement(const int* colWidths, const char* name,
size_t numEmpty, size_t maxHeight, size_t numCollisions, size_t maxCollisions,
size_t sum, size_t total)
{
#if 0
DENG2_ASSERT(colWidths);
float coverage, collision, variance;
if(0 != total)
{
size_t sumSqr = sum*sum;
float mean = (signed)sum / total;
variance = ((signed)sumSqr - (signed)sum * mean) / (((signed)total)-1);
coverage = 100 / (float)PATHDIRECTORY_PATHHASH_SIZE * (PATHDIRECTORY_PATHHASH_SIZE - numEmpty);
collision = 100 / (float) total * numCollisions;
}
else
{
variance = coverage = collision = 0;
}
const int* col = colWidths;
Con_Printf("%*s ", *col++, name);
Con_Printf("%*lu ", *col++, (unsigned long)total);
Con_Printf("%*lu", *col++, PATHDIRECTORY_PATHHASH_SIZE - (unsigned long)numEmpty);
Con_Printf(":%-*lu ", *col++, (unsigned long)numEmpty);
Con_Printf("%*lu ", *col++, (unsigned long)maxCollisions);
Con_Printf("%*lu ", *col++, (unsigned long)numCollisions);
Con_Printf("%*.2f ", *col++, collision);
Con_Printf("%*.2f ", *col++, coverage);
Con_Printf("%*.2f ", *col++, variance);
Con_Printf("%*lu\n", *col++, (unsigned long)maxHeight);
#endif
}
static void printDistributionOverview(PathDirectory* pd,
size_t nodeCountSum[PATHDIRECTORYNODE_TYPE_COUNT],
size_t nodeCountTotal[PATHDIRECTORYNODE_TYPE_COUNT],
size_t nodeBucketCollisions[PATHDIRECTORYNODE_TYPE_COUNT], size_t nodeBucketCollisionsTotal,
size_t nodeBucketCollisionsMax[PATHDIRECTORYNODE_TYPE_COUNT], size_t /*nodeBucketCollisionsMaxTotal*/,
size_t nodeBucketEmpty[PATHDIRECTORYNODE_TYPE_COUNT], size_t nodeBucketEmptyTotal, size_t nodeBucketHeight,
size_t /*nodeCount*/[PATHDIRECTORYNODE_TYPE_COUNT])
{
#if 0
#define NUMCOLS 10/*type+count+used:+empty+collideMax+collideCount+collidePercent+coverage+variance+maxheight*/
DENG2_ASSERT(pd);
size_t collisionsMax = 0, countSum = 0, countTotal = 0;
for(int i = 0; i < PATHDIRECTORYNODE_TYPE_COUNT; ++i)
{
if(nodeBucketCollisionsMax[i] > collisionsMax)
collisionsMax = nodeBucketCollisionsMax[i];