forked from mozilla/gecko-dev
-
Notifications
You must be signed in to change notification settings - Fork 2
/
nsVoidArray.cpp
1321 lines (1139 loc) · 31.3 KB
/
nsVoidArray.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
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2; c-file-offsets: ((substatement-open . 0)) -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1998
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include <stdlib.h>
#include "nsVoidArray.h"
#include "nsQuickSort.h"
#include "prbit.h"
#include "nsISupportsImpl.h" // for nsTraceRefcnt
#include "nsCRTGlue.h"
/**
* Grow the array by at least this many elements at a time.
*/
static const PRInt32 kMinGrowArrayBy = 8;
static const PRInt32 kMaxGrowArrayBy = 1024;
static const PRInt32 kAutoClearCompactSizeFactor = 4;
/**
* This is the threshold (in bytes) of the mImpl struct, past which
* we'll force the array to grow geometrically
*/
static const PRInt32 kLinearThreshold = 24 * sizeof(void *);
/**
* Compute the number of bytes requires for the mImpl struct that will
* hold |n| elements.
*/
#define SIZEOF_IMPL(n_) (sizeof(Impl) + sizeof(void *) * ((n_) - 1))
/**
* Compute the number of elements that an mImpl struct of |n| bytes
* will hold.
*/
#define CAPACITYOF_IMPL(n_) ((((n_) - sizeof(Impl)) / sizeof(void *)) + 1)
#if DEBUG_VOIDARRAY
#define MAXVOID 10
class VoidStats {
public:
VoidStats();
~VoidStats();
};
static int sizesUsed; // number of the elements of the arrays used
static int sizesAlloced[MAXVOID]; // sizes of the allocations. sorted
static int NumberOfSize[MAXVOID]; // number of this allocation size (1 per array)
static int AllocedOfSize[MAXVOID]; // number of this allocation size (each size for array used)
static int MaxAuto[MAXVOID]; // AutoArrays that maxed out at this size
static int GrowInPlace[MAXVOID]; // arrays this size that grew in-place via realloc
// these are per-allocation
static int MaxElements[2000]; // # of arrays that maxed out at each size.
// statistics macros
#define ADD_TO_STATS(x,size) do {int i; for (i = 0; i < sizesUsed; i++) \
{ \
if (sizesAlloced[i] == (int)(size)) \
{ ((x)[i])++; break; } \
} \
if (i >= sizesUsed && sizesUsed < MAXVOID) \
{ sizesAlloced[sizesUsed] = (size); \
((x)[sizesUsed++])++; break; \
} \
} while (0)
#define SUB_FROM_STATS(x,size) do {int i; for (i = 0; i < sizesUsed; i++) \
{ \
if (sizesAlloced[i] == (int)(size)) \
{ ((x)[i])--; break; } \
} \
} while (0)
VoidStats::VoidStats()
{
sizesUsed = 1;
sizesAlloced[0] = 0;
}
VoidStats::~VoidStats()
{
int i;
for (i = 0; i < sizesUsed; i++)
{
printf("Size %d:\n",sizesAlloced[i]);
printf("\tNumber of VoidArrays this size (max): %d\n",NumberOfSize[i]-MaxAuto[i]);
printf("\tNumber of AutoVoidArrays this size (max): %d\n",MaxAuto[i]);
printf("\tNumber of allocations this size (total): %d\n",AllocedOfSize[i]);
printf("\tNumber of GrowsInPlace this size (total): %d\n",GrowInPlace[i]);
}
printf("Max Size of VoidArray:\n");
for (i = 0; i < (int)(sizeof(MaxElements)/sizeof(MaxElements[0])); i++)
{
if (MaxElements[i])
printf("\t%d: %d\n",i,MaxElements[i]);
}
}
// Just so constructor/destructor's get called
VoidStats gVoidStats;
#endif
void
nsVoidArray::SetArray(Impl *newImpl, PRInt32 aSize, PRInt32 aCount,
PRBool aOwner, PRBool aHasAuto)
{
// old mImpl has been realloced and so we don't free/delete it
NS_PRECONDITION(newImpl, "can't set size");
mImpl = newImpl;
mImpl->mCount = aCount;
mImpl->mBits = static_cast<PRUint32>(aSize & kArraySizeMask) |
(aOwner ? kArrayOwnerMask : 0) |
(aHasAuto ? kArrayHasAutoBufferMask : 0);
}
// This does all allocation/reallocation of the array.
// It also will compact down to N - good for things that might grow a lot
// at times, but usually are smaller, like JS deferred GC releases.
PRBool nsVoidArray::SizeTo(PRInt32 aSize)
{
PRUint32 oldsize = GetArraySize();
PRBool isOwner = IsArrayOwner();
PRBool hasAuto = HasAutoBuffer();
if (aSize == (PRInt32) oldsize)
return PR_TRUE; // no change
if (aSize <= 0)
{
// free the array if allocated
if (mImpl)
{
if (isOwner)
{
free(reinterpret_cast<char *>(mImpl));
if (hasAuto) {
static_cast<nsAutoVoidArray*>(this)->ResetToAutoBuffer();
}
else {
mImpl = nsnull;
}
}
else
{
mImpl->mCount = 0; // nsAutoVoidArray
}
}
return PR_TRUE;
}
if (mImpl && isOwner)
{
// We currently own an array impl. Resize it appropriately.
if (aSize < mImpl->mCount)
{
// XXX Note: we could also just resize to mCount
return PR_TRUE; // can't make it that small, ignore request
}
char* bytes = (char *) realloc(mImpl,SIZEOF_IMPL(aSize));
Impl* newImpl = reinterpret_cast<Impl*>(bytes);
if (!newImpl)
return PR_FALSE;
#if DEBUG_VOIDARRAY
if (mImpl == newImpl)
ADD_TO_STATS(GrowInPlace,oldsize);
ADD_TO_STATS(AllocedOfSize,SIZEOF_IMPL(aSize));
if (aSize > mMaxSize)
{
ADD_TO_STATS(NumberOfSize,SIZEOF_IMPL(aSize));
if (oldsize)
SUB_FROM_STATS(NumberOfSize,oldsize);
mMaxSize = aSize;
if (mIsAuto)
{
ADD_TO_STATS(MaxAuto,SIZEOF_IMPL(aSize));
SUB_FROM_STATS(MaxAuto,oldsize);
}
}
#endif
SetArray(newImpl, aSize, newImpl->mCount, PR_TRUE, hasAuto);
return PR_TRUE;
}
if ((PRUint32) aSize < oldsize) {
// No point in allocating if it won't free the current Impl anyway.
return PR_TRUE;
}
// just allocate an array
// allocate the exact size requested
char* bytes = (char *) malloc(SIZEOF_IMPL(aSize));
Impl* newImpl = reinterpret_cast<Impl*>(bytes);
if (!newImpl)
return PR_FALSE;
#if DEBUG_VOIDARRAY
ADD_TO_STATS(AllocedOfSize,SIZEOF_IMPL(aSize));
if (aSize > mMaxSize)
{
ADD_TO_STATS(NumberOfSize,SIZEOF_IMPL(aSize));
if (oldsize && !mImpl)
SUB_FROM_STATS(NumberOfSize,oldsize);
mMaxSize = aSize;
}
#endif
if (mImpl)
{
#if DEBUG_VOIDARRAY
ADD_TO_STATS(MaxAuto,SIZEOF_IMPL(aSize));
SUB_FROM_STATS(MaxAuto,0);
SUB_FROM_STATS(NumberOfSize,0);
mIsAuto = PR_TRUE;
#endif
// We must be growing an nsAutoVoidArray - copy since we didn't
// realloc.
memcpy(newImpl->mArray, mImpl->mArray,
mImpl->mCount * sizeof(mImpl->mArray[0]));
}
SetArray(newImpl, aSize, mImpl ? mImpl->mCount : 0, PR_TRUE, hasAuto);
// no memset; handled later in ReplaceElementAt if needed
return PR_TRUE;
}
PRBool nsVoidArray::GrowArrayBy(PRInt32 aGrowBy)
{
// We have to grow the array. Grow by kMinGrowArrayBy slots if we're
// smaller than kLinearThreshold bytes, or a power of two if we're
// larger. This is much more efficient with most memory allocators,
// especially if it's very large, or of the allocator is binned.
if (aGrowBy < kMinGrowArrayBy)
aGrowBy = kMinGrowArrayBy;
PRUint32 newCapacity = GetArraySize() + aGrowBy; // Minimum increase
PRUint32 newSize = SIZEOF_IMPL(newCapacity);
if (newSize >= (PRUint32) kLinearThreshold)
{
// newCount includes enough space for at least kMinGrowArrayBy new
// slots. Select the next power-of-two size in bytes above or
// equal to that.
// Also, limit the increase in size to about a VM page or two.
if (GetArraySize() >= kMaxGrowArrayBy)
{
newCapacity = GetArraySize() + PR_MAX(kMaxGrowArrayBy,aGrowBy);
newSize = SIZEOF_IMPL(newCapacity);
}
else
{
PR_CEILING_LOG2(newSize, newSize);
newCapacity = CAPACITYOF_IMPL(PR_BIT(newSize));
}
}
// frees old mImpl IF this succeeds
if (!SizeTo(newCapacity))
return PR_FALSE;
return PR_TRUE;
}
nsVoidArray::nsVoidArray()
: mImpl(nsnull)
{
MOZ_COUNT_CTOR(nsVoidArray);
#if DEBUG_VOIDARRAY
mMaxCount = 0;
mMaxSize = 0;
mIsAuto = PR_FALSE;
ADD_TO_STATS(NumberOfSize,0);
MaxElements[0]++;
#endif
}
nsVoidArray::nsVoidArray(PRInt32 aCount)
: mImpl(nsnull)
{
MOZ_COUNT_CTOR(nsVoidArray);
#if DEBUG_VOIDARRAY
mMaxCount = 0;
mMaxSize = 0;
mIsAuto = PR_FALSE;
MaxElements[0]++;
#endif
SizeTo(aCount);
}
nsVoidArray& nsVoidArray::operator=(const nsVoidArray& other)
{
PRInt32 otherCount = other.Count();
PRInt32 maxCount = GetArraySize();
if (otherCount)
{
if (otherCount > maxCount)
{
// frees old mImpl IF this succeeds
if (!GrowArrayBy(otherCount-maxCount))
return *this; // XXX The allocation failed - don't do anything
memcpy(mImpl->mArray, other.mImpl->mArray, otherCount * sizeof(mImpl->mArray[0]));
mImpl->mCount = otherCount;
}
else
{
// the old array can hold the new array
memcpy(mImpl->mArray, other.mImpl->mArray, otherCount * sizeof(mImpl->mArray[0]));
mImpl->mCount = otherCount;
// if it shrank a lot, compact it anyways
if ((otherCount*2) < maxCount && maxCount > 100)
{
Compact(); // shrank by at least 50 entries
}
}
#if DEBUG_VOIDARRAY
if (mImpl->mCount > mMaxCount &&
mImpl->mCount < (PRInt32)(sizeof(MaxElements)/sizeof(MaxElements[0])))
{
MaxElements[mImpl->mCount]++;
MaxElements[mMaxCount]--;
mMaxCount = mImpl->mCount;
}
#endif
}
else
{
// Why do we drop the buffer here when we don't in Clear()?
SizeTo(0);
}
return *this;
}
nsVoidArray::~nsVoidArray()
{
MOZ_COUNT_DTOR(nsVoidArray);
if (mImpl && IsArrayOwner())
free(reinterpret_cast<char*>(mImpl));
}
PRBool nsVoidArray::SetCount(PRInt32 aNewCount)
{
NS_ASSERTION(aNewCount >= 0,"SetCount(negative index)");
if (aNewCount < 0)
return PR_FALSE;
if (aNewCount == 0)
{
Clear();
return PR_TRUE;
}
if (PRUint32(aNewCount) > PRUint32(GetArraySize()))
{
PRInt32 oldCount = Count();
PRInt32 growDelta = aNewCount - oldCount;
// frees old mImpl IF this succeeds
if (!GrowArrayBy(growDelta))
return PR_FALSE;
}
if (aNewCount > mImpl->mCount)
{
// Make sure that new entries added to the array by this
// SetCount are cleared to 0. Some users of this assume that.
// This code means we don't have to memset when we allocate an array.
memset(&mImpl->mArray[mImpl->mCount], 0,
(aNewCount - mImpl->mCount) * sizeof(mImpl->mArray[0]));
}
mImpl->mCount = aNewCount;
#if DEBUG_VOIDARRAY
if (mImpl->mCount > mMaxCount &&
mImpl->mCount < (PRInt32)(sizeof(MaxElements)/sizeof(MaxElements[0])))
{
MaxElements[mImpl->mCount]++;
MaxElements[mMaxCount]--;
mMaxCount = mImpl->mCount;
}
#endif
return PR_TRUE;
}
PRInt32 nsVoidArray::IndexOf(void* aPossibleElement) const
{
if (mImpl)
{
void** ap = mImpl->mArray;
void** end = ap + mImpl->mCount;
while (ap < end)
{
if (*ap == aPossibleElement)
{
return ap - mImpl->mArray;
}
ap++;
}
}
return -1;
}
PRBool nsVoidArray::InsertElementAt(void* aElement, PRInt32 aIndex)
{
PRInt32 oldCount = Count();
NS_ASSERTION(aIndex >= 0,"InsertElementAt(negative index)");
if (PRUint32(aIndex) > PRUint32(oldCount))
{
// An invalid index causes the insertion to fail
// Invalid indexes are ones that add more than one entry to the
// array (i.e., they can append).
return PR_FALSE;
}
if (oldCount >= GetArraySize())
{
if (!GrowArrayBy(1))
return PR_FALSE;
}
// else the array is already large enough
PRInt32 slide = oldCount - aIndex;
if (0 != slide)
{
// Slide data over to make room for the insertion
memmove(mImpl->mArray + aIndex + 1, mImpl->mArray + aIndex,
slide * sizeof(mImpl->mArray[0]));
}
mImpl->mArray[aIndex] = aElement;
mImpl->mCount++;
#if DEBUG_VOIDARRAY
if (mImpl->mCount > mMaxCount &&
mImpl->mCount < (PRInt32)(sizeof(MaxElements)/sizeof(MaxElements[0])))
{
MaxElements[mImpl->mCount]++;
MaxElements[mMaxCount]--;
mMaxCount = mImpl->mCount;
}
#endif
return PR_TRUE;
}
PRBool nsVoidArray::InsertElementsAt(const nsVoidArray& other, PRInt32 aIndex)
{
PRInt32 oldCount = Count();
PRInt32 otherCount = other.Count();
NS_ASSERTION(aIndex >= 0,"InsertElementsAt(negative index)");
if (PRUint32(aIndex) > PRUint32(oldCount))
{
// An invalid index causes the insertion to fail
// Invalid indexes are ones that are more than one entry past the end of
// the array (i.e., they can append).
return PR_FALSE;
}
if (oldCount + otherCount > GetArraySize())
{
if (!GrowArrayBy(otherCount))
return PR_FALSE;;
}
// else the array is already large enough
PRInt32 slide = oldCount - aIndex;
if (0 != slide)
{
// Slide data over to make room for the insertion
memmove(mImpl->mArray + aIndex + otherCount, mImpl->mArray + aIndex,
slide * sizeof(mImpl->mArray[0]));
}
for (PRInt32 i = 0; i < otherCount; i++)
{
// copy all the elements (destroys aIndex)
mImpl->mArray[aIndex++] = other.mImpl->mArray[i];
mImpl->mCount++;
}
#if DEBUG_VOIDARRAY
if (mImpl->mCount > mMaxCount &&
mImpl->mCount < (PRInt32)(sizeof(MaxElements)/sizeof(MaxElements[0])))
{
MaxElements[mImpl->mCount]++;
MaxElements[mMaxCount]--;
mMaxCount = mImpl->mCount;
}
#endif
return PR_TRUE;
}
PRBool nsVoidArray::ReplaceElementAt(void* aElement, PRInt32 aIndex)
{
NS_ASSERTION(aIndex >= 0,"ReplaceElementAt(negative index)");
if (aIndex < 0)
return PR_FALSE;
// Unlike InsertElementAt, ReplaceElementAt can implicitly add more
// than just the one element to the array.
if (PRUint32(aIndex) >= PRUint32(GetArraySize()))
{
PRInt32 oldCount = Count();
PRInt32 requestedCount = aIndex + 1;
PRInt32 growDelta = requestedCount - oldCount;
// frees old mImpl IF this succeeds
if (!GrowArrayBy(growDelta))
return PR_FALSE;
}
mImpl->mArray[aIndex] = aElement;
if (aIndex >= mImpl->mCount)
{
// Make sure that any entries implicitly added to the array by this
// ReplaceElementAt are cleared to 0. Some users of this assume that.
// This code means we don't have to memset when we allocate an array.
if (aIndex > mImpl->mCount) // note: not >=
{
// For example, if mCount is 2, and we do a ReplaceElementAt for
// element[5], then we need to set three entries ([2], [3], and [4])
// to 0.
memset(&mImpl->mArray[mImpl->mCount], 0,
(aIndex - mImpl->mCount) * sizeof(mImpl->mArray[0]));
}
mImpl->mCount = aIndex + 1;
#if DEBUG_VOIDARRAY
if (mImpl->mCount > mMaxCount &&
mImpl->mCount < (PRInt32)(sizeof(MaxElements)/sizeof(MaxElements[0])))
{
MaxElements[mImpl->mCount]++;
MaxElements[mMaxCount]--;
mMaxCount = mImpl->mCount;
}
#endif
}
return PR_TRUE;
}
// useful for doing LRU arrays
PRBool nsVoidArray::MoveElement(PRInt32 aFrom, PRInt32 aTo)
{
void *tempElement;
if (aTo == aFrom)
return PR_TRUE;
NS_ASSERTION(aTo >= 0 && aFrom >= 0,"MoveElement(negative index)");
if (aTo >= Count() || aFrom >= Count())
{
// can't extend the array when moving an element. Also catches mImpl = null
return PR_FALSE;
}
tempElement = mImpl->mArray[aFrom];
if (aTo < aFrom)
{
// Moving one element closer to the head; the elements inbetween move down
memmove(mImpl->mArray + aTo + 1, mImpl->mArray + aTo,
(aFrom-aTo) * sizeof(mImpl->mArray[0]));
mImpl->mArray[aTo] = tempElement;
}
else // already handled aFrom == aTo
{
// Moving one element closer to the tail; the elements inbetween move up
memmove(mImpl->mArray + aFrom, mImpl->mArray + aFrom + 1,
(aTo-aFrom) * sizeof(mImpl->mArray[0]));
mImpl->mArray[aTo] = tempElement;
}
return PR_TRUE;
}
PRBool nsVoidArray::RemoveElementsAt(PRInt32 aIndex, PRInt32 aCount)
{
PRInt32 oldCount = Count();
NS_ASSERTION(aIndex >= 0,"RemoveElementsAt(negative index)");
if (PRUint32(aIndex) >= PRUint32(oldCount))
{
// An invalid index causes the replace to fail
return PR_FALSE;
}
// Limit to available entries starting at aIndex
if (aCount + aIndex > oldCount)
aCount = oldCount - aIndex;
// We don't need to move any elements if we're removing the
// last element in the array
if (aIndex < (oldCount - aCount))
{
memmove(mImpl->mArray + aIndex, mImpl->mArray + aIndex + aCount,
(oldCount - (aIndex + aCount)) * sizeof(mImpl->mArray[0]));
}
mImpl->mCount -= aCount;
return PR_TRUE;
}
PRBool nsVoidArray::RemoveElement(void* aElement)
{
PRInt32 theIndex = IndexOf(aElement);
if (theIndex != -1)
return RemoveElementAt(theIndex);
return PR_FALSE;
}
void nsVoidArray::Clear()
{
if (mImpl)
{
mImpl->mCount = 0;
// We don't have to free on Clear, but if we have a built-in buffer,
// it's worth considering.
if (HasAutoBuffer() && IsArrayOwner() &&
GetArraySize() > kAutoClearCompactSizeFactor * kAutoBufSize) {
SizeTo(0);
}
}
}
void nsVoidArray::Compact()
{
if (mImpl)
{
// XXX NOTE: this is quite inefficient in many cases if we're only
// compacting by a little, but some callers care more about memory use.
PRInt32 count = Count();
if (HasAutoBuffer() && count <= kAutoBufSize)
{
Impl* oldImpl = mImpl;
static_cast<nsAutoVoidArray*>(this)->ResetToAutoBuffer();
memcpy(mImpl->mArray, oldImpl->mArray,
count * sizeof(mImpl->mArray[0]));
free(reinterpret_cast<char *>(oldImpl));
}
else if (GetArraySize() > count)
{
SizeTo(Count());
}
}
}
// Needed because we want to pass the pointer to the item in the array
// to the comparator function, not a pointer to the pointer in the array.
struct VoidArrayComparatorContext {
nsVoidArrayComparatorFunc mComparatorFunc;
void* mData;
};
static int
VoidArrayComparator(const void* aElement1, const void* aElement2, void* aData)
{
VoidArrayComparatorContext* ctx = static_cast<VoidArrayComparatorContext*>(aData);
return (*ctx->mComparatorFunc)(*static_cast<void* const*>(aElement1),
*static_cast<void* const*>(aElement2),
ctx->mData);
}
void nsVoidArray::Sort(nsVoidArrayComparatorFunc aFunc, void* aData)
{
if (mImpl && mImpl->mCount > 1)
{
VoidArrayComparatorContext ctx = {aFunc, aData};
NS_QuickSort(mImpl->mArray, mImpl->mCount, sizeof(mImpl->mArray[0]),
VoidArrayComparator, &ctx);
}
}
PRBool nsVoidArray::EnumerateForwards(nsVoidArrayEnumFunc aFunc, void* aData)
{
PRInt32 index = -1;
PRBool running = PR_TRUE;
if (mImpl)
{
while (running && (++index < mImpl->mCount))
{
running = (*aFunc)(mImpl->mArray[index], aData);
}
}
return running;
}
PRBool nsVoidArray::EnumerateBackwards(nsVoidArrayEnumFunc aFunc, void* aData)
{
PRBool running = PR_TRUE;
if (mImpl)
{
PRInt32 index = Count();
while (running && (0 <= --index))
{
running = (*aFunc)(mImpl->mArray[index], aData);
}
}
return running;
}
//----------------------------------------------------------------
// nsAutoVoidArray
nsAutoVoidArray::nsAutoVoidArray()
: nsVoidArray()
{
// Don't need to clear it. Some users just call ReplaceElementAt(),
// but we'll clear it at that time if needed to save CPU cycles.
#if DEBUG_VOIDARRAY
mIsAuto = PR_TRUE;
ADD_TO_STATS(MaxAuto,0);
#endif
ResetToAutoBuffer();
}
//----------------------------------------------------------------
// nsCStringArray
nsCStringArray::nsCStringArray(void)
: nsVoidArray()
{
}
nsCStringArray::nsCStringArray(PRInt32 aCount)
: nsVoidArray(aCount)
{
}
nsCStringArray::~nsCStringArray(void)
{
Clear();
}
nsCStringArray&
nsCStringArray::operator=(const nsCStringArray& other)
{
if (this == &other)
{
return *this;
}
// Free our strings
Clear();
// Copy the pointers
nsVoidArray::operator=(other);
// Now copy the strings
PRInt32 count = Count();
for (PRInt32 i = 0; i < count; ++i)
{
nsCString* oldString = static_cast<nsCString*>(other.ElementAt(i));
nsCString* newString = new nsCString(*oldString);
if (!newString)
{
mImpl->mCount = i;
return *this;
}
mImpl->mArray[i] = newString;
}
return *this;
}
void
nsCStringArray::CStringAt(PRInt32 aIndex, nsACString& aCString) const
{
nsCString* string = static_cast<nsCString*>(nsVoidArray::ElementAt(aIndex));
if (nsnull != string)
{
aCString = *string;
}
else
{
aCString.Truncate();
}
}
nsCString*
nsCStringArray::CStringAt(PRInt32 aIndex) const
{
return static_cast<nsCString*>(nsVoidArray::ElementAt(aIndex));
}
PRInt32
nsCStringArray::IndexOf(const nsACString& aPossibleString) const
{
if (mImpl)
{
void** ap = mImpl->mArray;
void** end = ap + mImpl->mCount;
while (ap < end)
{
nsCString* string = static_cast<nsCString*>(*ap);
if (string->Equals(aPossibleString))
{
return ap - mImpl->mArray;
}
ap++;
}
}
return -1;
}
#ifdef MOZILLA_INTERNAL_API
PRInt32
nsCStringArray::IndexOfIgnoreCase(const nsACString& aPossibleString) const
{
if (mImpl)
{
void** ap = mImpl->mArray;
void** end = ap + mImpl->mCount;
while (ap < end)
{
nsCString* string = static_cast<nsCString*>(*ap);
if (string->Equals(aPossibleString, nsCaseInsensitiveCStringComparator()))
{
return ap - mImpl->mArray;
}
ap++;
}
}
return -1;
}
#endif
PRBool
nsCStringArray::InsertCStringAt(const nsACString& aCString, PRInt32 aIndex)
{
nsCString* string = new nsCString(aCString);
if (!string)
return PR_FALSE;
if (nsVoidArray::InsertElementAt(string, aIndex))
return PR_TRUE;
delete string;
return PR_FALSE;
}
PRBool
nsCStringArray::ReplaceCStringAt(const nsACString& aCString, PRInt32 aIndex)
{
nsCString* string = static_cast<nsCString*>(nsVoidArray::ElementAt(aIndex));
if (nsnull != string)
{
*string = aCString;
return PR_TRUE;
}
return PR_FALSE;
}
PRBool
nsCStringArray::RemoveCString(const nsACString& aCString)
{
PRInt32 index = IndexOf(aCString);
if (-1 < index)
{
return RemoveCStringAt(index);
}
return PR_FALSE;
}
#ifdef MOZILLA_INTERNAL_API
PRBool
nsCStringArray::RemoveCStringIgnoreCase(const nsACString& aCString)
{
PRInt32 index = IndexOfIgnoreCase(aCString);
if (-1 < index)
{
return RemoveCStringAt(index);
}
return PR_FALSE;
}
#endif
PRBool nsCStringArray::RemoveCStringAt(PRInt32 aIndex)
{
nsCString* string = CStringAt(aIndex);
if (nsnull != string)
{
nsVoidArray::RemoveElementAt(aIndex);
delete string;
return PR_TRUE;
}
return PR_FALSE;
}
void
nsCStringArray::Clear(void)
{
PRInt32 index = Count();
while (0 <= --index)
{
nsCString* string = static_cast<nsCString*>(mImpl->mArray[index]);
delete string;
}
nsVoidArray::Clear();
}
static int
CompareCString(const nsCString* aCString1, const nsCString* aCString2, void*)
{
#ifdef MOZILLA_INTERNAL_API
return Compare(*aCString1, *aCString2);
#else
const char* s1;
const char* s2;
PRUint32 len1 = NS_CStringGetData(*aCString1, &s1);
PRUint32 len2 = NS_CStringGetData(*aCString2, &s2);
int r = memcmp(s1, s2, PR_MIN(len1, len2));
if (r)
return r;
if (len1 < len2)
return -1;
if (len1 > len2)
return 1;
return 0;
#endif
}
#ifdef MOZILLA_INTERNAL_API
static int
CompareCStringIgnoreCase(const nsCString* aCString1, const nsCString* aCString2, void*)
{
return Compare(*aCString1, *aCString2, nsCaseInsensitiveCStringComparator());
}
#endif
void nsCStringArray::Sort(void)
{
Sort(CompareCString, nsnull);
}
#ifdef MOZILLA_INTERNAL_API
void nsCStringArray::SortIgnoreCase(void)
{
Sort(CompareCStringIgnoreCase, nsnull);
}
#endif
void nsCStringArray::Sort(nsCStringArrayComparatorFunc aFunc, void* aData)
{
nsVoidArray::Sort(reinterpret_cast<nsVoidArrayComparatorFunc>(aFunc), aData);
}
PRBool
nsCStringArray::EnumerateForwards(nsCStringArrayEnumFunc aFunc, void* aData)
{
PRBool running = PR_TRUE;
if (mImpl)
{
PRInt32 index = -1;