forked from ValveSoftware/GameNetworkingSockets
-
Notifications
You must be signed in to change notification settings - Fork 15
/
utlrbtree.h
2093 lines (1740 loc) · 65.2 KB
/
utlrbtree.h
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 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $Header: $
// $NoKeywords: $
//=============================================================================//
#ifndef UTLRBTREE_H
#define UTLRBTREE_H
#include "utlmemory.h"
//-----------------------------------------------------------------------------
// Tool to generate a default compare function for any type that implements
// operator<, including all simple types
//-----------------------------------------------------------------------------
template <typename T >
class CDefOps
{
public:
static bool LessFunc( const T &lhs, const T &rhs ) { return ( lhs < rhs ); }
static bool LessFuncCtx( const T &lhs, const T &rhs, void *pCtx ) { return LessFunc( lhs, rhs ); }
};
#define DefLessFunc( type ) CDefOps<type>::LessFunc
#define DefLessFuncCtx( type ) CDefOps<type>::LessFuncCtx
template <typename T>
class CDefLess
{
public:
CDefLess() {}
CDefLess( int i ) {}
inline bool operator()( const T &lhs, const T &rhs ) const { return ( lhs < rhs ); }
inline bool operator!() const { return false; }
};
template <typename T>
class CDefLessReverse
{
public:
CDefLessReverse() {}
CDefLessReverse( int i ) {}
inline bool operator()( const T &lhs, const T &rhs ) const { return (lhs > rhs); }
inline bool operator!() const { return false; }
};
template <typename T>
class CDefLessPtr
{
public:
typedef T* PointerType_t;
CDefLessPtr() {}
CDefLessPtr( int i ) {}
inline bool operator()( const PointerType_t &lhs, const PointerType_t &rhs ) const { return ( *lhs < *rhs ); }
inline bool operator!() const { return false; }
};
typedef const char * PConstChar_t;
class CDefCaselessStringLess
{
public:
CDefCaselessStringLess() {}
CDefCaselessStringLess( int i ) {}
inline bool operator()( const PConstChar_t &lhs, const PConstChar_t &rhs ) const { return ( V_stricmp(lhs, rhs) < 0 ); }
inline bool operator!() const { return false; }
};
class CDefStringLess
{
public:
CDefStringLess() {}
CDefStringLess( int i ) {}
inline bool operator()( const PConstChar_t &lhs, const PConstChar_t &rhs ) const { return ( V_strcmp(lhs, rhs) < 0 ); }
inline bool operator!() const { return false; }
};
#define INVALID_RBTREE_IDX ((I)~0)
//-------------------------------------
inline bool StringLessThan( const char * const &lhs, const char * const &rhs) { return ( V_strcmp(lhs, rhs) < 0 ); }
inline bool CaselessStringLessThan( const char * const &lhs, const char * const &rhs ) { return ( V_stricmp(lhs, rhs) < 0 ); }
// Same as CaselessStringLessThan, but it ignores differences in / and \.
inline bool CaselessStringLessThanIgnoreSlashes( const char * const &lhs, const char * const &rhs )
{
const char *pa = lhs;
const char *pb = rhs;
while ( *pa && *pb )
{
char a = *pa;
char b = *pb;
// Check for dir slashes.
if ( a == '/' || a == '\\' )
{
if ( b != '/' && b != '\\' )
return ('/' < b);
}
else
{
if ( a >= 'a' && a <= 'z' )
a = 'A' + (a - 'a');
if ( b >= 'a' && b <= 'z' )
b = 'A' + (b - 'a');
if ( a > b )
return false;
else if ( a < b )
return true;
}
++pa;
++pb;
}
// Filenames also must be the same length.
if ( *pa != *pb )
{
// If pa shorter than pb then it's "less"
return ( !*pa );
}
return false;
}
//-------------------------------------
// inline these two templates to stop multiple definitions of the same code
template <> inline bool CDefOps<const char *>::LessFunc( const char * const &lhs, const char * const &rhs ) { return StringLessThan( lhs, rhs ); }
template <> inline bool CDefOps<char *>::LessFunc( char * const &lhs, char * const &rhs ) { return StringLessThan( lhs, rhs ); }
//-------------------------------------
#if (defined( _MSC_VER ) && _MSC_VER < 1600) || __cplusplus < 2011L
#define MAP_INDEX_TYPE( mapName ) int
#else
#define MAP_INDEX_TYPE( mapName ) \
decltype( (mapName).MaxElement() )
#endif
#define FOR_EACH_RBTREE( treeName, iteratorName ) \
for ( MAP_INDEX_TYPE(treeName) iteratorName = (treeName).FirstInorder(); iteratorName != (treeName).InvalidIndex(); iteratorName = (treeName).NextInorder( iteratorName ) )
// faster iteration, but in an unspecified order
#define FOR_EACH_RBTREE_FAST( treeName, iteratorName ) \
for ( MAP_INDEX_TYPE(treeName) iteratorName = 0; iteratorName < (treeName).MaxElement(); ++iteratorName ) if ( !(treeName).IsValidIndex( iteratorName ) ) continue; else
template <typename RBTREE_T>
void SetDefLessFunc( RBTREE_T &RBTree )
{
#if defined( _MSC_VER ) && _MSC_VER < 1600
RBTree.SetLessFunc( DefLessFunc( RBTREE_T::KeyType_t ) );
#else
RBTree.SetLessFunc( DefLessFunc( typename RBTREE_T::KeyType_t ) );
#endif
}
// inline implementation of a function usable by CDefLess to compare two parameters in-order
#define DECLARE_INLINE_OPERATOR_LESS_2( T, p1, p2 ) bool operator<( const T &rhs ) const { if ( p1 != rhs.p1 ) return p1 < rhs.p1; return p2 < rhs.p2; }
// For use with FindClosest
// Move these to a common area if anyone else ever uses them
enum CompareOperands_t
{
k_EEqual = 0x1,
k_EGreaterThan = 0x2,
k_ELessThan = 0x4,
k_EGreaterThanOrEqualTo = k_EGreaterThan | k_EEqual,
k_ELessThanOrEqualTo = k_ELessThan | k_EEqual,
};
template <class I>
class CDefRBTreeBalanceListener
{
public:
void OnRotateLeft( I node, I rightNode ) {}
void OnRotateRight( I node, I leftNode ) {}
void OnLinkToParent( I node ) {}
void OnPreUnlink( I node ) {}
void OnRelinkSuccessor( I node ) {}
};
template <class T, class I>
class CRBTreeBalanceListener
{
public:
CRBTreeBalanceListener() : m_pTarget( NULL ) { }
CRBTreeBalanceListener( T *pTarget ) : m_pTarget( pTarget ) { }
void OnRotateLeft( I node, I rightNode ) { if ( !m_pTarget ) return; m_pTarget->OnRotateLeft( node, rightNode); }
void OnRotateRight( I node, I leftNode ) { if ( !m_pTarget ) return; m_pTarget->OnRotateRight( node, leftNode); }
void OnLinkToParent( I node ) { if ( !m_pTarget ) return; m_pTarget->OnLinkToParent( node ); }
void OnPreUnlink( I node ) { if ( !m_pTarget ) return; m_pTarget->OnPreUnlink( node ); }
void OnRelinkSuccessor( I node ) { if ( !m_pTarget ) return; m_pTarget->OnRelinkSuccessor( node ); }
private:
T *m_pTarget;
};
namespace CUtlRBTreeInternal
{
template< class I >
struct Links_t
{
I m_Left;
I m_Right;
I m_Parent;
I m_Tag;
};
enum NodeColor_t
{
RED = 0,
BLACK
};
}
template < class I, class E >
class CUtlRBTreeBase
{
public:
CUtlRBTreeBase();
// Num elements
unsigned int Count() const;
// Max "size" of the vector
I MaxElement() const;
// Gets the root
I Root() const;
// Tests if root or leaf
bool IsRoot( I i ) const;
// Invalid index
static I InvalidIndex() { return INVALID_RBTREE_IDX; }
// First pre-order
I FirstPreorder() const;
I PrevPreorder( I i ) const;
protected:
// used in Links as the return value for InvalidIndex()
CUtlRBTreeInternal::Links_t<I> m_Sentinel;
// Checks if a node is valid and in the tree
bool _IsValidIndex( I i, size_t unNodeSize, void *pMemBase ) const;
// Gets at the links
CUtlRBTreeInternal::Links_t<I> const &_Links( I i, size_t unNodeSize, void *pMemBase ) const;
CUtlRBTreeInternal::Links_t<I> &_Links( I i, size_t unNodeSize, void *pMemBase );
// Gets the children
I _Parent( I i, size_t unNodeSize, void *pMemBase ) const;
I _LeftChild( I i, size_t unNodeSize, void *pMemBase ) const;
I _RightChild( I i, size_t unNodeSize, void *pMemBase ) const;
// Sets the children
void _SetParent( I i, I parent, size_t unNodeSize, void *pMemBase );
void _SetLeftChild( I i, I child, size_t unNodeSize, void *pMemBase );
void _SetRightChild( I i, I child, size_t unNodeSize, void *pMemBase );
bool _IsRed( I i, size_t unNodeSize, void *pMemBase ) const;
bool _IsBlack( I i, size_t unNodeSize, void *pMemBase ) const;
// Tests if a node is a left or right child
bool _IsLeftChild( I i, size_t unNodeSize, void *pMemBase ) const;
bool _IsRightChild( I i, size_t unNodeSize, void *pMemBase ) const;
// Sets/gets node color
CUtlRBTreeInternal::NodeColor_t _Color( I i, size_t unNodeSize, void *pMemBase ) const;
void _SetColor( I i, CUtlRBTreeInternal::NodeColor_t c, size_t unNodeSize, void *pMemBase );
void _RotateLeft(I i, size_t unNodeSize, void *pMemBase);
void _RotateRight(I i, size_t unNodeSize, void *pMemBase);
void _InsertRebalance(I i, size_t unNodeSize, void *pMemBase);
void _RemoveRebalance(I i, size_t unNodeSize, void *pMemBase);
void _Unlink( I elem, size_t unNodeSize, void *pMemBase );
// Sets the children
void _LinkToParent( I i, I parent, bool isLeft, size_t unNodeSize, void *pMemBase );
// Checks if the tree as a whole is valid
bool _IsValid( size_t unNodeSize, void *pMemBase ) const;
I _FirstInorder(size_t unNodeSize, void *pMemBase) const;
I _NextInorder( I i, size_t unNodeSize, void *pMemBase ) const;
I _PrevInorder( I i, size_t unNodeSize, void *pMemBase ) const;
I _LastInorder(size_t unNodeSize, void *pMemBase) const;
I _NextPreorder( I i, size_t unNodeSize, void *pMemBase ) const;
I _LastPreorder(size_t unNodeSize, void *pMemBase) const;
I _FirstPostorder(size_t unNodeSize, void *pMemBase) const;
I _NextPostorder( I i, size_t unNodeSize, void *pMemBase ) const;
int _Depth( I node, size_t unNodeSize, void *pMemBase ) const;
struct EmptyBaseOpt_t : E
{
EmptyBaseOpt_t() {}
EmptyBaseOpt_t( E init ) : E( init ) {}
void* m_pElements;
};
EmptyBaseOpt_t m_data;
inline void ResetDbgInfo( void *pMemBase )
{
m_data.m_pElements = pMemBase;
}
I m_Root;
I m_NumElements;
I m_FirstFree;
I m_TotalElements;
};
//-----------------------------------------------------------------------------
// A red-black binary search tree
//-----------------------------------------------------------------------------
template <class T, class I = int, typename L = bool (*)( const T &, const T & ), class E = CDefRBTreeBalanceListener< I > >
class CUtlRBTree : public CUtlRBTreeBase< I, E >
{
public:
typedef T KeyType_t;
typedef T ElemType_t;
typedef I IndexType_t;
// Less func typedef
// Returns true if the first parameter is "less" than the second
typedef L LessFunc_t;
typedef E BalanceListener_t;
// constructor, destructor
// Left at growSize = 0, the memory will first allocate 1 element and double in size
// at each increment.
// LessFunc_t is required, but may be set after the constructor using SetLessFunc() below
CUtlRBTree( int growSize = 0, int initSize = 0, const LessFunc_t &lessfunc = 0 );
CUtlRBTree( const LessFunc_t &lessfunc );
CUtlRBTree( const BalanceListener_t &eventListener);
~CUtlRBTree();
unsigned int NumAllocated() const;
// gets particular elements
T& Element( I i );
T const &Element( I i ) const;
T& operator[]( I i );
T const &operator[]( I i ) const;
T& ElementByLinearIndex( IndexType_t i );
const T& ElementByLinearIndex( IndexType_t i ) const;
CUtlRBTree<T, I, L, E>& operator=( const CUtlRBTree<T, I, L, E> &other );
// Gets the children
I Parent( I i ) const;
I LeftChild( I i ) const;
I RightChild( I i ) const;
// Tests if a node is a left or right child
bool IsLeftChild( I i ) const;
bool IsRightChild( I i ) const;
// Tests if root or leaf
bool IsLeaf( I i ) const;
// Checks if a node is valid and in the tree
bool IsValidIndex( I i ) const;
// Checks if a index is of range 0 to Count()-1
bool IsValidLinearIndex( I i ) const;
// Checks if the tree as a whole is valid
bool IsValid() const;
// returns the tree depth (not a very fast operation)
int Depth( I node ) const;
int Depth() const;
// Sets the less func
void SetLessFunc( const LessFunc_t &func );
// Allocation method
I NewNode( bool bConstructElement );
// Insert method (inserts in order)
I Insert( T const &insert, bool bInsertDuplicates = true );
void Insert( const T *pArray, int nItems, bool bInsertDuplicates = true );
// Insert with not found interface to match source engine branches
I InsertIfNotFound(T const &insert);
// FindOrInsert method (returns existing index, or inserts if not found)
I FindOrInsert( T const &insert );
// Find method
I Find( T const &search ) const;
// FindFirst method ( finds first inorder if there are duplicates )
I FindFirst( T const &search ) const;
// First element >= key
I FindClosest( T const &search, CompareOperands_t eFindCriteria ) const;
// Remove methods
void RemoveAt( I i );
bool Remove( T const &remove );
void RemoveAll();
void Purge();
bool HasElement( T const &search ) const;
// Allocation, deletion
void FreeNode( I i );
// Iteration
I FirstInorder() const;
I NextInorder( I i ) const;
I PrevInorder( I i ) const;
I LastInorder() const;
I NextPreorder( I i ) const;
I LastPreorder() const;
I FirstPostorder() const;
I NextPostorder( I i ) const;
// If you change the search key, this can be used to reinsert the
// element into the tree.
void Reinsert( I elem );
// swap in place
void Swap( CUtlRBTree< T, I, L, E > &that );
// If you build a container on top of RBTree you need this - otherwise you shouldnt use
// Insertion, removal
I InsertAt( I parent, bool leftchild, bool bConstructElement );
// If you build a container on top of RBTree you need this - otherwise you shouldnt use
// Inserts a node into the tree, doesn't copy the data in.
void FindInsertionPosition( T const &insert, bool bCheckForDuplicates, I &parent, bool &leftchild, bool &isDuplicate );
// Makes sure we have enough memory allocated to store a requested # of elements
void EnsureCapacity( int num );
int CubAllocated() { return m_Elements.CubAllocated(); }
I IteratorNext( I i ) const { return NextInorder( i ); }
I IteratorPrev( I i ) const { return i == INVALID_RBTREE_IDX ? LastInorder() : PrevInorder( i ); }
struct ProxyTypeIterateUnordered // "this" pointer is reinterpret_cast from CUtlRBTree!
{
typedef T ElemType_t;
typedef I IndexType_t;
T &Element( I i ) { return reinterpret_cast<CUtlRBTree*>(this)->Element( i ); }
const T &Element( I i ) const { return reinterpret_cast<const CUtlRBTree*>(this)->Element( i ); }
I IteratorNext( I i ) const
{
const CUtlRBTree* pTree = reinterpret_cast<const CUtlRBTree*>(this);
while ( ++i < pTree->MaxElement() )
{
if ( pTree->IsValidIndex( i ) )
return i;
}
return INVALID_RBTREE_IDX;
}
};
ProxyTypeIterateUnordered &IterateUnordered() { return *reinterpret_cast<ProxyTypeIterateUnordered*>(this); }
const ProxyTypeIterateUnordered &IterateUnordered() const { return *reinterpret_cast<const ProxyTypeIterateUnordered*>(this); }
static bool BDiffRBTrees( const CUtlRBTree<T, I, L, E> &rbTreeBase, const CUtlRBTree<T, I, L, E> &rbTreeCompare, CUtlRBTree<T, I, L, E> *prbTreeAdditions = NULL, CUtlRBTree<T, I, L, E> *prbTreeDeletions = NULL );
#ifdef DBGFLAG_VALIDATE
void Validate( CValidator &validator, const char *pchName );
#endif // DBGFLAG_VALIDATE
protected:
struct Node_t : public CUtlRBTreeInternal::Links_t<I>
{
T m_Data;
};
//
// Inline functions that just pass straight into base, but with extra params.
//
// This is done so the bulk of the code can be in the base class, but interfaces to
// these within child class code can be sane.
//
inline CUtlRBTreeInternal::Links_t<I> const &Links( I i ) const { return _Links( i, sizeof(Node_t), (void*)m_Elements.Base() ); }
inline CUtlRBTreeInternal::Links_t<I> &Links( I i ){ return this->_Links( i, sizeof(Node_t), (void*)m_Elements.Base() ); }
inline void SetParent( I i, I parent ) { _SetParent( i, parent, sizeof(Node_t), (void*)m_Elements.Base() ); }
inline void SetLeftChild( I i, I child ) { this->_SetLeftChild( i, child, sizeof(Node_t), (void*)m_Elements.Base() ); }
inline void SetRightChild( I i, I child ) { this->_SetRightChild( i, child, sizeof(Node_t), (void*)m_Elements.Base() ); }
// Checks if a link is red or black
inline bool IsRed( I i ) const { return _IsRed( i, sizeof(Node_t), (void*)m_Elements.Base() ); }
inline bool IsBlack( I i ) const { return _IsBlack( i, sizeof(Node_t), (void*)m_Elements.Base() ); }
// Sets/gets node color
inline CUtlRBTreeInternal::NodeColor_t Color( I i ) const { return _Color( i, sizeof(Node_t), (void*)m_Elements.Base() ); }
inline void SetColor( I i, CUtlRBTreeInternal::NodeColor_t c ) { return _SetColor( i, c, sizeof(Node_t), (void*)m_Elements.Base() ); }
// operations required to preserve tree balance
inline void RotateLeft(I i) { _RotateLeft( i, sizeof(Node_t), (void*)m_Elements.Base() ); }
inline void RotateRight(I i) { _RotateRight( i, sizeof(Node_t), (void*)m_Elements.Base() ); }
inline void InsertRebalance(I i) { _InsertRebalance( i, sizeof(Node_t), (void*)m_Elements.Base() ); }
inline void RemoveRebalance(I i) { _RemoveRebalance( i, sizeof(Node_t), (void*)m_Elements.Base() ); }
inline void Unlink( I elem ) { this->_Unlink( elem, sizeof(Node_t), (void*)m_Elements.Base() ); }
// Sets the children
inline void LinkToParent( I i, I parent, bool isLeft ) { this->_LinkToParent( i, parent, isLeft, sizeof(Node_t), (void*)m_Elements.Base() ); }
// copy constructors not allowed
CUtlRBTree( CUtlRBTree<T, I, L, E> const &tree );
// Remove and add back an element in the tree.
void Link( I elem );
// Used for sorting.
LessFunc_t m_LessFunc;
CUtlMemory<Node_t> m_Elements;
};
//-----------------------------------------------------------------------------
// constructor, destructor
//-----------------------------------------------------------------------------
template< class I, class E >
CUtlRBTreeBase< I, E >::CUtlRBTreeBase()
{
m_Root = INVALID_RBTREE_IDX;
m_NumElements = 0;
m_TotalElements = 0;
m_FirstFree = INVALID_RBTREE_IDX;
m_Sentinel.m_Left = m_Sentinel.m_Right = m_Sentinel.m_Parent = INVALID_RBTREE_IDX;
m_Sentinel.m_Tag = CUtlRBTreeInternal::BLACK;
}
template <class T, class I, typename L, class E>
inline CUtlRBTree<T, I, L, E>::CUtlRBTree( int growSize, int initSize, const LessFunc_t &lessfunc ) :
CUtlRBTreeBase< I, E >(),
m_LessFunc( lessfunc ),
m_Elements( growSize, initSize )
{
this->ResetDbgInfo( m_Elements.Base() );
}
template <class T, class I, typename L, class E>
inline CUtlRBTree<T, I, L, E>::CUtlRBTree( const LessFunc_t &lessfunc ) :
CUtlRBTreeBase< I, E >(),
m_Elements( 0, 0 ),
m_LessFunc( lessfunc )
{
this->ResetDbgInfo( m_Elements.Base() );
}
template <class T, class I, typename L, class E>
inline CUtlRBTree<T, I, L, E>::CUtlRBTree( const BalanceListener_t &eventListener) :
CUtlRBTreeBase< I, E >(),
m_Elements( 0, 0 ),
m_LessFunc( NULL )
{
CUtlRBTreeBase< I, E>::m_data = eventListener;
this->ResetDbgInfo( m_Elements.Base() );
}
template <class T, class I, typename L, class E>
inline CUtlRBTree<T, I, L, E>::~CUtlRBTree()
{
RemoveAll();
}
//-----------------------------------------------------------------------------
// gets particular elements
//-----------------------------------------------------------------------------
template <class T, class I, typename L, class E>
inline T &CUtlRBTree<T, I, L, E>::Element( I i )
{
return m_Elements[i].m_Data;
}
template <class T, class I, typename L, class E>
inline T const &CUtlRBTree<T, I, L, E>::Element( I i ) const
{
return m_Elements[i].m_Data;
}
template <class T, class I, typename L, class E>
inline T &CUtlRBTree<T, I, L, E>::operator[]( I i )
{
return Element(i);
}
template <class T, class I, typename L, class E>
inline T const &CUtlRBTree<T, I, L, E>::operator[]( I i ) const
{
return Element(i);
}
template <class T, class I, typename L, class E>
inline T &CUtlRBTree<T, I, L, E>::ElementByLinearIndex( IndexType_t i )
{
IndexType_t cElementsSeen = 0;
IndexType_t iterator = 0;
for ( ; iterator < CUtlRBTree<T,I,L,E>::MaxElement(); ++iterator )
{
if ( !IsValidIndex( iterator ) ) continue; else
{
if ( cElementsSeen++ == i )
break;
}
}
return m_Elements[iterator].m_Data;
}
template <class T, class I, typename L, class E>
inline const T &CUtlRBTree<T, I, L, E>::ElementByLinearIndex( IndexType_t i ) const
{
IndexType_t cElementsSeen = 0;
IndexType_t iterator = 0;
for ( ; iterator < CUtlRBTree<T,I,L,E>::MaxElement(); ++iterator )
{
if ( !IsValidIndex( iterator ) ) continue; else
{
if ( cElementsSeen == i )
break;
cElementsSeen++;
}
}
return m_Elements[iterator].m_Data;
}
template <class T, class I, typename L, class E>
inline bool CUtlRBTree<T, I, L, E>::IsValidLinearIndex( IndexType_t i ) const
{
return i >= 0 && i < (IndexType_t)CUtlRBTree<T,I,L,E>::Count();
}
template <class T, class I, typename L, class E>
inline CUtlRBTree<T, I, L, E>& CUtlRBTree<T, I, L, E>::operator=( const CUtlRBTree<T, I, L, E> &other )
{
RemoveAll();
EnsureCapacity( other.Count() );
m_LessFunc = other.m_LessFunc;
for ( I i = 0; i < other.MaxElement(); ++i )
{
if ( !other.IsValidIndex( i ) )
continue;
Insert( other[i] );
}
return *this;
}
//-----------------------------------------------------------------------------
//
// various accessors
//
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Gets the root
//-----------------------------------------------------------------------------
template < class I, class E >
inline I CUtlRBTreeBase< I, E >::Root() const
{
return m_Root;
}
//-----------------------------------------------------------------------------
// Num elements
//-----------------------------------------------------------------------------
template < class I, class E >
inline unsigned int CUtlRBTreeBase< I, E >::Count() const
{
return (unsigned int)m_NumElements;
}
//-----------------------------------------------------------------------------
// Num elements allocated
//-----------------------------------------------------------------------------
template <class T, class I, typename L, class E>
inline unsigned int CUtlRBTree<T, I, L, E>::NumAllocated() const
{
return (unsigned int)m_Elements.NumAllocated();
}
//-----------------------------------------------------------------------------
// Max "size" of the vector
//-----------------------------------------------------------------------------
template < class I, class E >
inline I CUtlRBTreeBase< I, E >::MaxElement() const
{
return (I)m_TotalElements;
}
//-----------------------------------------------------------------------------
// Gets the children
//-----------------------------------------------------------------------------
template <class T, class I, typename L, class E>
inline I CUtlRBTree<T, I, L, E>::Parent( I i ) const
{
return CUtlRBTreeBase< I, E >::_Parent( i, sizeof( Node_t ), (void *)m_Elements.Base() );
}
template < class I, class E >
inline I CUtlRBTreeBase< I, E >::_Parent( I i, size_t unNodeSize, void *pMemBase ) const
{
return _Links(i, unNodeSize, pMemBase ).m_Parent;
}
template <class T, class I, typename L, class E>
inline I CUtlRBTree<T, I, L, E>::LeftChild( I i ) const
{
return CUtlRBTreeBase< I, E >::_LeftChild( i, sizeof( Node_t ), (void *)m_Elements.Base() );
}
template < class I, class E >
inline I CUtlRBTreeBase< I, E >::_LeftChild( I i, size_t unNodeSize, void *pMemBase ) const
{
return _Links(i, unNodeSize, pMemBase ).m_Left;
}
template <class T, class I, typename L, class E>
inline I CUtlRBTree<T, I, L, E>::RightChild( I i ) const
{
return CUtlRBTreeBase< I, E >::_RightChild( i, sizeof( Node_t ), (void *)m_Elements.Base() );
}
template < class I, class E >
inline I CUtlRBTreeBase< I, E >::_RightChild( I i, size_t unNodeSize, void *pMemBase ) const
{
return _Links(i, unNodeSize, pMemBase ).m_Right;
}
//-----------------------------------------------------------------------------
// Tests if a node is a left or right child
//-----------------------------------------------------------------------------
template <class T, class I, typename L, class E>
inline bool CUtlRBTree<T, I, L, E>::IsLeftChild( I i ) const
{
return _IsLeftChild( i, sizeof( Node_t ), (void*)m_Elements.Base() );
}
template < class I, class E >
inline bool CUtlRBTreeBase< I, E >::_IsLeftChild( I i, size_t unNodeSize, void *pMemBase ) const
{
return _LeftChild(_Parent(i, unNodeSize, pMemBase), unNodeSize, pMemBase ) == i;
}
template <class T, class I, typename L, class E>
inline bool CUtlRBTree<T, I, L, E>::IsRightChild( I i ) const
{
return _IsRightChild( i, sizeof( Node_t ), (void*)m_Elements.Base() );
}
template < class I, class E >
inline bool CUtlRBTreeBase< I, E >::_IsRightChild( I i, size_t unNodeSize, void *pMemBase ) const
{
return _RightChild(_Parent(i, unNodeSize, pMemBase), unNodeSize, pMemBase ) == i;
}
//-----------------------------------------------------------------------------
// Tests if root or leaf
//-----------------------------------------------------------------------------
template < class I, class E >
inline bool CUtlRBTreeBase< I, E >::IsRoot( I i ) const
{
return i == m_Root;
}
template <class T, class I, typename L, class E>
inline bool CUtlRBTree<T, I, L, E>::IsLeaf( I i ) const
{
return (LeftChild(i) == INVALID_RBTREE_IDX ) && (RightChild(i) == INVALID_RBTREE_IDX );
}
//-----------------------------------------------------------------------------
// Checks if a node is valid and in the tree
// the sign-comparison supression is due to comparing index val < 0, which
// is never true for unsigned types, but specializing the template seems
// like overkill
//-----------------------------------------------------------------------------
template < class T, class I, typename L, class E>
inline bool CUtlRBTree< T, I, L, E>::IsValidIndex( I i ) const
{
return this->_IsValidIndex( i, sizeof( Node_t ), (void*)m_Elements.Base() );
}
template < class I, class E>
inline bool CUtlRBTreeBase< I, E>::_IsValidIndex( I i, size_t unNodeSize, void *pMemBase ) const
{
// gcc correctly notices that in many places we instantiate the template
// with an unsigned index type, and the i < 0 check is never true
#if defined (GNUC) || defined( COMPILER_SNC )
if ( i == INVALID_RBTREE_IDX || i >= MaxElement() ) // its outside the bounds of the base container
#else
if ( i < 0 || i >= MaxElement() ) // its outside the bounds of the base container
#endif
{
return false;
}
return _LeftChild(i, unNodeSize, pMemBase) != i;
}
//-----------------------------------------------------------------------------
// returns the tree depth (not a very fast operation)
//-----------------------------------------------------------------------------
template <class T, class I, typename L, class E>
inline int CUtlRBTree<T, I, L, E>::Depth() const
{
return Depth(CUtlRBTreeBase< I, E >::Root());
}
//-----------------------------------------------------------------------------
// Sets the children
//-----------------------------------------------------------------------------
template < class I, class E >
inline void CUtlRBTreeBase< I, E >::_SetParent( I i, I parent, size_t unSizeOfNode, void *pMemBase )
{
_Links( i, unSizeOfNode, pMemBase ).m_Parent = parent;
}
template < class I, class E >
inline void CUtlRBTreeBase< I, E >::_SetLeftChild( I i, I child, size_t unSizeOfNode, void *pMemBase )
{
_Links( i, unSizeOfNode, pMemBase ).m_Left = child;
}
template < class I, class E >
inline void CUtlRBTreeBase< I, E >::_SetRightChild( I i, I child, size_t unSizeOfNode, void *pMemBase )
{
_Links( i, unSizeOfNode, pMemBase ).m_Right = child;
}
//-----------------------------------------------------------------------------
// Gets at the links
//-----------------------------------------------------------------------------
template < class I, class E >
inline typename CUtlRBTreeInternal::Links_t<I> const &CUtlRBTreeBase< I, E >::_Links( I i, size_t unNodeSize, void *pMemBase ) const
{
return (i != INVALID_RBTREE_IDX ) ? *(CUtlRBTreeInternal::Links_t<I> *)( (uint8_t*)pMemBase + (unNodeSize*i) ) : m_Sentinel;
}
template < class I, class E >
inline typename CUtlRBTreeInternal::Links_t<I> &CUtlRBTreeBase< I, E >::_Links( I i, size_t unNodeSize, void *pMemBase )
{
DbgAssert(i != INVALID_RBTREE_IDX );
return *(CUtlRBTreeInternal::Links_t<I> *)( (uint8_t*)pMemBase + (unNodeSize*i) );
}
//-----------------------------------------------------------------------------
// Checks if a link is red or black
//-----------------------------------------------------------------------------
template < class I, class E >
inline bool CUtlRBTreeBase< I, E >::_IsRed( I i, size_t unNodeSize, void *pMemBase ) const
{
return (_Links(i, unNodeSize, pMemBase).m_Tag == CUtlRBTreeInternal::RED);
}
template < class I, class E >
inline bool CUtlRBTreeBase< I, E >::_IsBlack( I i, size_t unNodeSize, void *pMemBase ) const
{
return (_Links(i, unNodeSize, pMemBase).m_Tag == CUtlRBTreeInternal::BLACK);
}
//-----------------------------------------------------------------------------
// Sets/gets node color
//-----------------------------------------------------------------------------
template < class I, class E >
inline CUtlRBTreeInternal::NodeColor_t CUtlRBTreeBase< I, E >::_Color( I i, size_t unNodeSize, void *pMemBase ) const
{
return (CUtlRBTreeInternal::NodeColor_t)_Links( i, unNodeSize, pMemBase ).m_Tag;
}
template < class I, class E >
inline void CUtlRBTreeBase< I, E >::_SetColor( I i, CUtlRBTreeInternal::NodeColor_t c, size_t unNodeSize, void *pMemBase )
{
_Links( i, unNodeSize, pMemBase ).m_Tag = (I)c;
}
//-----------------------------------------------------------------------------
// Allocates/ deallocates nodes
//-----------------------------------------------------------------------------
template <class T, class I, typename L, class E>
I CUtlRBTree<T, I, L, E>::NewNode( bool bConstructElement )
{
I newElem;
// Nothing in the free list; add.
if (CUtlRBTreeBase< I, E >::m_FirstFree == INVALID_RBTREE_IDX )
{
if (m_Elements.NumAllocated() == CUtlRBTreeBase< I, E >::m_TotalElements)
m_Elements.Grow();
newElem = CUtlRBTreeBase< I, E >::m_TotalElements++;
}
else
{
newElem = CUtlRBTreeBase< I, E >::m_FirstFree;
CUtlRBTreeBase< I, E >::m_FirstFree = RightChild(CUtlRBTreeBase< I, E >::m_FirstFree);
}
#ifdef _DEBUG
// reset links to invalid....
CUtlRBTreeInternal::Links_t<I> &node = Links(newElem);
node.m_Left = node.m_Right = node.m_Parent = INVALID_RBTREE_IDX;
#endif
if ( bConstructElement )
Construct( &Element(newElem) );
this->ResetDbgInfo( m_Elements.Base() );
return newElem;
}
template <class T, class I, typename L, class E>
void CUtlRBTree<T, I, L, E>::FreeNode( I i )
{
DbgAssert( IsValidIndex(i) && (i != INVALID_RBTREE_IDX) );
Destruct( &Element(i) );
SetLeftChild( i, i ); // indicates it's in not in the tree
SetRightChild( i, CUtlRBTreeBase< I, E >::m_FirstFree );
CUtlRBTreeBase< I, E >::m_FirstFree = i;
}
//-----------------------------------------------------------------------------
// Rotates node i to the left
//-----------------------------------------------------------------------------
template < class I, class E >
void CUtlRBTreeBase< I, E >::_RotateLeft(I elem, size_t unNodeSize, void *pMemBase )
{
I rightchild = _RightChild(elem, unNodeSize, pMemBase );
_SetRightChild( elem, _LeftChild(rightchild, unNodeSize, pMemBase), unNodeSize, pMemBase );
if (_LeftChild(rightchild, unNodeSize, pMemBase) != INVALID_RBTREE_IDX )
_SetParent( _LeftChild(rightchild, unNodeSize, pMemBase), elem, unNodeSize, pMemBase );
if (rightchild != INVALID_RBTREE_IDX )
_SetParent( rightchild, _Parent(elem, unNodeSize, pMemBase), unNodeSize, pMemBase );
if (!IsRoot(elem))
{
if (_IsLeftChild(elem, unNodeSize, pMemBase))
_SetLeftChild( _Parent(elem, unNodeSize, pMemBase), rightchild, unNodeSize, pMemBase );
else
_SetRightChild( _Parent(elem, unNodeSize, pMemBase), rightchild, unNodeSize, pMemBase );
}
else
m_Root = rightchild;
_SetLeftChild( rightchild, elem, unNodeSize, pMemBase );