-
Notifications
You must be signed in to change notification settings - Fork 89
/
palInlineFuncs.h
1482 lines (1328 loc) · 46.9 KB
/
palInlineFuncs.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 (c) 2014-2024 Advanced Micro Devices, Inc. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
**********************************************************************************************************************/
/**
***********************************************************************************************************************
* @file palInlineFuncs.h
* @brief PAL utility collection inline functions.
***********************************************************************************************************************
*/
#pragma once
#include "palAssert.h"
#include "palStringUtil.h"
#include <cctype>
#include <cstdlib>
#include <cstring>
#include <cwchar>
#include <iterator>
#include <type_traits>
#include <limits>
namespace Util
{
/// Describes a value type, primarily used for loading settings values.
enum class ValueType : uint32
{
Boolean, ///< Boolean type.
Int8, ///< 8-bit integer type.
Uint8, ///< 8-bit unsigned integer type.
Int16, ///< 16-bit integer type.
Uint16, ///< 16-bit unsigned integer type.
Int32, ///< 32-bit integer type.
Uint32, ///< 32-bit unsigned integer type.
Int64, ///< 64-bit integer type.
Uint64, ///< 64-bit unsigned integer type.
Float, ///< Floating point type.
Str, ///< String type.
#if PAL_CLIENT_INTERFACE_MAJOR_VERSION < 905
Int = Int32, ///< Signed integer type.
Uint = Uint32, ///< Unsigned integer type.
#endif
};
/// Determines the length of an array at compile-time.
///
/// @returns The length of the array.
template <typename T, size_t N>
constexpr size_t ArrayLen(
const T (&array)[N]) ///< The array of arbitrary type T.
{
return N;
}
/// Determines the 32-bit length of an array at compile-time.
///
/// @returns The length of the array.
template <typename T, uint32 N>
constexpr uint32 ArrayLen32(
const T (&array)[N]) ///< The array of arbitrary type T.
{
return N;
}
/// Increments a const pointer by nBytes by first casting it to a const uint8*.
///
/// @returns Incremented pointer.
constexpr const void* VoidPtrInc(
const void* p, ///< [in] Pointer to be incremented.
size_t numBytes) ///< Number of bytes to increment the pointer by.
{
return (static_cast<const uint8*>(p) + numBytes);
}
/// Increments a pointer by nBytes by first casting it to a uint8*.
///
/// @returns Incremented pointer.
constexpr void* VoidPtrInc(
void* p, ///< [in] Pointer to be incremented.
size_t numBytes) ///< Number of bytes to increment the pointer by.
{
return (static_cast<uint8*>(p) + numBytes);
}
/// Decrements a const pointer by nBytes by first casting it to a const uint8*.
///
/// @returns Decremented pointer.
constexpr const void* VoidPtrDec(
const void* p, ///< [in] Pointer to be decremented.
size_t numBytes) ///< Number of bytes to decrement the pointer by.
{
return (static_cast<const uint8*>(p) - numBytes);
}
/// Decrements a pointer by nBytes by first casting it to a uint8*.
///
/// @returns Decremented pointer.
constexpr void* VoidPtrDec(
void* p, ///< [in] Pointer to be decremented.
size_t numBytes) ///< Number of bytes to decrement the pointer by.
{
return (static_cast<uint8*>(p) - numBytes);
}
/// Finds the number of bytes between two pointers by first casting them to uint8*.
///
/// This function expects the first pointer to not be smaller than the second.
///
/// @returns Number of bytes between the two pointers.
constexpr size_t VoidPtrDiff(
const void* p1, ///< [in] First pointer (higher address).
const void* p2) ///< [in] Second pointer (lower address).
{
PAL_CONSTEXPR_ASSERT(p1 >= p2);
return (static_cast<const uint8*>(p1) - static_cast<const uint8*>(p2));
}
/// Returns the high 32 bits of a 64-bit integer.
///
/// @returns Returns the high 32 bits of a 64-bit integer.
constexpr uint32 HighPart(
uint64 value) ///< 64-bit input value.
{
return (value & 0xFFFFFFFF00000000) >> 32;
}
/// Returns the low 32 bits of a 64-bit integer.
///
/// @returns Returns the low 32 bits of a 64-bit integer.
constexpr uint32 LowPart(
uint64 value) ///< 64-bit input value.
{
return (value & 0x00000000FFFFFFFF);
}
/// Returns the high 32 bits of a 64-bit integer as a 64-bit integer.
///
/// @returns Returns the high 32 bits of a 64-bit integer as a 64-bit integer
/// without shifting
constexpr uint64 HighPart64(
uint64 value) ///< 64-bit input value.
{
return (value & 0xFFFFFFFF00000000);
}
/// Combines the low and high 32 bits of a 64-bit integer.
///
/// @returns Returns the 64-bit integer.
constexpr uint64 Uint64CombineParts(
uint32 lowPart,
uint32 highPart)
{
return (uint64(highPart) << 32) | uint64(lowPart);
}
/// Returns a larger value from repeating a single byte
constexpr uint32 ReplicateByteAcrossDword(
uint8 value) ///< 8-bit input value.
{
return (value | (value << 8) | (value << 16) | (value << 24));
}
/// Returns a larger value from repeating a single byte
constexpr uint64 ReplicateByteAcrossQword(
uint8 value) ///< 8-bit input value.
{
return ((static_cast<uint64>(ReplicateByteAcrossDword(value)) << 32) | ReplicateByteAcrossDword(value));
}
/// Returns a bitfield from within some value.
///
/// @returns Returns a bitfield from within some value.
template <typename T>
constexpr T BitExtract(
T value, ///< Extract a bitfield from here.
uint32 firstBit, ///< The zero-based index of the first bit to extract.
uint32 lastBit) ///< The zero-based index of the last bit to extract.
{
return (value >> firstBit) & ((1 << (lastBit - firstBit + 1)) - 1);
}
/// Determines if any of the bits set in "test" are also set in "src".
///
/// @returns True if any bits in "test" are set in "src", false otherwise.
constexpr bool TestAnyFlagSet(
uint32 src, ///< Source pattern.
uint32 test) ///< Test pattern.
{
return ((src & test) != 0);
}
/// Determines if all of the bits set in "test" are also set in "src".
///
/// @returns True if all bits set in "test" are also set in "src", false otherwise.
constexpr bool TestAllFlagsSet(
uint32 src, ///< Source pattern.
uint32 test) ///< Test pattern.
{
return ((src & test) == test);
}
/// Determines if any of the bits set in "test" are also set in "src".
///
/// @returns True if any bits in "test" are set in "src", false otherwise.
constexpr bool TestAnyFlagSet64(
uint64 src, ///< Source pattern.
uint64 test) ///< Test pattern.
{
return ((src & test) != 0);
}
/// Determines if all of the bits set in "test" are also set in "src".
///
/// @returns True if all bits set in "test" are also set in "src", false otherwise.
constexpr bool TestAllFlagsSet64(
uint64 src, ///< Source pattern.
uint64 test) ///< Test pattern.
{
return ((src & test) == test);
}
/// Tests if a single bit in a bitfield is set.
///
/// @param [in] bitfield Bitfield being tested
/// @param [in] bit Bit index to test
///
/// @returns True if the flag is set.
template <typename T>
constexpr bool BitfieldIsSet(
const T bitfield,
uint32 bit)
{
PAL_CONSTEXPR_ASSERT(bit < (sizeof(T) * 8));
return (bitfield & (static_cast<T>(1) << bit));
}
/// Sets a single bit in a bitfield to one.
///
/// @param [in] bitfield Reference to the bitfield being modified
/// @param [in] bit Index of the bit to set
template <typename T>
void BitfieldSetBit(
T &bitfield,
uint32 bit)
{
PAL_CONSTEXPR_ASSERT(bit < (sizeof(T) * 8));
bitfield |= (static_cast<T>(1) << bit);
}
///@{
/// Counts the number of one bits (population count) in an unsigned integer using some bitwise magic explained in the
/// Software Optimization Guide for AMD64 Processors.
///
/// @param [in] value The value need to be counted.
///
/// @returns Number of one bits in the input
template <typename T>
constexpr uint32 CountSetBits(
T value)
{
uint32 x = static_cast<uint32>(value);
x = x - ((x >> 1) & 0x55555555);
x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
x = (((x + (x >> 4)) & 0x0F0F0F0F) * 0x01010101) >> ((sizeof(uint32) - 1) << 3);
return x;
}
constexpr uint32 CountSetBits(
uint64 value)
{
uint64 x = value;
x = x - ((x >> 1) & 0x5555555555555555ull);
x = (x & 0x3333333333333333ull) + ((x >> 2) & 0x3333333333333333ull);
x = (((x + (x >> 4)) & 0x0F0F0F0F0F0F0F0Full) * 0x0101010101010101ull) >> ((sizeof(uint64) - 1) << 3);
return static_cast<uint32>(x);
}
///@}
/// Update a subfield of a bitfield.
///
/// @param [in] bitFieldToUpdate Bitfield being updated
/// @param [in] updateValue Source value to update
/// @param [in] updateMask Bitmask to update
///
/// @returns True if the flag is set.
template <typename T>
void BitfieldUpdateSubfield(
T* pBitFieldToUpdate,
const T updateValue,
const T updateMask)
{
*pBitFieldToUpdate = ((*pBitFieldToUpdate) & ~updateMask) |
(updateValue & updateMask);
}
/// Tests if a single bit in a "wide bitfield" is set. A "wide bifield" is a bitfield which spans an array of
/// integers because there are more flags than bits in one integer.
///
/// @param [in] bitfield Reference to the bitfield being tested
/// @param [in] bit Index of the flag to test
///
/// @returns True if the flag is set.
template <typename T, size_t N>
constexpr bool WideBitfieldIsSet(
const T (&bitfield)[N],
uint32 bit)
{
const uint32 index = (bit / (sizeof(T) << 3));
const T mask = (static_cast<T>(1) << (bit & ((sizeof(T) << 3) - 1)));
return (0 != (bitfield[index] & mask));
}
/// Checks if any bit is set in a wide bitfield. A "wide bitfield" is a bitfield which spans an array of
/// integers because there are more flags than bits in one integer.
///
/// @param [in] bitfield Wide bitfield to count.
///
/// @returns True if the wide bitfield is non-zero; false otherwise.
template <typename T, size_t N>
bool WideBitfieldIsAnyBitSet(
const T(&bitfield)[N])
{
bool isBitSet = false;
for (uint32 i = 0; i < N; i++)
{
isBitSet |= (bitfield[i] != 0);
}
return isBitSet;
}
/// Sets a single bit in a "wide bitfield" to one. A "wide bifield" is a bitfield which spans an array of
/// integers because there are more flags than bits in one integer.
///
/// @param [in] bitfield Reference to the bitfield being modified
/// @param [in] bit Index of the flag to set
template <typename T, size_t N>
void WideBitfieldSetBit(
T (&bitfield)[N],
uint32 bit)
{
const uint32 index = (bit / (sizeof(T) << 3));
const T mask = (static_cast<T>(1) << (bit & ((sizeof(T) << 3) - 1)));
bitfield[index] |= mask;
}
/// Clears a single bit in a "wide bitfield" to zero. A "wide bifield" is a bitfield which spans an array of
/// integers because there are more flags than bits in one integer.
///
/// @param [in] bitfield Reference to the bitfield being modified
/// @param [in] bit Index of the flag to set
template <typename T, size_t N>
void WideBitfieldClearBit(
T (&bitfield)[N],
uint32 bit)
{
const uint32 index = (bit / (sizeof(T) << 3));
const T mask = (static_cast<T>(1) << (bit & ((sizeof(T) << 3) - 1)));
bitfield[index] &= ~mask;
}
/// Sets consecutive bits in a "wide bitfield" to one. A "wide bifield" is a bitfield which spans an array of
/// integers because there are more flags than bits in one integer.
///
/// @param [in] bitfield Reference to the bitfield being modified
/// @param [in] startingBit Index of the first flag to set
/// @param [in] numBits Count of consecutive flags to set
template <typename T, size_t N>
void WideBitfieldSetRange(
T (&bitfield)[N],
uint32 startingBit,
uint32 numBits)
{
constexpr uint32 SizeInBits = (sizeof(T) << 3);
PAL_ASSERT((startingBit + numBits) <= (SizeInBits * N));
uint32 index = (startingBit / SizeInBits);
startingBit &= (SizeInBits - 1);
while (numBits > 0)
{
const uint32 maxNumBits = SizeInBits - startingBit;
const uint32 curNumBits = (maxNumBits < numBits) ? maxNumBits : numBits;
const T bitMask = (curNumBits == SizeInBits) ? -1 : ((static_cast<T>(1) << curNumBits) - 1);
bitfield[index++] |= (bitMask << startingBit);
startingBit = 0;
numBits -= curNumBits;
}
}
/// XORs all of the bits in two "wide bitfields". A "wide bifield" is a bitfield which spans an array of integers
/// because there are more flags than bits in one integer.
///
/// @param [in] bitfield1 Reference to the first bitfield.
/// @param [in] bitfield2 Reference to the second bitfield.
/// @param [out] pOut Result of (bitfield1 ^ bitfield2)
template <typename T, size_t N>
void WideBitfieldXorBits(
const T (&bitfield1)[N],
const T (&bitfield2)[N],
T* pOut)
{
for (uint32 i = 0; i < N; i++)
{
pOut[i] = (bitfield1[i] ^ bitfield2[i]);
}
}
/// ANDs all of the bits in two "wide bitfields". A "wide bifield" is a bitfield which spans an array of integers
/// because there are more flags than bits in one integer.
///
/// @param [in] bitfield1 Reference to the first bitfield.
/// @param [in] bitfield2 Reference to the second bitfield.
/// @param [out] pOut Result of (bitfield1 & bitfield2)
template <typename T, size_t N>
void WideBitfieldAndBits(
const T (&bitfield1)[N],
const T (&bitfield2)[N],
T* pOut)
{
for (uint32 i = 0; i < N; i++)
{
pOut[i] = (bitfield1[i] & bitfield2[i]);
}
}
/// Counts the number of one bits (population count) in a wide bitfield. A "wide bitfield" is a bitfield which spans
/// an array of integers because there are more flags than bits in one integer.
///
/// @param [in] bitfield Wide bitfield to count.
///
/// @returns Number of one bits in the input
template <typename T, size_t N>
uint32 WideBitfieldCountSetBits(
const T(&bitfield)[N])
{
uint32 count = 0;
for (uint32 i = 0; i < N; i++)
{
count += CountSetBits(bitfield[i]);
}
return count;
}
/// Unsets the least-significant '1' bit in the given number.
/// Usually used in conjunction with BitMaskScanForward
///
/// @param [in] value The value to be modified
///
/// @returns A copy of value with the lowest '1' bit unset.
template <typename T>
T UnsetLeastBit(
T val)
{
static_assert(std::is_unsigned<T>::value, "Must use unsigned ints here");
return val & (val - 1);
}
/// Scans the specified bit-mask for the least-significant '1' bit.
///
/// @returns True if the input was nonzero; false otherwise.
template <typename T>
bool BitMaskScanForward(
uint32* pIndex, ///< [out] Index of least-significant '1' bit. Undefined if input is zero.
T mask) ///< Bit-mask to scan.
{
// Bitscan intrinsics may compile to flaky code in certain situations. Discarding bitscan flags avoids this. The key
// is to forward declare result, and set it in a conditional branch after the bitscan. Be careful if modifying this.
bool result = false;
if (mask != 0)
{
#if defined(__GNUC__)
*pIndex = (sizeof(T) > 4) ? __builtin_ctzll(mask) : __builtin_ctz(static_cast<uint32>(mask));
#else
uint32 index = 0;
for (; ((mask & 0x1) == 0); mask >>= 1, ++index);
*pIndex = index;
#endif
result = true;
}
return result;
}
/// Scans the specified bit-mask for the most-significant '1' bit.
///
/// @returns True if the input was nonzero; false otherwise.
template <typename T>
bool BitMaskScanReverse(
uint32* pIndex, ///< [out] Index of most-significant '1' bit. Undefined if input is zero.
T mask) ///< Bit-mask to scan.
{
// Bitscan intrinsics may compile to flaky code in certain situations. Discarding bitscan flags avoids this. The key
// is to forward declare result, and set it in a conditional branch after the bitscan. Be careful if modifying this.
bool result = false;
if (mask != 0)
{
#if defined(__GNUC__)
*pIndex = (sizeof(T) > 4) ? (63u - __builtin_clzll(mask)) : (31u - __builtin_clz(static_cast<uint32>(mask)));
#else
uint32 index = 31u;
for (; (((mask >> index) & 0x1) == 0); --index);
*pIndex = index;
#endif
result = true;
}
return result;
}
/// Scans the specified wide bit-mask for the least-significant '1' bit.
///
/// @returns True if input was nonzero; false otherwise.
template <typename T, size_t N>
bool WideBitMaskScanForward(
uint32* pIndex, ///< [out] Index of least-significant '1' bit. Undefined if input is zero.
T (&mask)[N]) ///< Bit-mask to scan.
{
uint32 maskIndex = ((*pIndex) / (sizeof(T) << 3));
// Check to see if the wide bitmask has some bits set.
uint32 index = 0;
while ((mask[index] == 0) && (++index < N));
bool result = (index < N);
while (result == true)
{
result = BitMaskScanForward(pIndex, mask[maskIndex]);
if (result == false)
{
++maskIndex;
result = (maskIndex < N);
}
else
{
(*pIndex) = (*pIndex) + (maskIndex * (sizeof(T) << 3));
break;
}
}
return result;
}
/// Scans the specified wide bit-mask for the most-significant '1' bit.
///
/// @returns True if input was nonzero; false otherwise.
template <typename T, size_t N>
bool WideBitMaskScanReverse(
uint32* pIndex, ///< [out] Index of most-significant '1' bit. Undefined if input is zero.
T (&mask)[N]) ///< Bit-mask to scan.
{
uint32 maskIndex = ((*pIndex) / (sizeof(T) << 3));
// Check to see if the wide bitmask has some bits set.
uint32 index = N - 1;
while ((mask[index] == 0) && (--index > 0));
bool result = (mask[index] != 0);
while (result == true)
{
result = BitMaskScanReverse(pIndex, mask[maskIndex]);
if (result == false)
{
const uint32 oldIndex = maskIndex--;
result = (oldIndex != 0);
}
else
{
(*pIndex) = (*pIndex) + (maskIndex * (sizeof(T) << 3));
break;
}
}
return result;
}
/// Generates a bitmask.
///
/// @param [in] numBits Number of bits to set (starting at 0)
///
/// @returns Bitmask in storage of type T with bits [0:numBits-1] set.
template <typename T>
constexpr T BitfieldGenMask(
T numBits)
{
PAL_CONSTEXPR_ASSERT(numBits <= (sizeof(T) * 8));
const T mask = (numBits < (sizeof(T) * 8)) ? ((static_cast<T>(1) << (numBits)) - static_cast<T>(1)) : static_cast<T>(-1);
return mask;
}
/// Determines if a value is a power of two.
///
/// @returns True if it is a power of two, false otherwise.
constexpr bool IsPowerOfTwo(
uint64 value) ///< Value to check.
{
return (value == 0) ? false : ((value & (value - 1)) == 0);
}
/// Determines if 'value' is at least aligned to the specified power-of-2 alignment.
///
/// @returns True if aligned, false otherwise.
constexpr bool IsPow2Aligned(
uint64 value, ///< Value to check.
uint64 alignment) ///< Desired alignment.
{
PAL_CONSTEXPR_ASSERT(IsPowerOfTwo(alignment));
return ((value & (alignment - 1)) == 0);
}
/// Determines if 'ptr' is at least aligned to the specified power-of-2 alignment.
///
/// @returns True if aligned, false otherwise.
inline bool VoidPtrIsPow2Aligned(
const void* ptr, ///< Pointer to check.
uint64 alignment) ///< Desired alignment.
{
PAL_ASSERT(IsPowerOfTwo(alignment));
return ((reinterpret_cast<size_t>(ptr) & (alignment - 1)) == 0);
}
/// Rounds the specified uint 'value' up to the nearest value meeting the specified 'alignment'. Only power of 2
/// alignments are supported by this function.
///
/// @returns Aligned value.
template <typename T>
constexpr T Pow2Align(
T value, ///< Value to align.
uint64 alignment) ///< Desired alignment (must be a power of 2).
{
PAL_CONSTEXPR_ASSERT(IsPowerOfTwo(alignment));
return ((value + static_cast<T>(alignment) - 1) & ~(static_cast<T>(alignment) - 1));
}
/// Rounds the specified uint 'value' up to the nearest power of 2
///
/// @param [in] value The value to pad.
///
/// @returns Power of 2 padded value.
template <typename T>
T Pow2Pad(
T value)
{
T ret = value;
if ((value & (value - 1)) != 0)
{
uint32 lastBitIndex = 0;
BitMaskScanReverse(&lastBitIndex, value);
ret = (static_cast<T>(0x2) << lastBitIndex);
}
return ret;
}
/// Computes the base-2 logarithm of an unsigned integer.
///
/// If the given integer is not a power of 2, this function will not provide an exact answer.
///
/// @param [in] u Value to compute the logarithm of.
///
/// @returns log_2(u)
template <typename T>
uint32 Log2(
T u)
{
uint32 logValue = 0;
return BitMaskScanReverse(&logValue, u) ? logValue : 0;
}
/// Computes the base-2 logarithm of an unsigned 64-bit integer based on ceiling
///
/// If the given integer is not a power of 2, this function will not provide an exact answer.
///
/// @returns ceilLog_2(u)
template <typename T>
uint32 CeilLog2(
T u) ///< Value to compute the ceil logarithm of.
{
const uint32 logValue = Log2(u);
return ((static_cast<T>(0x1ul) << logValue) < u) ? (logValue + 1) : logValue;
}
/// Implements an alternative version of integer division in which the quotient is always rounded up instead of down.
///
/// @returns The rounded quotient.
template <typename T>
constexpr T RoundUpQuotient(
T dividend, ///< Value to divide.
T divisor) ///< Value to divide by.
{
return ((dividend + (divisor - 1)) / divisor);
}
/// Rounds up the specified integer to the nearest multiple of the specified alignment value.
///
/// @returns Rounded value.
template <typename T>
constexpr T RoundUpToMultiple(
T operand, ///< Value to be aligned.
T alignment) ///< Alignment desired.
{
return (((operand + (alignment - 1)) / alignment) * alignment);
}
/// Rounds down the specified integer to the nearest multiple of the specified alignment value.
///
/// @returns Rounded value.
template <typename T>
constexpr T RoundDownToMultiple(
T operand, ///< Value to be aligned.
T alignment) ///< Alignment desired.
{
return ((operand / alignment) * alignment);
}
/// Rounds the specified 'value' down to the nearest value meeting the specified 'alignment'. Only power of 2
/// alignments are supported by this function.
///
/// @returns Rounded value.
template <typename T>
constexpr T Pow2AlignDown(
T value, ///< Value to align.
uint64 alignment) ///< Desired alignment (must be a power of 2).
{
PAL_CONSTEXPR_ASSERT(IsPowerOfTwo(alignment));
return (value & ~(alignment - 1));
}
/// Determines the maximum of two numbers.
///
/// @returns The larger of the two inputs.
template <typename T>
constexpr T Max(
T value1, ///< First value to check.
T value2) ///< Second value to check.
{
return ((value1 > value2) ? value1 : value2);
}
/// Determines the maximum of N numbers.
///
/// @returns The largest of all the inputs.
template <typename T, typename... Ts>
constexpr T Max(
T value1, ///< First value to check.
T value2, ///< Second value to check.
Ts... values) ///< Additional values to check.
{
return Max(((value1 > value2) ? value1 : value2), values...);
}
/// Determines the minimum of two numbers.
///
/// @returns The smaller of the two inputs.
template <typename T>
constexpr T Min(
T value1, ///< First value to check.
T value2) ///< Second value to check.
{
return ((value1 < value2) ? value1 : value2);
}
/// Determines the minimum of N numbers.
///
/// @returns The smallest of all the inputs.
template <typename T, typename... Ts>
constexpr T Min(
T value1, ///< First value to check.
T value2, ///< Second value to check.
Ts... values) ///< Additional values to check.
{
return Min(((value1 < value2) ? value1 : value2), values...);
}
/// Clamps the input number so that it falls in-between the lower and upper bounds (inclusive).
///
/// @returns Clamped input number.
template <typename T>
constexpr T Clamp(
T input, ///< Input number to clamp.
T lowBound, ///< Lower-bound to clamp to.
T highBound) ///< Upper-bound to clamp to.
{
return ((input <= lowBound) ? lowBound :
(input >= highBound) ? highBound : input);
}
/// Determines if the input is within the range specified (inclusive).
///
/// @returns True if within range, False otherwise.
template <typename T>
constexpr bool InRange(
T input, ///< Input number to range check.
T lowBound, ///< Low bound of the range to check (inclusive).
T highBound) ///< High bound of the range to check (inclusive).
{
return (lowBound <= input) && (input <= highBound);
}
/// Converts a byte value to the equivalent number of DWORDs (uint32) rounded up. I.e., 3 bytes will return 1 dword.
///
/// @returns Number of dwords necessary to cover numBytes.
constexpr uint32 NumBytesToNumDwords(
uint32 numBytes) ///< Byte count to convert.
{
return Pow2Align(numBytes, static_cast<uint32>(sizeof(uint32))) / sizeof(uint32);
}
/// Compare two strings ignoring case
inline int Strcasecmp(
const char* pSrc, ///< [in] The source string to be compared.
const char* pDst) ///< [in] The dest string to compare.
{
PAL_ASSERT(pSrc != nullptr);
PAL_ASSERT(pDst != nullptr);
return strcasecmp(pDst, pSrc);
}
/// Performs a safe strcpy by requiring the destination buffer size.
inline void Strncpy(
char* pDst, ///< [out] Destination string.
const char* pSrc, ///< [in] Source string to be copied into destination.
size_t dstSize) ///< Size of the destination buffer in bytes.
{
PAL_ASSERT(pDst != nullptr);
PAL_ASSERT(pSrc != nullptr);
PAL_ALERT(strlen(pSrc) >= dstSize);
if (dstSize > 0)
{
strncpy(pDst, pSrc, (dstSize - 1));
pDst[dstSize - 1] = '\0';
}
}
/// Simple wrapper for wcscpy_s or wcsncpy, which are available on Windows and Linux, respectively.
inline void Wcsncpy(
wchar_t* pDst, ///< [out] Destination string.
const wchar_t* pSrc, ///< [in] Source string to copy.
size_t dstSize) ///< Length of the destination buffer, in wchar_t's.
{
#if defined(PAL_SHORT_WCHAR)
CopyUtf16String(pDst, pSrc, (dstSize - 1));
#else
wcsncpy(pDst, pSrc, (dstSize - 1));
#endif
pDst[dstSize - 1] = L'\0';
}
// Wrapper for wcscat or wcscat_s which provides a safe version of wcscat
inline void Wcscat(
wchar_t* pDst,
const wchar_t* pSrc,
size_t dstSize)
{
const size_t dstLen = PalWcslen(pDst);
#if defined(PAL_SHORT_WCHAR)
CopyUtf16String(&pDst[dstLen], pSrc, (dstSize - dstLen - 1));
#else
wcsncat(pDst, pSrc, (dstSize - dstLen - 1));
#endif
pDst[dstSize - 1] = L'\0';
}
/// Simple wrapper for strncat or strncat_s which provides a safe version of strncat.
inline void Strncat(
char* pDst, ///< [in,out] Destination string.
size_t sizeDst, ///< Length of the destination string, including the null terminator.
const char* pSrc) ///< [in] Source string.
{
PAL_ASSERT((pDst != nullptr) && (pSrc != nullptr));
#if defined(__unix__)
// Compute the length of the destination string to prevent buffer overruns.
const size_t dstLength = strlen(pDst);
strncat(pDst, pSrc, (sizeDst - dstLength - 1));
#endif
}
/// Simple wrapper for strtok_s or strtok_r which provides a safe version of strtok.
inline char* Strtok(
char* str, ///< [in] Token string.
const char* delim, ///< [in] Token delimit.
char** buf) ///< [in,out] Buffer to store the rest of the string.
{
PAL_ASSERT((delim != nullptr) && (buf != nullptr));
char* pToken = nullptr;
#if defined(__unix__)
pToken = strtok_r(str, delim, buf);
#endif
return pToken;
}
/// Rounds the specified pointer up to the nearest value meeting the specified 'alignment'. Only power of 2 alignments
/// are supported by this function.
///
/// @returns Aligned pointer.
inline void* VoidPtrAlign(
void* ptr, ///< Pointer to align.
size_t alignment) ///< Desired alignment.
{
// This function only works for POW2 alignment
PAL_ASSERT(IsPowerOfTwo(alignment));
return reinterpret_cast<void*>(
(reinterpret_cast<size_t>(ptr) + (alignment - 1)) & ~(alignment - 1));
}
/// Converts a raw string value to the correct data type.
inline void StringToValueType(
const char* pStrValue, ///< [in] Setting value in string form.
ValueType type, ///< Data type of the value being converted.
size_t valueSize, ///< Size of pValue buffer.
void* pValue) ///< [out] Converted setting value buffer.
{
switch (type)
{
case ValueType::Boolean:
*(static_cast<bool*>(pValue)) = ((atoi(pStrValue)) ? true : false);
break;
case ValueType::Int8:
*(static_cast<int8*>(pValue)) = static_cast<int8>(strtoll(pStrValue, nullptr, 0));
break;
case ValueType::Uint8:
*(static_cast<uint8*>(pValue)) = static_cast<uint8>(strtoull(pStrValue, nullptr, 0));
break;
case ValueType::Int16:
*(static_cast<int16*>(pValue)) = static_cast<int16>(strtoll(pStrValue, nullptr, 0));
break;
case ValueType::Uint16:
*(static_cast<uint16*>(pValue)) = static_cast<uint16>(strtoull(pStrValue, nullptr, 0));
break;
case ValueType::Int32:
*(static_cast<int32*>(pValue)) = static_cast<int32>(strtoll(pStrValue, nullptr, 0));
break;
case ValueType::Uint32:
*(static_cast<uint32*>(pValue)) = static_cast<uint32>(strtoull(pStrValue, nullptr, 0));
break;
case ValueType::Int64:
*(static_cast<int64*>(pValue)) = static_cast<int64>(strtoll(pStrValue, nullptr, 0));
break;
case ValueType::Uint64:
*(static_cast<uint64*>(pValue)) = static_cast<uint64>(strtoull(pStrValue, nullptr, 0));
break;
case ValueType::Float:
*(static_cast<float*>(pValue)) = static_cast<float>(atof(pStrValue));
break;
case ValueType::Str:
Strncpy(static_cast<char*>(pValue), pStrValue, valueSize);
break;
}
}
/// Converts a raw string value to the correct data type, returning 'true' if parsed correctly.
/// When not parsed correctly, the value will be unchanged.
///