aboutsummaryrefslogtreecommitdiff
path: root/mp/src/public/tier1/utllinkedlist.h
blob: 46ac4a6ff1efb9d68011f5a4b1e177b557b797bc (plain) (blame)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: Linked list container class 
//
// $Revision: $
// $NoKeywords: $
//=============================================================================//

#ifndef UTLLINKEDLIST_H
#define UTLLINKEDLIST_H

#ifdef _WIN32
#pragma once
#endif

#include "tier0/basetypes.h"
#include "utlmemory.h"
#include "utlfixedmemory.h"
#include "utlblockmemory.h"
#include "tier0/dbg.h"

// define to enable asserts griping about things you shouldn't be doing with multilists
// #define MULTILIST_PEDANTIC_ASSERTS 1 

// This is a useful macro to iterate from head to tail in a linked list.
#define FOR_EACH_LL( listName, iteratorName ) \
	for( int iteratorName=(listName).Head(); (listName).IsUtlLinkedList && iteratorName != (listName).InvalidIndex(); iteratorName = (listName).Next( iteratorName ) )

//-----------------------------------------------------------------------------
// class CUtlLinkedList:
// description:
//		A lovely index-based linked list! T is the class type, I is the index
//		type, which usually should be an unsigned short or smaller. However,
//		you must avoid using 16- or 8-bit arithmetic on PowerPC architectures; 
//		therefore you should not use UtlLinkedListElem_t::I as the type of 
//		a local variable... ever. PowerPC integer arithmetic must be 32- or 
//		64-bit only; otherwise performance plummets.
//-----------------------------------------------------------------------------

template <class T, class I> 
struct UtlLinkedListElem_t
{
	T  m_Element;
	I  m_Previous;
	I  m_Next;

private:
	// No copy constructor for these...
	UtlLinkedListElem_t( const UtlLinkedListElem_t& );
};


// Class S is the storage type; the type you can use to save off indices in 
// persistent memory. Class I is the iterator type, which is what should be used
// in local scopes. I defaults to be S, but be aware that on the 360, 16-bit 
// arithmetic is catastrophically slow. Therefore you should try to save shorts
// in memory, but always operate on 32's or 64's in local scope.
// The ideal parameter order would be TSMI (you are more likely to override M than I)
// but since M depends on I we can't have the defaults in that order, alas.
template <class T, class S = unsigned short, bool ML = false, class I = S, class M = CUtlMemory< UtlLinkedListElem_t<T, S>, I > > 
class CUtlLinkedList
{
public:
	typedef T ElemType_t;
	typedef S IndexType_t; // should really be called IndexStorageType_t, but that would be a huge change
	typedef I IndexLocalType_t;
	typedef M MemoryAllocator_t;
	static const bool IsUtlLinkedList = true; // Used to match this at compiletime 

	// constructor, destructor
	CUtlLinkedList( int growSize = 0, int initSize = 0 );
	~CUtlLinkedList();

	// gets particular elements
	T&         Element( I i );
	T const&   Element( I i ) const;
	T&         operator[]( I i );
	T const&   operator[]( I i ) const;

	// Make sure we have a particular amount of memory
	void EnsureCapacity( int num );

	void SetGrowSize( int growSize );

	// Memory deallocation
	void Purge();

	// Delete all the elements then call Purge.
	void PurgeAndDeleteElements();
	
	// Insertion methods....
	I	InsertBefore( I before );
	I	InsertAfter( I after );
	I	AddToHead( ); 
	I	AddToTail( );

	I	InsertBefore( I before, T const& src );
	I	InsertAfter( I after, T const& src );
	I	AddToHead( T const& src ); 
	I	AddToTail( T const& src );

	// Find an element and return its index or InvalidIndex() if it couldn't be found.
	I		Find( const T &src ) const;
	
	// Look for the element. If it exists, remove it and return true. Otherwise, return false.
	bool	FindAndRemove( const T &src );

	// Removal methods
	void	Remove( I elem );
	void	RemoveAll();

	// Allocation/deallocation methods
	// If multilist == true, then list list may contain many
	// non-connected lists, and IsInList and Head + Tail are meaningless...
	I		Alloc( bool multilist = false );
	void	Free( I elem );

	// list modification
	void	LinkBefore( I before, I elem );
	void	LinkAfter( I after, I elem );
	void	Unlink( I elem );
	void	LinkToHead( I elem );
	void	LinkToTail( I elem );

	// invalid index (M will never allocate an element at this index)
	inline static S  InvalidIndex()  { return ( S )M::InvalidIndex(); }

	// Is a given index valid to use? (representible by S and not the invalid index)
	static bool IndexInRange( I index );

	inline static size_t ElementSize() { return sizeof( ListElem_t ); }

	// list statistics
	int	Count() const;
	I	MaxElementIndex() const;
	I	NumAllocated( void ) const { return m_NumAlloced; }

	// Traversing the list
	I  Head() const;
	I  Tail() const;
	I  Previous( I i ) const;
	I  Next( I i ) const;

	// STL compatible const_iterator class
	template < typename List_t >
	class _CUtlLinkedList_constiterator_t
	{
	public:
		typedef typename List_t::ElemType_t ElemType_t;
		typedef typename List_t::IndexType_t IndexType_t;

		// Default constructor -- gives a currently unusable iterator.
		_CUtlLinkedList_constiterator_t()
			: m_list( 0 )
			, m_index( List_t::InvalidIndex() )
		{
		}
		// Normal constructor.
		_CUtlLinkedList_constiterator_t( const List_t& list, IndexType_t index )
			: m_list( &list )
			, m_index( index )
		{
		}

		// Pre-increment operator++. This is the most efficient increment
		// operator so it should always be used.
		_CUtlLinkedList_constiterator_t& operator++()
		{
			m_index = m_list->Next( m_index );
			return *this;
		}
		// Post-increment operator++. This is less efficient than pre-increment.
		_CUtlLinkedList_constiterator_t operator++(int)
		{
			// Copy ourselves.
			_CUtlLinkedList_constiterator_t temp = *this;
			// Increment ourselves.
			++*this;
			// Return the copy.
			return temp;
		}

		// Pre-decrement operator--. This is the most efficient decrement
		// operator so it should always be used.
		_CUtlLinkedList_constiterator_t& operator--()
		{
			Assert( m_index != m_list->Head() );
			if ( m_index == m_list->InvalidIndex() )
			{
				m_index = m_list->Tail();
			}
			else
			{
				m_index = m_list->Previous( m_index );
			}
			return *this;
		}
		// Post-decrement operator--. This is less efficient than post-decrement.
		_CUtlLinkedList_constiterator_t operator--(int)
		{
			// Copy ourselves.
			_CUtlLinkedList_constiterator_t temp = *this;
			// Decrement ourselves.
			--*this;
			// Return the copy.
			return temp;
		}

		bool operator==( const _CUtlLinkedList_constiterator_t& other) const
		{
			Assert( m_list == other.m_list );
			return m_index == other.m_index;
		}

		bool operator!=( const _CUtlLinkedList_constiterator_t& other) const
		{
			Assert( m_list == other.m_list );
			return m_index != other.m_index;
		}

		const ElemType_t& operator*() const
		{
			return m_list->Element( m_index );
		}

		const ElemType_t* operator->() const
		{
			return (&**this);
		}

	protected:
		// Use a pointer rather than a reference so that we can support
		// assignment of iterators.
		const List_t* m_list;
		IndexType_t m_index;
	};

	// STL compatible iterator class, using derivation so that a non-const
	// list can return a const_iterator.
	template < typename List_t >
	class _CUtlLinkedList_iterator_t : public _CUtlLinkedList_constiterator_t< List_t >
	{
	public:
		typedef typename List_t::ElemType_t ElemType_t;
		typedef typename List_t::IndexType_t IndexType_t;
		typedef _CUtlLinkedList_constiterator_t< List_t > Base;

		// Default constructor -- gives a currently unusable iterator.
		_CUtlLinkedList_iterator_t()
		{
		}
		// Normal constructor.
		_CUtlLinkedList_iterator_t( const List_t& list, IndexType_t index )
			: _CUtlLinkedList_constiterator_t< List_t >( list, index )
		{
		}

		// Pre-increment operator++. This is the most efficient increment
		// operator so it should always be used.
		_CUtlLinkedList_iterator_t& operator++()
		{
			Base::m_index = Base::m_list->Next( Base::m_index );
			return *this;
		}
		// Post-increment operator++. This is less efficient than pre-increment.
		_CUtlLinkedList_iterator_t operator++(int)
		{
			// Copy ourselves.
			_CUtlLinkedList_iterator_t temp = *this;
			// Increment ourselves.
			++*this;
			// Return the copy.
			return temp;
		}

		// Pre-decrement operator--. This is the most efficient decrement
		// operator so it should always be used.
		_CUtlLinkedList_iterator_t& operator--()
		{
			Assert( Base::m_index != Base::m_list->Head() );
			if ( Base::m_index == Base::m_list->InvalidIndex() )
			{
				Base::m_index = Base::m_list->Tail();
			}
			else
			{
				Base::m_index = Base::m_list->Previous( Base::m_index );
			}
			return *this;
		}
		// Post-decrement operator--. This is less efficient than post-decrement.
		_CUtlLinkedList_iterator_t operator--(int)
		{
			// Copy ourselves.
			_CUtlLinkedList_iterator_t temp = *this;
			// Decrement ourselves.
			--*this;
			// Return the copy.
			return temp;
		}

		ElemType_t& operator*() const
		{
			// Const_cast to allow sharing the implementation with the
			// base class.
			List_t* pMutableList = const_cast<List_t*>( Base::m_list );
			return pMutableList->Element( Base::m_index );
		}

		ElemType_t* operator->() const
		{
			return (&**this);
		}
	};

	typedef _CUtlLinkedList_constiterator_t<CUtlLinkedList<T, S, ML, I, M> > const_iterator;
	typedef _CUtlLinkedList_iterator_t<CUtlLinkedList<T, S, ML, I, M> > iterator;
	const_iterator begin() const
	{
		return const_iterator( *this, Head() );
	}
	iterator begin()
	{
		return iterator( *this, Head() );
	}

	const_iterator end() const
	{
		return const_iterator( *this, InvalidIndex() );
	}
	iterator end()
	{
		return iterator( *this, InvalidIndex() );
	}

	// Are nodes in the list or valid?
	bool  IsValidIndex( I i ) const;
	bool  IsInList( I i ) const;
   
protected:

	// What the linked list element looks like
	typedef UtlLinkedListElem_t<T, S>  ListElem_t;

	// constructs the class
	I		AllocInternal( bool multilist = false );
	void ConstructList();
	
	// Gets at the list element....
	ListElem_t& InternalElement( I i ) { return m_Memory[i]; }
	ListElem_t const& InternalElement( I i ) const { return m_Memory[i]; }

	// copy constructors not allowed
	CUtlLinkedList( CUtlLinkedList<T, S, ML, I, M> const& list ) { Assert(0); }

	M	m_Memory;
	I	m_Head;
	I	m_Tail;
	I	m_FirstFree;
	I	m_ElementCount;		// The number actually in the list
	I	m_NumAlloced;		// The number of allocated elements
	typename M::Iterator_t	m_LastAlloc; // the last index allocated

	// For debugging purposes; 
	// it's in release builds so this can be used in libraries correctly
	ListElem_t  *m_pElements;

	FORCEINLINE M const &Memory( void ) const
	{
		return m_Memory;
	}

	void ResetDbgInfo()
	{
		m_pElements = m_Memory.Base();
	}

private:
	// Faster version of Next that can only be used from tested code internal
	// to this class, such as Find(). It avoids the cost of checking the index
	// validity, which is a big win on debug builds.
	I  PrivateNext( I i ) const;
};


// this is kind of ugly, but until C++ gets templatized typedefs in C++0x, it's our only choice
template < class T >
class CUtlFixedLinkedList : public CUtlLinkedList< T, int, true, int, CUtlFixedMemory< UtlLinkedListElem_t< T, int > > >
{
public:
	CUtlFixedLinkedList( int growSize = 0, int initSize = 0 )
		: CUtlLinkedList< T, int, true, int, CUtlFixedMemory< UtlLinkedListElem_t< T, int > > >( growSize, initSize ) {}

	typedef CUtlLinkedList< T, int, true, int, CUtlFixedMemory< UtlLinkedListElem_t< T, int > > > BaseClass;
	bool IsValidIndex( int i ) const
	{
		if ( !BaseClass::Memory().IsIdxValid( i ) )
			return false;

#ifdef _DEBUG // it's safe to skip this here, since the only way to get indices after m_LastAlloc is to use MaxElementIndex
		if ( BaseClass::Memory().IsIdxAfter( i, this->m_LastAlloc ) )
		{
			Assert( 0 );
			return false; // don't read values that have been allocated, but not constructed
		}
#endif

		return ( BaseClass::Memory()[ i ].m_Previous != i ) || ( BaseClass::Memory()[ i ].m_Next == i );
	}

private:
	int	MaxElementIndex() const { Assert( 0 ); return BaseClass::InvalidIndex(); } // fixedmemory containers don't support iteration from 0..maxelements-1
	void ResetDbgInfo() {}
};

// this is kind of ugly, but until C++ gets templatized typedefs in C++0x, it's our only choice
template < class T, class I = unsigned short >
class CUtlBlockLinkedList : public CUtlLinkedList< T, I, true, I, CUtlBlockMemory< UtlLinkedListElem_t< T, I >, I > >
{
public:
	CUtlBlockLinkedList( int growSize = 0, int initSize = 0 )
		: CUtlLinkedList< T, I, true, I, CUtlBlockMemory< UtlLinkedListElem_t< T, I >, I > >( growSize, initSize ) {}
protected:
	void ResetDbgInfo() {}
};


//-----------------------------------------------------------------------------
// constructor, destructor
//-----------------------------------------------------------------------------

template <class T, class S, bool ML, class I, class M>
CUtlLinkedList<T,S,ML,I,M>::CUtlLinkedList( int growSize, int initSize ) :
	m_Memory( growSize, initSize ), m_LastAlloc( m_Memory.InvalidIterator() )
{
	// Prevent signed non-int datatypes
	COMPILE_TIME_ASSERT( sizeof(S) == 4 || ( ( (S)-1 ) > 0 ) );
	ConstructList();
	ResetDbgInfo();
}

template <class T, class S, bool ML, class I, class M>
CUtlLinkedList<T,S,ML,I,M>::~CUtlLinkedList( ) 
{
	RemoveAll();
}

template <class T, class S, bool ML, class I, class M>
void CUtlLinkedList<T,S,ML,I,M>::ConstructList()
{
	m_Head = InvalidIndex(); 
	m_Tail = InvalidIndex();
	m_FirstFree = InvalidIndex();
	m_ElementCount = 0;
	m_NumAlloced = 0;
}


//-----------------------------------------------------------------------------
// gets particular elements
//-----------------------------------------------------------------------------

template <class T, class S, bool ML, class I, class M>
inline T& CUtlLinkedList<T,S,ML,I,M>::Element( I i )
{
	return m_Memory[i].m_Element; 
}

template <class T, class S, bool ML, class I, class M>
inline T const& CUtlLinkedList<T,S,ML,I,M>::Element( I i ) const
{
	return m_Memory[i].m_Element; 
}

template <class T, class S, bool ML, class I, class M>
inline T& CUtlLinkedList<T,S,ML,I,M>::operator[]( I i )        
{ 
	return m_Memory[i].m_Element; 
}

template <class T, class S, bool ML, class I, class M>
inline T const& CUtlLinkedList<T,S,ML,I,M>::operator[]( I i ) const 
{
	return m_Memory[i].m_Element; 
}

//-----------------------------------------------------------------------------
// list statistics
//-----------------------------------------------------------------------------

template <class T, class S, bool ML, class I, class M>
inline int CUtlLinkedList<T,S,ML,I,M>::Count() const      
{ 
#ifdef MULTILIST_PEDANTIC_ASSERTS
	AssertMsg( !ML, "CUtlLinkedList::Count() is meaningless for linked lists." );
#endif
	return m_ElementCount; 
}

template <class T, class S, bool ML, class I, class M>
inline I CUtlLinkedList<T,S,ML,I,M>::MaxElementIndex() const   
{
	return m_Memory.NumAllocated();
}


//-----------------------------------------------------------------------------
// Traversing the list
//-----------------------------------------------------------------------------

template <class T, class S, bool ML, class I, class M>
inline I  CUtlLinkedList<T,S,ML,I,M>::Head() const  
{ 
	return m_Head; 
}

template <class T, class S, bool ML, class I, class M>
inline I  CUtlLinkedList<T,S,ML,I,M>::Tail() const  
{ 
	return m_Tail; 
}

template <class T, class S, bool ML, class I, class M>
inline I  CUtlLinkedList<T,S,ML,I,M>::Previous( I i ) const  
{ 
	Assert( IsValidIndex(i) ); 
	return InternalElement(i).m_Previous; 
}

template <class T, class S, bool ML, class I, class M>
inline I  CUtlLinkedList<T,S,ML,I,M>::Next( I i ) const  
{ 
	Assert( IsValidIndex(i) ); 
	return InternalElement(i).m_Next; 
}

template <class T, class S, bool ML, class I, class M>
inline I  CUtlLinkedList<T,S,ML,I,M>::PrivateNext( I i ) const  
{ 
	return InternalElement(i).m_Next; 
}


//-----------------------------------------------------------------------------
// Are nodes in the list or valid?
//-----------------------------------------------------------------------------

#pragma warning(push)
#pragma warning( disable: 4310 ) // Allows "(I)(S)M::INVALID_INDEX" below
template <class T, class S, bool ML, class I, class M>
inline bool CUtlLinkedList<T,S,ML,I,M>::IndexInRange( I index ) // Static method
{
	// Since S is not necessarily the type returned by M, we need to check that M returns indices
	// which are representable by S. A common case is 'S === unsigned short', 'I == int', in which
	// case CUtlMemory will have 'InvalidIndex == (int)-1' (which casts to 65535 in S), and will
	// happily return elements at index 65535 and above.

	// Do some static checks here:
	//  'I' needs to be able to store 'S'
	COMPILE_TIME_ASSERT( sizeof(I) >= sizeof(S) );
	//  'S' should be unsigned (to avoid signed arithmetic errors for plausibly exhaustible ranges)
	COMPILE_TIME_ASSERT( ( sizeof(S) > 2 ) || ( ( (S)-1 ) > 0 ) );
	//  M::INVALID_INDEX should be storable in S to avoid ambiguities (e.g. with 65536)
	COMPILE_TIME_ASSERT( ( M::INVALID_INDEX == -1 ) || ( M::INVALID_INDEX == (S)M::INVALID_INDEX ) );

	return ( ( (S)index == index ) && ( (S)index != InvalidIndex() ) );
}
#pragma warning(pop)

template <class T, class S, bool ML, class I, class M>
inline bool CUtlLinkedList<T,S,ML,I,M>::IsValidIndex( I i ) const  
{
	if ( !m_Memory.IsIdxValid( i ) )
		return false;

	if ( m_Memory.IsIdxAfter( i, m_LastAlloc ) )
		return false; // don't read values that have been allocated, but not constructed

	return ( m_Memory[ i ].m_Previous != i ) || ( m_Memory[ i ].m_Next == i );
}

template <class T, class S, bool ML, class I, class M>
inline bool CUtlLinkedList<T,S,ML,I,M>::IsInList( I i ) const
{
	if ( !m_Memory.IsIdxValid( i ) || m_Memory.IsIdxAfter( i, m_LastAlloc ) )
		return false; // don't read values that have been allocated, but not constructed

	return Previous( i ) != i;
}

/*
template <class T>
inline bool CUtlFixedLinkedList<T>::IsInList( int i ) const
{
	return m_Memory.IsIdxValid( i ) && (Previous( i ) != i);
}
*/

//-----------------------------------------------------------------------------
// Makes sure we have enough memory allocated to store a requested # of elements
//-----------------------------------------------------------------------------

template< class T, class S, bool ML, class I, class M >
void CUtlLinkedList<T,S,ML,I,M>::EnsureCapacity( int num )
{
	MEM_ALLOC_CREDIT_CLASS();
	m_Memory.EnsureCapacity(num);
	ResetDbgInfo();
}

template< class T, class S, bool ML, class I, class M >
void CUtlLinkedList<T,S,ML,I,M>::SetGrowSize( int growSize )
{
	RemoveAll();
	m_Memory.Init( growSize );
	ResetDbgInfo();
}


//-----------------------------------------------------------------------------
// Deallocate memory
//-----------------------------------------------------------------------------

template <class T, class S, bool ML, class I, class M>
void  CUtlLinkedList<T,S,ML,I,M>::Purge()
{
	RemoveAll();

	m_Memory.Purge();
	m_FirstFree = InvalidIndex();
	m_NumAlloced = 0;

	//Routing "m_LastAlloc = m_Memory.InvalidIterator();" through a local const to sidestep an internal compiler error on 360 builds
	const typename M::Iterator_t scInvalidIterator = m_Memory.InvalidIterator();
	m_LastAlloc = scInvalidIterator;
	ResetDbgInfo();
}


template<class T, class S, bool ML, class I, class M>
void CUtlLinkedList<T,S,ML,I,M>::PurgeAndDeleteElements()
{
	I iNext;
	for( I i=Head(); i != InvalidIndex(); i=iNext )
	{
		iNext = Next(i);
		delete Element(i);
	}

	Purge();
}


//-----------------------------------------------------------------------------
// Node allocation/deallocation
//-----------------------------------------------------------------------------
template <class T, class S, bool ML, class I, class M>
I CUtlLinkedList<T,S,ML,I,M>::AllocInternal( bool multilist )
{
	Assert( !multilist || ML );
#ifdef MULTILIST_PEDANTIC_ASSERTS
	Assert( multilist == ML );
#endif
	I elem;
	if ( m_FirstFree == InvalidIndex() )
	{
		Assert( m_Memory.IsValidIterator( m_LastAlloc ) || m_ElementCount == 0 );

		typename M::Iterator_t it = m_Memory.IsValidIterator( m_LastAlloc ) ? m_Memory.Next( m_LastAlloc ) : m_Memory.First();

		if ( !m_Memory.IsValidIterator( it ) )
		{
			MEM_ALLOC_CREDIT_CLASS();
			m_Memory.Grow();
			ResetDbgInfo();

			it = m_Memory.IsValidIterator( m_LastAlloc ) ? m_Memory.Next( m_LastAlloc ) : m_Memory.First();

			Assert( m_Memory.IsValidIterator( it ) );
			if ( !m_Memory.IsValidIterator( it ) )
			{
				// We rarely if ever handle alloc failure. Continuing leads to corruption.
				Error( "CUtlLinkedList overflow! (exhausted memory allocator)\n" );
				return InvalidIndex();
			}
		}

		// We can overflow before the utlmemory overflows, since S != I
		if ( !IndexInRange( m_Memory.GetIndex( it ) ) )
		{
			// We rarely if ever handle alloc failure. Continuing leads to corruption.
			Error( "CUtlLinkedList overflow! (exhausted index range)\n" );
			return InvalidIndex();
		}

		m_LastAlloc = it;
		elem = m_Memory.GetIndex( m_LastAlloc );
		m_NumAlloced++;
	} 
	else
	{
		elem = m_FirstFree;
		m_FirstFree = InternalElement( m_FirstFree ).m_Next;
	}

	if ( !multilist )
	{
		InternalElement( elem ).m_Next = elem;
		InternalElement( elem ).m_Previous = elem;
	}
	else
	{
		InternalElement( elem ).m_Next = InvalidIndex();
		InternalElement( elem ).m_Previous = InvalidIndex();
	}

	return elem;
}

template <class T, class S, bool ML, class I, class M>
I CUtlLinkedList<T,S,ML,I,M>::Alloc( bool multilist )
{
	I elem = AllocInternal( multilist );
	if ( elem == InvalidIndex() )
		return elem;

	Construct( &Element(elem) );

	return elem;
}

template <class T, class S, bool ML, class I, class M>
void  CUtlLinkedList<T,S,ML,I,M>::Free( I elem )
{
	Assert( IsValidIndex(elem) && IndexInRange( elem ) );
	Unlink(elem);

	ListElem_t &internalElem = InternalElement(elem);
	Destruct( &internalElem.m_Element );
	internalElem.m_Next = m_FirstFree;
	m_FirstFree = elem;
}

//-----------------------------------------------------------------------------
// Insertion methods; allocates and links (uses default constructor)
//-----------------------------------------------------------------------------

template <class T, class S, bool ML, class I, class M>
I CUtlLinkedList<T,S,ML,I,M>::InsertBefore( I before )
{
	// Make a new node
	I   newNode = AllocInternal();
	if ( newNode == InvalidIndex() )
		return newNode;

	// Link it in
	LinkBefore( before, newNode );
	
	// Construct the data
	Construct( &Element(newNode) );
	
	return newNode;
}

template <class T, class S, bool ML, class I, class M>
I CUtlLinkedList<T,S,ML,I,M>::InsertAfter( I after )
{
	// Make a new node
	I   newNode = AllocInternal();
	if ( newNode == InvalidIndex() )
		return newNode;

	// Link it in
	LinkAfter( after, newNode );
	
	// Construct the data
	Construct( &Element(newNode) );
	
	return newNode;
}

template <class T, class S, bool ML, class I, class M>
inline I CUtlLinkedList<T,S,ML,I,M>::AddToHead( ) 
{ 
	return InsertAfter( InvalidIndex() ); 
}

template <class T, class S, bool ML, class I, class M>
inline I CUtlLinkedList<T,S,ML,I,M>::AddToTail( ) 
{ 
	return InsertBefore( InvalidIndex() ); 
}


//-----------------------------------------------------------------------------
// Insertion methods; allocates and links (uses copy constructor)
//-----------------------------------------------------------------------------

template <class T, class S, bool ML, class I, class M>
I CUtlLinkedList<T,S,ML,I,M>::InsertBefore( I before, T const& src )
{
	// Make a new node
	I   newNode = AllocInternal();
	if ( newNode == InvalidIndex() )
		return newNode;

	// Link it in
	LinkBefore( before, newNode );
	
	// Construct the data
	CopyConstruct( &Element(newNode), src );
	
	return newNode;
}

template <class T, class S, bool ML, class I, class M>
I CUtlLinkedList<T,S,ML,I,M>::InsertAfter( I after, T const& src )
{
	// Make a new node
	I   newNode = AllocInternal();
	if ( newNode == InvalidIndex() )
		return newNode;

	// Link it in
	LinkAfter( after, newNode );
	
	// Construct the data
	CopyConstruct( &Element(newNode), src );
	
	return newNode;
}

template <class T, class S, bool ML, class I, class M>
inline I CUtlLinkedList<T,S,ML,I,M>::AddToHead( T const& src ) 
{ 
	return InsertAfter( InvalidIndex(), src ); 
}

template <class T, class S, bool ML, class I, class M>
inline I CUtlLinkedList<T,S,ML,I,M>::AddToTail( T const& src ) 
{ 
	return InsertBefore( InvalidIndex(), src ); 
}


//-----------------------------------------------------------------------------
// Removal methods
//-----------------------------------------------------------------------------

template<class T, class S, bool ML, class I, class M>
I CUtlLinkedList<T,S,ML,I,M>::Find( const T &src ) const
{
	// Cache the invalidIndex to avoid two levels of function calls on each iteration.
	I invalidIndex = InvalidIndex();
	for ( I i=Head(); i != invalidIndex; i = PrivateNext( i ) )
	{
		if ( Element( i ) == src )
			return i;
	}
	return InvalidIndex();
}


template<class T, class S, bool ML, class I, class M>
bool CUtlLinkedList<T,S,ML,I,M>::FindAndRemove( const T &src )
{
	I i = Find( src );
	if ( i == InvalidIndex() )
	{
		return false;
	}
	else
	{
		Remove( i );
		return true;
	}
}


template <class T, class S, bool ML, class I, class M>
void  CUtlLinkedList<T,S,ML,I,M>::Remove( I elem )
{
	Free( elem );
}

template <class T, class S, bool ML, class I, class M>
void  CUtlLinkedList<T,S,ML,I,M>::RemoveAll()
{
	// Have to do some convoluted stuff to invoke the destructor on all
	// valid elements for the multilist case (since we don't have all elements
	// connected to each other in a list).

	if ( m_LastAlloc == m_Memory.InvalidIterator() )
	{
		Assert( m_Head == InvalidIndex() );
		Assert( m_Tail == InvalidIndex() );
		Assert( m_FirstFree == InvalidIndex() );
		Assert( m_ElementCount == 0 );
		return;
	}

	if ( ML )
	{
		for ( typename M::Iterator_t it = m_Memory.First(); it != m_Memory.InvalidIterator(); it = m_Memory.Next( it ) )
		{
			I i = m_Memory.GetIndex( it );
			if ( IsValidIndex( i ) ) // skip elements already in the free list
			{
				ListElem_t &internalElem = InternalElement( i );
				Destruct( &internalElem.m_Element );
				internalElem.m_Previous = i;
				internalElem.m_Next = m_FirstFree;
				m_FirstFree = i;
			}

			if ( it == m_LastAlloc )
				break; // don't destruct elements that haven't ever been constructed
		}
	}
	else
	{
		I i = Head();
		I next;
		while ( i != InvalidIndex() )
		{
			next = Next( i );
			ListElem_t &internalElem = InternalElement( i );
			Destruct( &internalElem.m_Element );
			internalElem.m_Previous = i;
			internalElem.m_Next = next == InvalidIndex() ? m_FirstFree : next;
			i = next;
		}
		if ( Head() != InvalidIndex() )
		{
			m_FirstFree = Head();
		}
	}

	// Clear everything else out
	m_Head = InvalidIndex(); 
	m_Tail = InvalidIndex();
	m_ElementCount = 0;
}


//-----------------------------------------------------------------------------
// list modification
//-----------------------------------------------------------------------------

template <class T, class S, bool ML, class I, class M>
void  CUtlLinkedList<T,S,ML,I,M>::LinkBefore( I before, I elem )
{
	Assert( IsValidIndex(elem) );
	
	// Unlink it if it's in the list at the moment
	Unlink(elem);
	
	ListElem_t * RESTRICT pNewElem = &InternalElement(elem);
	
	// The element *after* our newly linked one is the one we linked before.
	pNewElem->m_Next = before;
	
	S newElem_mPrevious; // we need to hang on to this for the compairson against InvalidIndex()
					// below; otherwise we get a a load-hit-store on pNewElem->m_Previous, even
					// with RESTRICT
	if (before == InvalidIndex())
	{
		// In this case, we're linking to the end of the list, so reset the tail
		newElem_mPrevious = m_Tail;
		pNewElem->m_Previous = m_Tail;
		m_Tail = elem;
	}
	else
	{
		// Here, we're not linking to the end. Set the prev pointer to point to
		// the element we're linking.
		Assert( IsInList(before) );
		ListElem_t * RESTRICT beforeElem = &InternalElement(before);
		pNewElem->m_Previous = newElem_mPrevious = beforeElem->m_Previous;
		beforeElem->m_Previous = elem;
	}
	
	// Reset the head if we linked to the head of the list
	if (newElem_mPrevious == InvalidIndex())
		m_Head = elem;
	else
		InternalElement(newElem_mPrevious).m_Next = elem;
	
	// one more element baby
	++m_ElementCount;
}

template <class T, class S, bool ML, class I, class M>
void  CUtlLinkedList<T,S,ML,I,M>::LinkAfter( I after, I elem )
{
	Assert( IsValidIndex(elem) );
	
	// Unlink it if it's in the list at the moment
	if ( IsInList(elem) )
		Unlink(elem);
	
	ListElem_t& newElem = InternalElement(elem);
	
	// The element *before* our newly linked one is the one we linked after
	newElem.m_Previous = after;
	if (after == InvalidIndex())
	{
		// In this case, we're linking to the head of the list, reset the head
		newElem.m_Next = m_Head;
		m_Head = elem;
	}
	else
	{
		// Here, we're not linking to the end. Set the next pointer to point to
		// the element we're linking.
		Assert( IsInList(after) );
		ListElem_t& afterElem = InternalElement(after);
		newElem.m_Next = afterElem.m_Next;
		afterElem.m_Next = elem;
	}
	
	// Reset the tail if we linked to the tail of the list
	if (newElem.m_Next == InvalidIndex())
		m_Tail = elem;
	else
		InternalElement(newElem.m_Next).m_Previous = elem;
	
	// one more element baby
	++m_ElementCount;
}

template <class T, class S, bool ML, class I, class M>
void  CUtlLinkedList<T,S,ML,I,M>::Unlink( I elem )
{
	Assert( IsValidIndex(elem) );
	if (IsInList(elem))
	{
		ListElem_t * RESTRICT pOldElem = &m_Memory[ elem ];

		// If we're the first guy, reset the head
		// otherwise, make our previous node's next pointer = our next
		if ( pOldElem->m_Previous != InvalidIndex() )
		{
			m_Memory[ pOldElem->m_Previous ].m_Next = pOldElem->m_Next;
		}
		else
		{
			m_Head = pOldElem->m_Next;
		}

		// If we're the last guy, reset the tail
		// otherwise, make our next node's prev pointer = our prev
		if ( pOldElem->m_Next != InvalidIndex() )
		{
			m_Memory[ pOldElem->m_Next ].m_Previous = pOldElem->m_Previous;
		}
		else
		{
			m_Tail = pOldElem->m_Previous;
		}

		// This marks this node as not in the list, 
		// but not in the free list either
		pOldElem->m_Previous = pOldElem->m_Next = elem;

		// One less puppy
		--m_ElementCount;
	}
}

template <class T, class S, bool ML, class I, class M>
inline void CUtlLinkedList<T,S,ML,I,M>::LinkToHead( I elem ) 
{
	LinkAfter( InvalidIndex(), elem ); 
}

template <class T, class S, bool ML, class I, class M>
inline void CUtlLinkedList<T,S,ML,I,M>::LinkToTail( I elem ) 
{
	LinkBefore( InvalidIndex(), elem ); 
}


//-----------------------------------------------------------------------------
// Class to drop in to replace a CUtlLinkedList that needs to be more memory agressive
//-----------------------------------------------------------------------------

DECLARE_POINTER_HANDLE( UtlPtrLinkedListIndex_t ); // to enforce correct usage

template < typename T >
class CUtlPtrLinkedList
{
public:
	CUtlPtrLinkedList()
		: m_pFirst( NULL ),
		m_nElems( 0 )
	{
		COMPILE_TIME_ASSERT( sizeof(IndexType_t) == sizeof(Node_t *) );
	}

	~CUtlPtrLinkedList()
	{
		RemoveAll();
	}

	typedef UtlPtrLinkedListIndex_t IndexType_t;

	T &operator[]( IndexType_t i )			
	{ 
		return (( Node_t * )i)->elem; 
	}

	const T &operator[]( IndexType_t i ) const
	{ 
		return (( Node_t * )i)->elem; 
	}

	IndexType_t	AddToTail()								
	{ 
		return DoInsertBefore( (IndexType_t)m_pFirst, NULL );
	}

	IndexType_t	AddToTail( T const& src )
	{ 
		return DoInsertBefore( (IndexType_t)m_pFirst, &src );
	}

	IndexType_t	AddToHead()								
	{ 
		IndexType_t result = DoInsertBefore( (IndexType_t)m_pFirst, NULL );
		m_pFirst = ((Node_t *)result);
		return result;
	}

	IndexType_t	AddToHead( T const& src )
	{ 
		IndexType_t result = DoInsertBefore( (IndexType_t)m_pFirst, &src );
		m_pFirst = ((Node_t *)result);
		return result;
	}

	IndexType_t InsertBefore( IndexType_t before )
	{
		return DoInsertBefore( before, NULL );
	}

	IndexType_t InsertAfter( IndexType_t after )
	{
		Node_t *pBefore = ((Node_t *)after)->next;
		return DoInsertBefore( pBefore, NULL );
	}

	IndexType_t InsertBefore( IndexType_t before, T const& src  )
	{
		return DoInsertBefore( before, &src );
	}

	IndexType_t InsertAfter( IndexType_t after, T const& src  )
	{
		Node_t *pBefore = ((Node_t *)after)->next;
		return DoInsertBefore( pBefore, &src );
	}

	void Remove( IndexType_t elem )
	{ 
		Node_t *p = (Node_t *)elem;

		if ( p->pNext == p )
		{
			m_pFirst = NULL;
		}
		else
		{
			if ( m_pFirst == p )
			{
				m_pFirst = p->pNext;
			}
			p->pNext->pPrev = p->pPrev;
			p->pPrev->pNext = p->pNext;
		}

		delete p;
		m_nElems--;
	}

	void RemoveAll()
	{
		Node_t *p = m_pFirst;
		if ( p )
		{
			do 
			{
				Node_t *pNext = p->pNext;
				delete p;
				p = pNext;
			} while( p != m_pFirst );
		}

		m_pFirst = NULL;
		m_nElems = 0;
	}

	int	Count() const									
	{ 
		return m_nElems; 
	}

	IndexType_t Head() const							
	{ 
		return (IndexType_t)m_pFirst;
	}

	IndexType_t Next( IndexType_t i ) const				
	{ 
		Node_t *p = ((Node_t *)i)->pNext;
		if ( p != m_pFirst )
		{
			return (IndexType_t)p;
		}
		return NULL; 
	}

	bool IsValidIndex( IndexType_t i ) const
	{
		Node_t *p = ((Node_t *)i);
		return ( p && p->pNext && p->pPrev );
	}

	inline static IndexType_t  InvalidIndex()			
	{ 
		return NULL; 
	}
private:

	struct Node_t
	{
		Node_t() {}
		Node_t( const T &_elem ) : elem( _elem ) {}

		T elem;
		Node_t *pPrev, *pNext;
	};

	Node_t *AllocNode( const T *pCopyFrom )
	{
		MEM_ALLOC_CREDIT_CLASS();
		Node_t *p;

		if ( !pCopyFrom )
		{
			p = new Node_t;
		}
		else
		{
			p = new Node_t( *pCopyFrom );
		}

		return p;
	}

	IndexType_t DoInsertBefore( IndexType_t before, const T *pCopyFrom )
	{
		Node_t *p = AllocNode( pCopyFrom );
		Node_t *pBefore = (Node_t *)before;
		if ( pBefore )
		{
			p->pNext = pBefore;
			p->pPrev = pBefore->pPrev;
			pBefore->pPrev = p;
			p->pPrev->pNext = p;
		}
		else
		{
			Assert( !m_pFirst );
			m_pFirst = p->pNext = p->pPrev = p;
		}

		m_nElems++;
		return (IndexType_t)p;
	}

	Node_t *m_pFirst;
	unsigned m_nElems;
};

//-----------------------------------------------------------------------------

#endif // UTLLINKEDLIST_H