Repository navigation
Expand file tree
/
Copy pathArray.h
More file actions
1039 lines (903 loc) · 20 KB
/
Copy pathArray.h
File metadata and controls
1039 lines (903 loc) · 20 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/// \file
/// \author Matthew Allen
/// \brief Growable, type-safe array.
#pragma once
#include <type_traits>
#include <stdlib.h>
#include <assert.h>
#include <cstdlib>
#include <initializer_list>
#include <functional>
#if defined(LGI_CHECK_MALLOC) && !defined(LGI_MEM_DEBUG)
#error "Include GMem.h first"
#endif
#ifndef LGI_STATIC
/// Same as LgiTrace but writes a stack trace as well.
LgiFunc void LStackTrace(const char *Format, ...);
#endif
#if defined(PLATFORM_MINGW)
#ifdef __cplusplus
extern "C" {
#endif
#ifndef _QSORT_S_DEFINED
#define _QSORT_S_DEFINED
_CRTIMP void __cdecl qsort_s(void *_Base,
size_t _NumOfElements,
size_t _SizeOfElements,
int (__cdecl *_PtFuncCompare)(void *,const void *,const void *),
void *_Context);
#endif
#ifdef __cplusplus
}
#endif
#endif
#include "lgi/common/Range.h"
/// \brief Growable type-safe array.
/// \ingroup Base
///
/// You can store simple objects inline in this array, but all their contents are initialized
/// to the octet 0x00. Which limits use to objects that don't have a virtual table and
/// don't need construction (constructors are not called).
///
/// The objects are copied around during use so you can't assume their pointer
/// will remain the same over time either. However when objects are deleted from the
/// array their destructors WILL be called. This allows you to have simple objects that
/// have dynamically allocated pointers that are freed properly. A good example of this
/// type of object is the LVariant or LAutoString class.
///
/// If you want to store objects with a virtual table, or that need their constructor
/// to be called then you should create the LArray with pointers to the objects instead
/// of inline objects. And to clean up the memory you can call LArray::DeleteObjects or
/// LArray::DeleteArrays.
template <class Type>
class LArray
{
Type *p = NULL;
ssize_t len = 0;
ssize_t alloc = 0;
#ifdef _DEBUG
public:
size_t GetAlloc() { return alloc; }
#endif
protected:
uint8_t fixed : 1;
uint8_t warnResize : 1;
public:
typedef Type ItemType;
constexpr static ssize_t MIN_SIZE = 16;
constexpr static ssize_t INVALID = -1;
/// Constructor
LArray(size_t PreAlloc = 0)
{
alloc = len = PreAlloc;
fixed = false;
warnResize = true;
if (alloc)
{
size_t Bytes = sizeof(Type) * alloc;
p = (Type*) malloc(Bytes);
if (p)
{
memset((uint8_t*)p, 0, Bytes);
}
else
{
alloc = len = 0;
}
}
}
LArray(std::initializer_list<Type> il)
{
fixed = false;
warnResize = true;
if (Length(il.size()))
{
size_t n = 0;
for (auto i: il)
p[n++] = i;
}
}
LArray(const LArray<Type> &c)
{
fixed = false;
warnResize = true;
*this = c;
}
/// Destructor
~LArray()
{
Length(0);
}
/// This frees the memory without calling the destructor of the elements.
/// Useful if you're storing large amounts of plain data types, like char or int.
void Free()
{
if (p)
{
free(p);
p = NULL;
}
len = alloc = 0;
}
/// Does a range check on a pointer...
/// \returns true if the pointer is pointing to a valid object
/// in this array.
bool PtrCheck(void *Ptr)
{
return p != NULL &&
Ptr >= p &&
Ptr < &p[len];
}
/// Does a range check on an index...
bool IdxCheck(ssize_t i) const
{
return i >= 0 && i < len;
}
/// Returns the number of used entries
size_t Length() const
{
return len;
}
/// Makes the length fixed..
void SetFixedLength(bool fix = true, bool warn = true)
{
fixed = fix;
warnResize = warn;
}
/// Gets the fixed length setting
bool GetFixedLength() { return fixed; }
/// Emtpies the array of all objects.
bool Empty()
{
return Length(0);
}
/// Sets the length of available entries
bool Length(ssize_t i)
{
if (i > 0)
{
if (i > len && fixed)
{
#ifndef LGI_STATIC
if (warnResize)
LStackTrace("Attempt to enlarged fixed array.\n");
#endif
return false;
}
ssize_t nalloc = alloc;
if (i < len)
{
// Shrinking
}
else
{
// Expanding
nalloc = 0x10;
while (nalloc < i)
nalloc <<= 1;
assert(nalloc >= i);
}
if (nalloc != alloc)
{
auto np = (Type*)malloc(sizeof(Type) * nalloc);
if (!np)
{
return false;
}
memset((uint8_t*)(np + len), 0, (nalloc - len) * sizeof(Type));
if (p)
{
// copy across common elements
memcpy((uint8_t*)np, p, MIN(len, i) * sizeof(Type));
free(p);
}
p = np;
alloc = nalloc;
}
if (i > len)
{
// zero new elements
memset((uint8_t*)(p + len), 0, sizeof(Type) * (nalloc - len));
}
else if (i < len)
{
for (ssize_t n=i; n<len; n++)
p[n].~Type();
}
len = i;
}
else
{
if (p)
{
ssize_t Length = len;
for (ssize_t i=0; i<Length; i++)
p[i].~Type();
}
Free();
}
return true;
}
bool operator ==(const LArray<Type> &a) const
{
if (Length() != a.Length())
return false;
for (ssize_t i=0; i<len; i++)
if (p[i] != a.ItemAt(i))
return false;
return true;
}
bool operator !=(const LArray<Type> &a) const
{
return !(*this == a);
}
LArray<Type> &operator =(const LArray<Type> &a)
{
fixed = false;
Length(a.Length());
fixed = a.fixed;
warnResize = a.warnResize;
if (p && a.p)
{
for (ssize_t i=0; i<len; i++)
p[i] = a.p[i];
}
return *this;
}
Type &First()
{
if (len <= 0)
{
LAssert(!"Must have one element.");
static Type t;
return t;
}
return p[0];
}
Type &Last()
{
if (len <= 0)
{
LAssert(!"Must have one element.");
static Type t;
return t;
}
return p[len-1];
}
/// This can be used instead of the [] operator in situations
/// where the array is const.
const Type &ItemAt(ssize_t index) const
{
if (index >= 0 && index < len)
return p[index];
static Type t;
return t;
}
// Returns the address of an item or NULL if index is out of range
Type *AddressOf(ssize_t index = 0)
{
if (index < 0)
index += len;
if (index < 0 || index >= len)
return nullptr;
return p + index;
}
/// \brief Returns a reference a given entry.
///
/// If the entry is off the end of the array and "fixed" is false,
/// it will grow to make it valid.
Type &operator [](ssize_t index)
{
static Type empty;
if (index < 0) // index from the end... -1 being the last element, -2 the second last etc.
index += len;
if (index < 0)
return empty;
if (fixed && index >= len)
{
#ifndef LGI_STATIC
if (warnResize)
LStackTrace("%s:%i - Attempt to enlarged fixed array.", _FL);
#endif
return empty;
}
if (index >= alloc)
{
// increase array length
auto nalloc = MAX(alloc, MIN_SIZE);
while (nalloc <= index)
{
nalloc <<= 1;
}
#if 0
if (nalloc > 1<<30)
{
#if defined(_DEBUG) && defined(_MSC_VER)
LAssert(0);
#endif
ZeroObj(t);
return t;
}
#endif
// alloc new array
auto np = (Type*) malloc(sizeof(Type) * nalloc);
if (np)
{
// clear new cells
memset((uint8_t*)(np + len), 0, (nalloc - len) * sizeof(Type));
if (p)
{
// copy across old cells
memcpy((uint8_t*)np, p, len * sizeof(Type));
// clear old array
free(p);
}
// new values
p = np;
alloc = nalloc;
}
else
{
static Type *t = 0;
return *t;
}
}
// adjust length of the the array
if (index + 1 > len)
{
len = index + 1;
}
return p[index];
}
/// Delete all the entries as if they are pointers to objects
void DeleteObjects()
{
if (len > 0)
{
size_t InitialLen = len;
delete p[0];
if (InitialLen == len)
{
// Non self deleting
for (uint i=1; i<len; i++)
{
delete p[i];
p[i] = 0;
}
Length(0);
}
else
{
// Self deleting object...
while (len)
{
delete p[0];
}
}
}
}
/// Delete all the entries as if they are pointers to arrays
void DeleteArrays()
{
for (uint32_t i=0; i<len; i++)
{
DeleteArray(p[i]);
}
Length(0);
}
/// Find the index of entry 'n'
ssize_t IndexOf(Type n) const
{
for (ssize_t i=0; i<len; i++)
{
if (p[i] == n)
return i;
}
return INVALID;
}
/// Returns true if the item 'n' is in the array
bool HasItem(Type n)
{
return IndexOf(n) >= 0;
}
/// Removes first element
Type PopFirst()
{
if (len <= 0)
return Type();
Type ret = std::move(p[0]);
DeleteAt(0, true);
return ret;
}
/// Removes last element
Type PopLast()
{
if (len <= 0)
{
return Type();
}
Type ret = std::move(p[len - 1]);
Length(len - 1);
return ret;
}
/// Deletes an entry
bool DeleteAt
(
/// The index of the entry to delete
ssize_t index,
/// true if the order of the array matters, otherwise false.
bool Ordered = false
)
{
if (index < 0)
index += len;
if (index < 0)
return false;
if (p && index < len)
{
// Delete the object
p[index].~Type();
// Move the memory up
if (index < len - 1)
{
if (Ordered)
memmove((uint8_t*)(p + index), p + index + 1, (len - index - 1) * sizeof(Type) );
else
p[index] = p[len-1];
}
// Adjust length
len--;
// Kill the element at the end... otherwise New() returns non-zero data.
memset((uint8_t*)(p + len), 0, sizeof(Type));
return true;
}
return false;
}
/// Deletes a range.
/// This operation always maintains order.
/// \returns the number of removed elements
ssize_t DeleteRange(LRange r)
{
// Truncate range to the size of this array
if (r.Start < 0)
r.Start = 0;
if (r.End() >= (ssize_t)len)
r.Len = len - r.Start;
// Delete all the elements we are removing
for (ssize_t i=r.Start; i<r.End(); i++)
p[i].~Type();
// Move the elements down
auto Remain = len - r.End();
if (Remain > 0)
memmove(&p[r.Start], &p[r.End()], sizeof(Type)*Remain);
len = r.Start + Remain;
return r.Len;
}
/// Deletes the entry 'n'
bool Delete
(
/// The value of the entry to delete
Type n,
/// true if the order of the array matters, otherwise false.
bool Ordered = false
)
{
ssize_t i = IndexOf(n);
if (p && i >= 0)
{
return DeleteAt(i, Ordered);
}
return false;
}
/// Appends an element
void Add
(
/// Item to insert
const Type &n
)
{
(*this)[len] = n;
}
/// Appends multiple elements
bool Add
(
/// Items to insert
const Type *s,
/// Length of array
ssize_t count
)
{
if (!s || count < 1)
return false;
ssize_t i = len;
if (!Length(len + count))
return false;
Type *d = p + i;
while (count--)
{
*d++ = *s++;
}
return true;
}
/// Appends an array of elements
bool Add
(
/// Array to insert
const LArray<Type> &a
)
{
ssize_t old = len;
if (Length(len + a.Length()))
{
for (unsigned i=0; i<a.Length(); i++, old++)
p[old] = a.ItemAt(i);
}
else return false;
return true;
}
LArray<Type> operator +(const LArray<Type> &b)
{
LArray<Type> a = *this;
a.SetFixedLength(false);
if (!a.Add(b))
{
LAssert(!"Add failed");
}
return a;
}
LArray<Type> &operator +=(const LArray<Type> &b)
{
Add(b);
return *this;
}
/// Inserts an element into the array
bool AddAt
(
/// Item to insert before
ssize_t index,
/// Item to insert
Type n
)
{
// Make room
if (!Length(len + 1))
return false;
if (index >= 0 && index < len - 1)
// Shift elements after insert point up one
memmove((uint8_t*)(p + index + 1), p + index, (len - index - 1) * sizeof(Type) );
else
// Add at the end, not after the end...
index = len - 1;
// Insert item
memset((uint8_t*)(p + index), 0, sizeof(*p));
p[index] = n;
return true;
}
/// Inserts an array into the array at a position
bool AddAt
(
/// Item to insert before
ssize_t index,
/// Array to insert
const LArray<Type> &a
)
{
if (index < 0)
index += len;
if (index < 0)
return false;
// Make room
if (!Length(len + a.Length()))
return false;
if (index < len - 1)
// Shift elements after insert point up one
memmove((uint8_t*)(p + index + a.Length()), p + index, (len - index - a.Length()) * sizeof(Type) );
else
// Add at the end, not after the end...
index = len - a.Length();
// Insert items
memset((uint8_t*)(p + index), 0, a.Length() * sizeof(*p));
for (size_t i=0; i<a.Length(); i++)
p[index+i] = a.ItemAt(i);
return true;
}
protected:
template<typename T>
void SortImpl(T& a)
{
// Sorting non-pointers...
std::qsort(p, len, sizeof(*p),
[](const void *a, const void *b) -> int
{
auto A = (const Type*)a;
auto B = (const Type*)b;
auto cmp = *A - *B;
if (cmp < 0) return -1;
return cmp > 0 ? 1 : 0;
});
}
template<typename T>
void SortImpl(T*& a)
{
// Sorting pointers...
std::qsort(p, len, sizeof(*p),
[](const void *a, const void *b) -> int
{
auto &A = *(const Type*)a;
auto &B = *(const Type*)b;
auto cmp = *A - *B;
if (cmp < 0) return -1;
return cmp > 0 ? 1 : 0;
});
}
public:
/// Sorts the array via objects '-' operator
void Sort()
{
if (len <= 0)
return;
SortImpl(*p);
}
/// Sorts the array via a callback.
void Sort(std::function<int(Type*,Type*)> Compare)
{
#if !defined(WINDOWS) && !defined(HAIKU) && !defined(LINUX)
#define USER_DATA_FIRST 1
#else
#define USER_DATA_FIRST 0
#endif
#if defined(HAIKU) && !defined(_GNU_SOURCE)
#error "_GNU_SOURCE needs to be defined in your project settings"
#endif
#if defined(WINDOWS)
/* _ACRTIMP void __cdecl qsort_s(void* _Base,
rsize_t _NumOfElements,
rsize_t _SizeOfElements,
int (__cdecl* _PtFuncCompare)(void*, void const*, void const*),
void* _Context); */
qsort_s
#else
qsort_r
#endif
(
p,
len,
sizeof(Type),
#if USER_DATA_FIRST
&Compare,
#endif
#if defined(HAIKU) || defined(LINUX)
// typedef int (*_compare_function_qsort_r)(const void*, const void*, void*);
// extern void qsort_r(void* base, size_t numElements, size_t sizeOfElement, _compare_function_qsort_r, void* cookie);
[](const void *a, const void *b, void *ud) -> int
#else
[](void *ud, const void *a, const void *b) -> int
#endif
{
return (*( (std::function<int(Type*,Type*)>*)ud ))((Type*)a, (Type*)b);
}
#if !USER_DATA_FIRST
, &Compare
#endif
);
}
/// \returns a reference to a new object on the end of the array
///
/// Never assign this to an existing variable. e.g:
/// LArray<MyObject> a;
/// MyObject &o = a.New();
/// o.Type = something;
/// o = a.New();
/// o.Type = something else;
///
/// This causes the first object to be overwritten with a blank copy.
Type &New()
{
return (*this)[len];
}
/// Returns the memory held by the array and sets itself to empty
Type *Release()
{
Type *Ptr = p;
p = nullptr;
len = alloc = 0;
return Ptr;
}
void Swap(LArray<Type> &other)
{
LSwap(p, other.p);
LSwap(len, other.len);
LSwap(alloc, other.alloc);
}
/// Swaps a range of elements between this array and 'b'
bool SwapRange
(
// The range of 'this' to swap out
LRange aRange,
// The other array to swap with
LArray<Type> &b,
// The range of 'b' to swap with this array
LRange bRange
)
{
LArray<Type> Tmp;
// Store entries in this that will be swapped
Tmp.Add(AddressOf(aRange.Start), aRange.Len);
// Copy b's range into this
ssize_t Common = MIN(bRange.Len, aRange.Len);
ssize_t aIdx = aRange.Start;
ssize_t bIdx = bRange.Start;
for (ssize_t i=0; i<Common; i++) // First the common items
(*this)[aIdx++] = b[bIdx++];
if (aRange.Len < bRange.Len)
{
// Grow range to fit 'b'
ssize_t Items = bRange.Len - aRange.Len;
for (ssize_t i=0; i<Items; i++)
if (!AddAt(aIdx++, b[bIdx++]))
return false;
}
else if (aRange.Len > bRange.Len)
{
// Shrink the range in this to fit 'b'
ssize_t Del = aRange.Len - bRange.Len;
for (ssize_t i=0; i<Del; i++)
if (!DeleteAt(aIdx, true))
return false;
}
// Now copy Tmp into b
ssize_t TmpIdx = 0;
bIdx = bRange.Start;
for (TmpIdx=0; TmpIdx<Common; TmpIdx++) // First the common items.
b[bIdx++] = Tmp[TmpIdx];
if (aRange.Len > bRange.Len)
{
// Grow range to fit this
ssize_t Add = aRange.Len - bRange.Len;
for (ssize_t i=0; i<Add; i++)
if (!b.AddAt(bIdx++, Tmp[TmpIdx++]))
return false;
}
else if (aRange.Len < bRange.Len)
{
// Shrink the range in this to fit 'b'
ssize_t Del = bRange.Len - aRange.Len;
for (ssize_t i=0; i<Del; i++)
if (!b.DeleteAt(bIdx, true))
return false;
}
return true;
}
template <class T>
class Iter
{
friend class LArray<T>;
ssize_t i;
char each_dir;
LArray<T> *a;
public:
Iter(LArray<T> *arr) // 'End' constructor
{
i = -1;
a = arr;
each_dir = 0;
}
Iter(LArray<T> *arr, size_t pos)
{
i = pos;
a = arr;
each_dir = 0;
}
bool operator ==(const Iter<T> &it) const
{
int x = (int)In() + (int)it.In();
if (x == 2)
return (a == it.a) && (i == it.i);
return x == 0;
}
bool operator !=(const Iter<T> &it) const
{
return !(*this == it);
}
operator bool() const
{
return In();
}
bool In() const
{
return i >= 0 && i < (ssize_t)a->Length();
}
bool End() const
{
return i < 0 || i >= a->Length();
}
T &operator *()
{
if (In())
return (*a)[i];
printf("%s:%i - deref operator outside of array bounds.\n", _FL);
static T null;
return null;
}
Iter<T> &operator ++() { i++; return *this; }
Iter<T> &operator --() { i--; return *this; }
Iter<T> &operator ++(int) { i++; return *this; }
Iter<T> &operator --(int) { i--; return *this; }
};
typedef Iter<Type> I;
I begin(size_t start = 0) { return I(this, start); }
I rbegin() { return I(this, len-1); }
I end() { return I(this); }
bool Delete(I &It)
{
return DeleteAt(It.i, true);
}
// Return a subset of the array:
LArray<Type> Slice(ssize_t Start, ssize_t End = -1)
{
LArray<Type> a;
// Range limit the inputs...
if (Start < 0)
{
Start = len + Start;
if (Start < 0)
Start = 0;
}
if (Start > (ssize_t)len)
Start = len;
if (End < 0)
{
End = len + End + 1;
if (End < 0)
End = 0;
}
if (End > (ssize_t)len)
End = len;
if (End > Start)
{
if (a.Length(End - Start))
{
for (size_t i=0; i<a.Length(); i++)
{
LAssert(Start + (ssize_t)i < len);
a[i] = p[Start + i];
}
}
}
return a;
}
LArray<Type> Reverse()
{
LArray<Type> r;