-
-
Notifications
You must be signed in to change notification settings - Fork 34
/
crt.h
1920 lines (1627 loc) · 68.6 KB
/
crt.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
#pragma once
// used: [stl] string, string_view, wstring, wstring_view
#include <string>
// used: [crt] va_list, va_start, va_end
#include <stdarg.h>
#include "../common.h"
#ifdef CS_COMPILER_MSC
#include <intrin.h>
#endif
// used: algorithm function
#include "math.h"
// used: stb_sprintf
#include "../../dependencies/stb_sprintf.h"
// add support of syntax highlight to our string formatting methods
#ifdef CS_COMPILER_CLANG
#define CS_CRT_FORMAT_STRING_ATTRIBUTE(METHOD, STRING_INDEX, FIRST_INDEX) __attribute__((format(METHOD, STRING_INDEX, FIRST_INDEX)))
#elif defined(__RESHARPER__)
#define CS_CRT_FORMAT_STRING_ATTRIBUTE(METHOD, STRING_INDEX, FIRST_INDEX) [[rscpp::format(METHOD, STRING_INDEX, FIRST_INDEX)]]
#else
#define CS_CRT_FORMAT_STRING_ATTRIBUTE(METHOD, STRING_INDEX, FIRST_INDEX)
#endif
// @todo: '__restrict' keyword to hint compiler on those
// @todo: disable msvc debug runtime checks for those
/*
* C-RUNTIME
* - rebuild of C standard library and partially STL
*/
namespace CRT
{
/*
* - according to IEEE-754:
*
* 1. binary32 floating point
* +/- exponent (+127) mantissa (fractional part)
* *-------*---*-----------------*-----------------------------------------------*
* | width | 1 | 8 | 23 |
* *-------*---*-----------------*-----------------------------------------------*
* | mask | 0 | 0 1 1 1 1 1 0 0 | 0 0 0 1 0 0 0 1 1 1 0 1 0 0 0 1 0 1 0 0 1 1 1 |
* *-------*---*-----------------*-----------------------------------------------*
* ^ ^ ^ ^ ^
* 31 30 23 22 0
*
* 2. binary64 floating point
* +/- exponent (+1023) mantissa (fractional part)
* *-------*---*-----------------------*---------------------------------------------------*
* | width | 1 | 11 | 52 |
* *-------*---*-----------------------*---------------------------------------------------*
* | mask | 0 | 0 1 1 1 1 1 0 0 0 0 0 | 0 0 0 1 0 0 0 1 1 1 0 1 0 0 0 1 0 1 0 0 1 1 1 ... |
* *-------*---*-----------------------*---------------------------------------------------*
* ^ ^ ^ ^ ^
* 63 62 52 51 0
*/
template <typename T> requires (std::is_floating_point_v<T>)
struct FloatSpecification_t
{
static_assert(std::numeric_limits<T>::is_iec559);
static_assert(sizeof(long double) == 8, "CRT rebuild doesn't support binary128 format");
// bit equivalent integer type for given floating point type
using BitEquivalent_t = std::conditional_t<std::is_same_v<T, double> || std::is_same_v<T, long double>, std::uint64_t, std::uint32_t>;
static constexpr std::uint32_t MANTISSA_WIDTH = ((sizeof(T) == sizeof(double)) ? 52U : 23U);
static constexpr std::uint32_t EXPONENT_WIDTH = ((sizeof(T) == sizeof(double)) ? 11U : 8U);
static constexpr std::uint32_t SIGN_WIDTH = 1U;
static constexpr std::uint32_t TOTAL_WIDTH = MANTISSA_WIDTH + EXPONENT_WIDTH + SIGN_WIDTH;
static constexpr std::uint32_t EXPONENT_BIAS = (1U << (EXPONENT_WIDTH - 1U)) - 1U;
static constexpr BitEquivalent_t MANTISSA_MASK = (BitEquivalent_t(1U) << MANTISSA_WIDTH) - 1U;
static constexpr BitEquivalent_t SIGN_MASK = (BitEquivalent_t(1U) << (EXPONENT_WIDTH + MANTISSA_WIDTH));
static constexpr BitEquivalent_t EXPONENT_MASK = ~(SIGN_MASK | MANTISSA_MASK);
static constexpr BitEquivalent_t QUIET_NAN_MASK = (BitEquivalent_t(1U) << (MANTISSA_WIDTH - 1U));
};
/* @section: [internal] constants */
// largest valid base
constexpr int _NUMBER_MAX_BASE = 36;
// every possible character to represent the number with the largest valid base
constexpr const char* _NUMBER_ALPHA = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
// lookup table for fast integer to string conversion in range [00 .. 99]
constexpr char _TWO_DIGITS_LUT[] =
"0001020304050607080910111213141516171819"
"2021222324252627282930313233343536373839"
"4041424344454647484950515253545556575859"
"6061626364656667686970717273747576777879"
"8081828384858687888990919293949596979899";
// lookup table for fast hex integer to string conversion in range [00 .. FF]
constexpr char _TWO_DIGITS_HEX_LUT[] =
"000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F"
"202122232425262728292A2B2C2D2E2F303132333435363738393A3B3C3D3E3F"
"404142434445464748494A4B4C4D4E4F505152535455565758595A5B5C5D5E5F"
"606162636465666768696A6B6C6D6E6F707172737475767778797A7B7C7D7E7F"
"808182838485868788898A8B8C8D8E8F909192939495969798999A9B9C9D9E9F"
"A0A1A2A3A4A5A6A7A8A9AAABACADAEAFB0B1B2B3B4B5B6B7B8B9BABBBCBDBEBF"
"C0C1C2C3C4C5C6C7C8C9CACBCCCDCECFD0D1D2D3D4D5D6D7D8D9DADBDCDDDEDF"
"E0E1E2E3E4E5E6E7E8E9EAEBECEDEEEFF0F1F2F3F4F5F6F7F8F9FAFBFCFDFEFF";
template <typename T, std::size_t BASE> requires (std::is_integral_v<T> && BASE > 0U && BASE <= _NUMBER_MAX_BASE)
struct IntegerToString_t
{
// maximum count of characters, including terminating null and negative sign where appropriate, needed for integer-to-string conversion
static consteval std::size_t MaxCount()
{
std::size_t nDigitsCount = 0U;
constexpr std::uint64_t ullNegativeMax = (std::is_unsigned_v<T> ? (std::numeric_limits<T>::max)() : (static_cast<std::uint64_t>((std::numeric_limits<T>::max)()) + 1ULL));
for (std::uint64_t nShift = ullNegativeMax; nShift > 0ULL; nShift /= BASE)
nDigitsCount++;
return (nDigitsCount + (std::is_signed_v<T> && BASE == 10U ? 1U : 0U) + 1U);
}
};
/*
* @section: utility
* - methods that provide general-purpose functionality
*/
#pragma region stl_utility
// indicate that an object may be "moved from", i.e. allowing the efficient transfer of resources to another object, alternative of 'std::move'
template <class T>
[[nodiscard]] CS_INLINE constexpr std::remove_reference_t<T>&& Move(T&& argument) noexcept
{
return static_cast<std::remove_reference_t<T>&&>(argument);
}
// forward an lvalue as either an lvalue or an rvalue, alternative of 'std::forward'
template <class T>
[[nodiscard]] CS_INLINE constexpr T&& Forward(std::remove_reference_t<T>& argument) noexcept
{
return static_cast<T&&>(argument);
}
// forward an rvalue as an rvalue, alternative of 'std::forward'
template <class T>
[[nodiscard]] CS_INLINE constexpr T&& Forward(std::remove_reference_t<T>&& argument) noexcept
{
static_assert(!std::is_lvalue_reference_v<T>, "bad forward call");
return static_cast<T&&>(argument);
}
/// swap value of @a'left' to @a'right' and @a'right' to @a'left', alternative of 'std::swap'
template <typename T>
requires (std::is_move_constructible_v<T> && std::is_move_assignable_v<T>)
CS_INLINE constexpr void Swap(T& left, T& right) noexcept(std::is_nothrow_move_constructible_v<T>&& std::is_nothrow_move_assignable_v<T>)
{
T temporary = Move(left);
left = Move(right);
right = Move(temporary);
}
#pragma endregion
/* @section: memory */
#pragma region crt_memory
/// compare bytes in two buffers, alternative of 'memcmp()'
/// @remarks: compares the first count bytes of @a'pFirstBuffer' and @a'pRightBuffer' and return a value that indicates their relationship, performs unsigned character comparison
/// @returns: <0 - if @a'pFirstBuffer' less than @a'pRightBuffer', 0 - if @a'pFirstBuffer' identical to @a'pRightBuffer', >0 - if @a'pFirstBuffer' greater than @a'pRightBuffer'
CS_INLINE int MemoryCompare(const void* pLeftBuffer, const void* pRightBuffer, std::size_t nCount)
{
auto pLeftByte = static_cast<const std::uint8_t*>(pLeftBuffer);
auto pRightByte = static_cast<const std::uint8_t*>(pRightBuffer);
while (nCount--)
{
if (*pLeftByte++ != *pRightByte++)
return pLeftByte[-1] - pRightByte[-1];
}
return 0;
}
/// compare bytes in two buffers, alternative of 'wmemcmp()'
/// @remarks: compares the first count characters of @a'pwLeftBuffer' and @a'pwRightBuffer' and return a value that indicates their relationship, performs signed character comparison
/// @returns: <0 - if @a'pwLeftBuffer' less than @a'pwRightBuffer', 0 - if @a'pwLeftBuffer' identical to @a'pwRightBuffer', >0 - if @a'pwLeftBuffer' greater than @a'pwRightBuffer'
CS_INLINE int MemoryCompareW(const wchar_t* pwLeftBuffer, const wchar_t* pwRightBuffer, std::size_t nCount)
{
while (nCount--)
{
if (*pwLeftBuffer++ != *pwRightBuffer++)
return pwLeftBuffer[-1] - pwRightBuffer[-1];
}
return 0;
}
/// find character in a buffer, alternative of 'memchr()'
/// @remarks: look for the first occurrence of @a'uSearch' character in the first @a'nCount' characters of buffer, performs unsigned comparison for elements
/// @returns: pointer to the found character on success, null otherwise
CS_INLINE void* MemoryChar(const void* pBuffer, const std::uint8_t uSearch, std::size_t nCount)
{
auto pByte = static_cast<const std::uint8_t*>(pBuffer);
while (nCount--)
{
if (*pByte == uSearch)
return const_cast<std::uint8_t*>(pByte);
++pByte;
}
return nullptr;
}
/// find wide character in a buffer, alternative of 'wmemchr()'
/// @remarks: look for the first occurrence of @a'wSearch' character in the first @a'nCount' wide characters of buffer, performs signed comparison for elements
/// @returns: pointer to the found wide character on success, null otherwise
CS_INLINE wchar_t* MemoryCharW(wchar_t* pwBuffer, const wchar_t wSearch, std::size_t nCount)
{
while (nCount--)
{
if (*pwBuffer == wSearch)
return pwBuffer;
++pwBuffer;
}
return nullptr;
}
/// set a buffer to a specified byte, alternative of 'memset()'
/// @remarks: sets the first @a'nCount' bytes of @a'pDestination' to the @a'uByte'
/// @returns: pointer to the @a'pDestination'
CS_INLINE void* MemorySet(void* pDestination, const std::uint8_t uByte, std::size_t nCount)
{
#ifdef CS_COMPILER_MSC
// @test: clang always tries to detect 'memset' like instructions and replace them with CRT's function call
if (const std::size_t nCountAlign = (nCount & 3U); nCountAlign == 0U)
{
auto pDestinationLong = static_cast<unsigned long*>(pDestination);
__stosd(pDestinationLong, static_cast<unsigned long>(uByte) * 0x01010101, nCount >> 2U);
}
else if (nCountAlign == 2U)
{
auto pDestinationWord = static_cast<unsigned short*>(pDestination);
__stosw(pDestinationWord, static_cast<unsigned short>(uByte | (uByte << 8U)), nCount >> 1U);
}
else
{
auto pDestinationByte = static_cast<unsigned char*>(pDestination);
__stosb(pDestinationByte, uByte, nCount);
}
#else
auto pDestinationByte = static_cast<std::uint8_t*>(pDestination);
while (nCount--)
*pDestinationByte++ = uByte;
#endif
return pDestination;
}
/// copy one buffer to another, alternative of 'memcpy()'
/// @remarks: copies @a'nCount' bytes from @a'pSource' to @a'pDestination'. if the source and destination regions overlap, the behavior is undefined
/// @returns: pointer to the @a'pDestination'
CS_INLINE void* MemoryCopy(void* pDestination, const void* pSource, std::size_t nCount)
{
#ifdef CS_COMPILER_MSC
// @test: clang always tries to detect 'memcpy' like instructions and replace them with CRT's function call
if (const std::size_t nCountAlign = (nCount & 3U); nCountAlign == 0U)
{
auto pDestinationLong = static_cast<unsigned long*>(pDestination);
auto pSourceLong = static_cast<const unsigned long*>(pSource);
__movsd(pDestinationLong, pSourceLong, nCount >> 2U);
}
else if (nCountAlign == 2U)
{
auto pDestinationWord = static_cast<unsigned short*>(pDestination);
auto pSourceWord = static_cast<const unsigned short*>(pSource);
__movsw(pDestinationWord, pSourceWord, nCount >> 1U);
}
else
{
auto pDestinationByte = static_cast<unsigned char*>(pDestination);
auto pSourceByte = static_cast<const unsigned char*>(pSource);
__movsb(pDestinationByte, pSourceByte, nCount);
}
#else
auto pDestinationByte = static_cast<std::uint8_t*>(pDestination);
auto pSourceByte = static_cast<const std::uint8_t*>(pSource);
while (nCount--)
*pDestinationByte++ = *pSourceByte++;
#endif
return pDestination;
}
/// move one buffer to another, alternative of 'memmove()'
/// @remarks: copies @a'nCount' bytes from @a'pSource' to @a'pDestination'. if some portions of the source and the destination regions overlap, both functions ensure that the original source bytes in the overlapping region are copied before being overwritten
/// @returns: pointer to the @a'pDestination'
CS_INLINE void* MemoryMove(void* pDestination, const void* pSource, std::size_t nCount)
{
auto pDestinationByte = static_cast<std::uint8_t*>(pDestination);
auto pSourceByte = static_cast<const std::uint8_t*>(pSource);
// perform copy when source greater than destination
if (pDestinationByte < pSourceByte)
{
#ifdef CS_COMPILER_MSC
// @todo: also check for available align for given nCount
__movsb(pDestinationByte, pSourceByte, nCount);
#else
while (nCount--)
*pDestinationByte++ = *pSourceByte++;
#endif
}
// inverse copy otherwise
else
{
std::uint8_t* pLastDestinationByte = pDestinationByte + (nCount - 1U);
const std::uint8_t* pLastSourceByte = pSourceByte + (nCount - 1U);
while (nCount--)
*pLastDestinationByte-- = *pLastSourceByte--;
}
return pDestination;
}
#pragma endregion
/*
* @section: character
* - valid only for default C locale
*/
#pragma region crt_characters
/// alternative of 'iscntrl()', @todo: 'iswcntrl()'
/// @returns: true if given character is a control character, false otherwise
[[nodiscard]] constexpr bool IsControl(const std::uint8_t uChar)
{
return (uChar <= 0x1F || uChar == 0x7F);
}
/// alternative of 'isdigit()', @todo: 'iswdigit()'
/// @returns: true if given character is decimal digit, false otherwise
[[nodiscard]] constexpr bool IsDigit(const std::uint8_t uChar)
{
return (uChar >= '0' && uChar <= '9');
}
/// alternative of 'isxdigit()', @todo: 'iswxdigit()'
/// @returns: true if given character is hexadecimal digit, false otherwise
[[nodiscard]] constexpr bool IsHexDigit(const std::uint8_t uChar)
{
return ((uChar >= '0' && uChar <= '9') || (uChar >= 'A' && uChar <= 'F') || (uChar >= 'a' && uChar <= 'f'));
}
/// alternative of 'isblank()', @todo: 'iswblank()'
/// @returns: true if given character is blank, false otherwise
[[nodiscard]] constexpr bool IsBlank(const std::uint8_t uChar)
{
return (uChar == '\t' || uChar == ' ');
}
/// alternative of 'isspace()', @todo: 'iswspace()'
/// @returns: true if given character is whitespace, false otherwise
[[nodiscard]] constexpr bool IsSpace(const std::uint8_t uChar)
{
return ((uChar >= '\t' && uChar <= '\r') || uChar == ' ');
}
/// alternative of 'isalpha()', @todo: 'iswalpha()'
/// @returns: true if given character is alphabetic, false otherwise
[[nodiscard]] constexpr bool IsAlpha(const std::uint8_t uChar)
{
return ((uChar >= 'A' && uChar <= 'Z') || (uChar >= 'a' && uChar <= 'z'));
}
/// alternative of 'isalnum()', @todo: 'iswalnum()'
/// @returns: true if given character is alphabetic or numeric, false otherwise
[[nodiscard]] constexpr bool IsAlphaNum(const std::uint8_t uChar)
{
return ((uChar >= '0' && uChar <= '9') || (uChar >= 'A' && uChar <= 'Z') || (uChar >= 'a' && uChar <= 'z'));
}
/// alternative of 'isprint()', @todo: 'iswprint()'
/// @returns: true if given character is printable, false otherwise
[[nodiscard]] constexpr bool IsPrint(const std::uint8_t uChar)
{
return (uChar >= ' ' && uChar <= '~');
}
/// alternative of 'isgraph()', @todo: 'iswgraph()'
/// @returns: true if given character is graphic (has a graphical representation), false otherwise
[[nodiscard]] constexpr bool IsGraph(const std::uint8_t uChar)
{
return (uChar >= '!' && uChar <= '~');
}
/// alternative of 'ispunct()', @todo: 'iswpunct()'
/// @returns: true if given character is a punctuation character, false otherwise
[[nodiscard]] constexpr bool IsPunct(const std::uint8_t uChar)
{
return ((uChar >= '!' && uChar <= '/') || (uChar >= ':' && uChar <= '@') || (uChar >= '[' && uChar <= '`') || (uChar >= '{' && uChar <= '~'));
}
/// alternative of 'isupper()', @todo: 'iswupper()'
/// @returns: true if given alphabetic character is uppercase, false otherwise
[[nodiscard]] constexpr bool IsUpper(const std::uint8_t uChar)
{
return (uChar >= 'A' && uChar <= 'Z');
}
/// alternative of 'islower()', @todo: 'iswlower()'
/// @returns: true if given alphabetic character is lowercase, false otherwise
[[nodiscard]] constexpr bool IsLower(const std::uint8_t uChar)
{
return (uChar >= 'a' && uChar <= 'z');
}
#pragma endregion
/* @section: character conversion */
#pragma region crt_character_conversion
/// convert single digit character to integer
/// @returns: converted value if character is digit, 0 otherwise
[[nodiscard]] constexpr std::int32_t CharToInt(const std::uint8_t uChar)
{
return IsDigit(uChar) ? (uChar - '0') : 0;
}
/// convert single hex digit character to integer
/// @returns: converted value if character is hex digit, 0 otherwise
[[nodiscard]] constexpr std::uint32_t CharToHexInt(const std::uint8_t uChar)
{
const std::uint8_t uCharLower = (uChar | ('a' ^ 'A'));
return ((uCharLower >= 'a' && uCharLower <= 'f') ? (uCharLower - 'a' + 0xA) : (IsDigit(uChar) ? (uChar - '0') : 0x0));
}
// convert single character to uppercase, alternative of 'toupper()', @todo: 'towupper()'
[[nodiscard]] constexpr char CharToUpper(const std::uint8_t uChar)
{
return static_cast<char>(IsLower(uChar) ? (uChar & ~('a' ^ 'A')) : uChar);
}
// convert single character to lowercase, alternative of 'tolower()', @todo: 'towlower()'
[[nodiscard]] constexpr char CharToLower(const std::uint8_t uChar)
{
return static_cast<char>(IsUpper(uChar) ? (uChar | ('a' ^ 'A')) : uChar);
}
#pragma endregion
/*
* @section: string
* - @note: return value of some methods correspond to the POSIX standard but not C standard, it was necessary to reduce time complexity of them
* - valid only for default C locale
*/
#pragma region crt_string
/// get the length of a string, alternative of 'strlen()', 'wcslen()'
/// @returns: number of characters in the string, not including the terminating null character
template <typename C> requires (std::is_same_v<C, char> || std::is_same_v<C, wchar_t>)
constexpr std::size_t StringLength(const C* tszSource)
{
const C* tszSourceEnd = tszSource;
while (*tszSourceEnd != C('\0'))
++tszSourceEnd;
return tszSourceEnd - tszSource;
}
/// get the length of a string limited by max length, alternative of 'strnlen()', 'wcsnlen()'
/// @returns: number of characters in the string, not including the terminating null character. if there is no null terminator within the first @a'nMaxLength' bytes of the string, then @a'nMaxLength' is returned to indicate the error condition
template <typename C> requires (std::is_same_v<C, char> || std::is_same_v<C, wchar_t>)
constexpr std::size_t StringLengthN(const C* tszSource, const std::size_t nMaxLength)
{
std::size_t i = 0U;
while (tszSource[i] != C('\0') && i < nMaxLength)
++i;
return i;
}
/// compare two strings, alternative of 'strcmp()', 'wcscmp()'
/// @remarks: performs a signed/unsigned character comparison depending on the string type
/// @returns: <0 - if @a'tszLeft' less than @a'tszRight', 0 - if @a'tszLeft' is identical to @a'tszRight', >0 - if @a'tszLeft' greater than @a'tszRight'
template <typename C> requires (std::is_same_v<C, char> || std::is_same_v<C, wchar_t>)
constexpr int StringCompare(const C* tszLeft, const C* tszRight)
{
if (tszLeft == nullptr)
return -1;
if (tszRight == nullptr)
return 1;
using ComparisonType_t = std::conditional_t<std::is_same_v<C, char>, std::uint8_t, std::conditional_t<sizeof(wchar_t) == 2U, std::int16_t, std::int32_t>>;
ComparisonType_t nLeft, nRight;
do
{
nLeft = static_cast<ComparisonType_t>(*tszLeft++);
nRight = static_cast<ComparisonType_t>(*tszRight++);
if (nLeft == C('\0'))
break;
} while (nLeft == nRight);
return nLeft - nRight;
}
/// case-insensitive compare two strings, alternative of 'stricmp()', @todo: 'wcsicmp()'
/// @remarks: performs unsigned character comparison
/// @returns: <0 - if @a'szLeft' less than @a'szRight', 0 - if @a'szLeft' is identical to @a'szRight', >0 - if @a'szLeft' greater than @a'szRight'
constexpr int StringCompareI(const char* szLeft, const char* szRight)
{
std::uint8_t uLeft, uRight;
do
{
uLeft = static_cast<std::uint8_t>(CharToLower(static_cast<std::uint8_t>(*szLeft++)));
uRight = static_cast<std::uint8_t>(CharToLower(static_cast<std::uint8_t>(*szRight++)));
if (uLeft == '\0')
break;
} while (uLeft == uRight);
return uLeft - uRight;
}
/// compare two strings up to the specified count of characters, alternative of 'strncmp()', 'wcsncmp()'
/// @remarks: performs a signed/unsigned character comparison depending on the string type
/// @returns: <0 - if @a'tszLeft' less than @a'tszRight', 0 - if 'tszLeft' is identical to @a'tszRight', >0 - if @a'tszLeft' greater than @a'tszRight'
template <typename C> requires (std::is_same_v<C, char> || std::is_same_v<C, wchar_t>)
constexpr int StringCompareN(const C* tszLeft, const C* tszRight, std::size_t nCount)
{
using ComparisonType_t = std::conditional_t<std::is_same_v<C, char>, std::uint8_t, std::conditional_t<sizeof(wchar_t) == 2U, std::int16_t, std::int32_t>>;
ComparisonType_t nLeft, nRight;
while (nCount--)
{
nLeft = static_cast<ComparisonType_t>(*tszLeft++);
nRight = static_cast<ComparisonType_t>(*tszRight++);
if (nLeft != nRight)
return nLeft - nRight;
if (nLeft == C('\0'))
break;
}
return 0;
}
/// find a character in a string, alternative of 'strchr()', 'wcschr()'
/// @remarks: the null terminating character is included in the search, performs signed character comparison
/// @returns: pointer to the first found occurrence of @a'iSearch' character in @a'tszSource' on success, null otherwise
template <typename C> requires (std::is_same_v<C, char> || std::is_same_v<C, wchar_t>)
constexpr C* StringChar(const C* tszSource, const int iSearch)
{
while (*tszSource != C('\0'))
{
if (*tszSource == iSearch)
return const_cast<C*>(tszSource);
++tszSource;
}
return nullptr;
}
/// find a last occurrence of character in a string, alternative of 'strrchr()', 'wcsrchr()'
/// @remarks: the null terminating character is included in the search, performs signed character comparison
/// @returns: pointer to the last found occurrence of @a'iSearch' character in @a'tszSource' on success, null otherwise
template <typename C> requires (std::is_same_v<C, char> || std::is_same_v<C, wchar_t>)
constexpr C* StringCharR(const C* tszSource, const int iSearch)
{
C* tszLastOccurrence = nullptr;
do
{
if (*tszSource == iSearch)
tszLastOccurrence = const_cast<C*>(tszSource);
} while (*tszSource++ != C('\0'));
return tszLastOccurrence;
}
/// search for one string inside another, alternative of 'strstr()', 'wcsstr()'
/// @remarks: finds the first occurrence of @a'tszSearch' in @a'tszSource'. the search does not include terminating null character, performs signed character comparison
/// @returns: pointer to the first found occurrence of @a'tszSearch' substring in @a'tszSource' on success, null otherwise
template <typename C> requires (std::is_same_v<C, char> || std::is_same_v<C, wchar_t>)
constexpr C* StringString(const C* tszSource, const C* tszSearch)
{
while (*tszSource != C('\0'))
{
while (*tszSearch != C('\0') && (*tszSource - *tszSearch) == C('\0'))
{
++tszSource;
++tszSearch;
}
if (*tszSearch == C('\0'))
return const_cast<C*>(tszSource);
++tszSource;
}
return nullptr;
}
/// case-insensitive search for one string inside another, alternative of 'strcasestr()'
/// @remarks: finds the first occurrence of @a'szSearch' in @a'szSource'. the search does not include terminating null character, performs unsigned character comparison
/// @returns: pointer to the first found occurrence of @a'szSearch' substring in @a'szSource' on success, null otherwise
constexpr char* StringStringI(const char* szSource, const char* szSearch)
{
while (*szSource != '\0')
{
while (*szSearch != '\0' && CharToLower(static_cast<std::uint8_t>(*szSource)) == CharToLower(static_cast<std::uint8_t>(*szSearch)))
{
++szSource;
++szSearch;
}
if (*szSearch == '\0')
return const_cast<char*>(szSource);
++szSource;
}
return nullptr;
}
/// copy a one string to another, alternative of 'stpcpy()', 'wcpcpy()'
/// @remarks: copies @a'szSource', including the terminating null character, to the location that's specified by @a'szDestination'. the behavior is undefined if the source and destination strings overlap
/// @returns: pointer to the terminating null in @a'tszDestination'
template <typename C> requires (std::is_same_v<C, char> || std::is_same_v<C, wchar_t>)
constexpr C* StringCopy(C* tszDestination, const C* tszSource)
{
while (*tszSource != C('\0'))
*tszDestination++ = *tszSource++;
*tszDestination = C('\0');
return tszDestination;
}
/// copy a one string to another up to the specified count of characters, alternative of 'stpncpy()', 'wcpncpy()'
/// @remarks: copies the initial @a'nCount' characters of @a'tszSource' to @a'tszDestination'. if count is less than or equal to the length of @a'tszSource', a null character is not appended automatically to the copied string. if @a'nCount' is greater than the length of @a'tszSource', the destination string is padded with null characters up to length count. the behavior is undefined if the source and destination strings overlap
/// @returns: pointer to @a'tszDestination' + @a'nCount'
template <typename C> requires (std::is_same_v<C, char> || std::is_same_v<C, wchar_t>)
constexpr C* StringCopyN(C* tszDestination, const C* tszSource, std::size_t nCount)
{
while (nCount--)
*tszDestination++ = (*tszSource != C('\0') ? *tszSource++ : C('\0'));
return tszDestination;
}
/// append a one string to another, alternative of 'stpcat()', 'wcpcat()'
/// @remarks: appends @a'tszSource' to @a'tszDestination' and terminates the resulting string with a null character. the initial character of @a'tszSource' overwrites the terminating null character of @a'tszDestination'. the behavior is undefined if the source and destination strings overlap
/// @returns: pointer to the terminating null in @a'tszDestination'
template <typename C> requires (std::is_same_v<C, char> || std::is_same_v<C, wchar_t>)
constexpr C* StringCat(C* tszDestination, const C* tszSource)
{
while (*tszDestination != C('\0'))
++tszDestination;
while (*tszSource != C('\0'))
*tszDestination++ = *tszSource++;
*tszDestination = C('\0');
return tszDestination;
}
/// append a one string to another up to the specified count of characters, alternative of 'stpncat()', 'wcpncat()'
/// @remarks: appends, at most, the first @a'nCount' characters of @a'tszSource' to @a'tszDestination'. the initial character of @a'tszSource' overwrites the terminating null character of @a'tszDestination'. if a null character appears in @a'tszSource' before @a'nCount' characters are appended, function appends all characters from @a'tszSource', up to the null character. if count is greater than the length of @a'tszSource', the length of @a'tszSource' is used in place of count. in all cases, the resulting string is terminated with a null character. if copying takes place between strings that overlap, the behavior is undefined
/// @returns: pointer to the terminating null in @a'tszDestination'
template <typename C> requires (std::is_same_v<C, char> || std::is_same_v<C, wchar_t>)
constexpr C* StringCatN(C* tszDestination, const C* tszSource, std::size_t nCount)
{
while (*tszDestination != C('\0'))
++tszDestination;
while (*tszSource != C('\0') && nCount--)
*tszDestination++ = *tszSource++;
*tszDestination = C('\0');
return tszDestination;
}
#pragma endregion
/*
* @section: string conversion
* - these methods can write past the end of a buffer that is too small.
* to prevent buffer overruns, ensure that buffer is large enough to hold the converted data and the trailing null-character.
* misuse of these methods can cause serious security issues in your code
* - valid only for default C locale
*/
#pragma region crt_string_conversion
/// convert every char in the string to uppercase
/// @returns: pointer to the @a'szDestination'
constexpr char* StringToUpper(char* szDestination)
{
char* szDestinationOut = szDestination;
while (*szDestinationOut++ != '\0')
*szDestinationOut = CharToUpper(static_cast<std::uint8_t>(*szDestinationOut));
return szDestination;
}
/// convert every char in the string to lowercase
/// @returns: pointer to the @a'szDestination'
constexpr char* StringToLower(char* szDestination)
{
char* szDestinationOut = szDestination;
while (*szDestinationOut++ != '\0')
*szDestinationOut = CharToLower(static_cast<std::uint8_t>(*szDestinationOut));
return szDestination;
}
// @todo: rework sprintf like, with specific format right here
/// convert the integer to a string, alternative of 'to_string', '_itoa_s', '_ltoa_s', '_ultoa_s', '_i64toa_s', '_ui64toa_s'
/// @param[in] iBase numeric base to use to represent number in range [2 .. 36]
/// @returns: pointer to the begin of converted integer in the buffer
template <typename T> requires std::is_integral_v<T>
char* IntegerToString(const T value, char* szDestination, const std::size_t nDestinationLength, int iBase = 10)
{
if (iBase < 0 || iBase == 1 || iBase > _NUMBER_MAX_BASE)
{
CS_ASSERT(false); // given number base is out of range
return szDestination;
}
const bool bIsPositive = (value >= 0);
std::make_unsigned_t<T> uValue = (bIsPositive ? static_cast<std::make_unsigned_t<T>>(value) : static_cast<std::make_unsigned_t<T>>(0 - value)); // @test: how it actually compiles, can avoid branch at compile time
char* szDestinationEnd = szDestination + nDestinationLength;
*--szDestinationEnd = '\0';
if (uValue == 0U)
*--szDestinationEnd = '0';
// for decimal base perform fast path write by two digits in a group
else if (iBase == 10)
{
while (uValue >= 100U)
{
const char* szTwoDigits = &_TWO_DIGITS_LUT[(uValue % 100U) * 2U];
*--szDestinationEnd = szTwoDigits[1];
*--szDestinationEnd = szTwoDigits[0];
uValue /= 100U;
}
if (uValue < 10U)
*--szDestinationEnd = _NUMBER_ALPHA[uValue];
else
{
const char* szTwoDigits = &_TWO_DIGITS_LUT[uValue * 2U];
*--szDestinationEnd = szTwoDigits[1];
*--szDestinationEnd = szTwoDigits[0];
}
// insert negative sign, only decimal base can have it
if (!bIsPositive)
*--szDestinationEnd = '-';
}
// for hexadecimal base perform fast path write by two digits in a group
else if (iBase == 16)
{
while (uValue >= 0x100)
{
const char* szTwoDigits = &_TWO_DIGITS_HEX_LUT[(uValue % 0x100) * 2U];
*--szDestinationEnd = szTwoDigits[1];
*--szDestinationEnd = szTwoDigits[0];
uValue /= 0x100;
}
if (uValue < 0x10)
*--szDestinationEnd = _NUMBER_ALPHA[uValue];
else
{
const char* szTwoDigits = &_TWO_DIGITS_HEX_LUT[uValue * 2U];
*--szDestinationEnd = szTwoDigits[1];
*--szDestinationEnd = szTwoDigits[0];
}
}
// for other bases perform write by single digit
else
{
while (uValue > 0U)
{
*--szDestinationEnd = _NUMBER_ALPHA[uValue % iBase];
uValue /= iBase;
}
}
return szDestinationEnd;
}
// @todo: rework sprintf like, with specific format right here
/// convert the floating point to a string, alternative of 'to_string'
/// @returns:
template <typename T> requires std::is_floating_point_v<T>
char* FloatToString(const T value, char* szDestination, const std::size_t nDestinationSize, int iPrecision = std::numeric_limits<T>::digits10)
{
// @todo: because i dont have time so yeah, would rebuild it some time
StringPrintN(szDestination, nDestinationSize, "%.*f", iPrecision, value);
return szDestination;
}
/**
* convert the time point to a string, alternative of 'strftime', 'wcsftime'
* @param[in] tszFormat string specifying the format of conversion. formatting codes are:
* - '%a' abbreviated weekday name
* - '%A' full weekday name
* - '%b' abbreviated month name
* - '%B' full month name
* - '%c' date and time representation appropriate for locale
* - '%C' century as a decimal number [0 .. 99]
* - '%d' day of month as a decimal number [01 .. 31]
* - '%D' equivalent to "%m/%d/%y"
* - '%e' day of month as a decimal number [1 .. 31], where single digits are preceded by a space
* - '%F' equivalent to "%Y-%m-%d"
* - '%g' week-based year without century as a decimal number, the ISO 8601 time format [00 .. 99]
* - '%G' week-based year as a decimal number, the ISO 8601 time format [0000 .. 9999]
* - '%h' Abbreviated month name(equivalent to % b)
* - '%H' hour in 24-hour format [00 .. 23]
* - '%I' hour in 12-hour format [01 .. 12]
* - '%j' day of the year as a decimal number [001 .. 366]
* - '%m' month as a decimal number [01 .. 12]
* - '%M' minute as a decimal number [00 .. 59]
* - '%n' new line character escape
* - '%p' the locale's A.M./P.M. indicator for 12-hour clock
* - '%r' the locale's 12-hour clock time
* - '%R' equivalent to "%H:%M"
* - '%S' second as decimal number [00 .. 59]
* - '%t' tab character escape
* - '%T' equivalent to "%H:%M:%S", the ISO 8601 time format
* - '%u' weekday as a decimal number, the ISO 8601 time format [1 .. 7]
* - '%U' week number of the year as a decimal number, where the first Sunday is the first day of week 1 [00 .. 53]
* - '%V' week number as a decimal number, the ISO 8601 time format [00 .. 53]
* - '%w' weekday as a decimal number [0 .. 6]
* - '%W' week number of the year as a decimal number, where the first Monday is the first day of week 1 [00 .. 53]
* - '%x' date representation for the locale
* - '%X' time representation for the locale
* - '%y' year without century, as decimal number [00 .. 99]
* - '%Y' year with century, as decimal number [1900 .. 9999]
* - '%z' the offset from UTC, the ISO 8601 format
* - '%Z' either the locale's time-zone name or time zone abbreviation, depending on registry settings
* - '%%' percent character escape
* @returns: the number of characters placed in @a'szDestination' not including the terminating null, if the total number of characters, including the terminating null, is more than @a'nDestinationSize', returns 0 and the contents of @a'szDestination' are indeterminate
**/
template <typename C> requires (std::is_same_v<C, char> || std::is_same_v<C, wchar_t>)
std::size_t TimeToString(C* tszDestination, const std::size_t nDestinationSize, const C* tszFormat, const std::tm* pTime)
{
// full names of weekdays
constexpr const char* arrWeekdayNames[7] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
// full names of months
constexpr const char* arrMonthNames[12] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
C* tszDestinationOut = tszDestination;
C* tszFormatCurrent = nullptr;
// try to find format token, at same time copy everything until it
while (*tszFormat != C('\0') && nDestinationSize > 0U)
{
if (*tszFormat == C('%'))
{
tszFormatCurrent = const_cast<C*>(tszFormat);
break;
}
*tszDestinationOut++ = *tszFormat++;
}
std::size_t nWroteCount = tszDestinationOut - tszDestination;
// check do we have nothing to format
if (tszFormatCurrent == nullptr)
return tszDestinationOut - tszDestination;
while (*tszFormatCurrent != C('\0') && nWroteCount < nDestinationSize)
{
// check is format token begin
if (*tszFormatCurrent == C('%'))
{
++tszFormatCurrent;
// we are don't support any locale and other modifiers
if (*tszFormatCurrent == C('#') || *tszFormatCurrent == C('0') || *tszFormatCurrent == C('E'))
++tszFormatCurrent;
const C* tszDestinationBefore = tszDestinationOut;
/*
* handle format token
* @test: C standard and POSIX are very unclear and don't explicitly specify the behaviour when time components are negative
*/
switch (*tszFormatCurrent)
{
case C('a'):
{
const char* szWeekdayName = arrWeekdayNames[pTime->tm_wday];
std::size_t i = 3U;
while (i-- > 0U)
*tszDestinationOut++ = static_cast<C>(szWeekdayName[i]);
break;
}
case C('A'):
{
const char* szWeekdayName = arrWeekdayNames[pTime->tm_wday];
while (*szWeekdayName != C('\0'))
*tszDestinationOut++ = static_cast<C>(*szWeekdayName++);
break;
}
case C('b'):
case C('h'): // equivalent to "%b"
{
const char* szMonthName = arrMonthNames[pTime->tm_mon];
std::size_t i = 3U;
while (i-- > 0U)
*tszDestinationOut++ = static_cast<C>(szMonthName[i]);
break;
}
case C('B'):
{
const char* szMonthName = arrMonthNames[pTime->tm_mon];
while (*szMonthName != C('\0'))
*tszDestinationOut++ = static_cast<C>(*szMonthName++);
break;
}
case C('c'):
{
// default locale equivalent to "%a %b %e %H:%M:%S %Y"
// @todo: is it possible to avoid these ugly branches and make string type dependent on template
if constexpr (std::is_same_v<C, wchar_t>)
tszDestinationOut += TimeToString(tszDestinationOut, nDestinationSize - (tszDestinationOut - tszDestination), L"%a %b %e %H:%M:%S %Y", pTime);
else
tszDestinationOut += TimeToString(tszDestinationOut, nDestinationSize - (tszDestinationOut - tszDestination), "%a %b %e %H:%M:%S %Y", pTime);
break;
}
case C('C'):
{
const int iYear = pTime->tm_year + 1900;
const int iCentury = iYear / 100;
if (iYear >= -99 && iYear < 0)
{
*tszDestinationOut++ = C('-');
*tszDestinationOut++ = C('0');
}
else if (iCentury >= 0 && iCentury < 100)
{
const char* szCenturyNumber = &_TWO_DIGITS_LUT[static_cast<unsigned int>(iCentury) * 2U];
*tszDestinationOut++ = static_cast<C>(*szCenturyNumber++);
*tszDestinationOut++ = static_cast<C>(*szCenturyNumber);
}
else
*tszDestinationOut++ = static_cast<C>(iCentury % 10U + '0');
break;
}
case C('d'):
{
const char* szMonthDayNumber = &_TWO_DIGITS_LUT[static_cast<unsigned int>(pTime->tm_mday) * 2U];
*tszDestinationOut++ = static_cast<C>(*szMonthDayNumber++);
*tszDestinationOut++ = static_cast<C>(*szMonthDayNumber);
break;
}
case C('D'):
[[fallthrough]];
case C('x'):
{
// default locale equivalent to "%m/%d/%y"
if constexpr (std::is_same_v<C, wchar_t>)
tszDestinationOut += TimeToString(tszDestinationOut, nDestinationSize - (tszDestinationOut - tszDestination), L"%m/%d/%y", pTime);
else
tszDestinationOut += TimeToString(tszDestinationOut, nDestinationSize - (tszDestinationOut - tszDestination), "%m/%d/%y", pTime);
break;
}
case C('e'):
{