-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
jo_stdcpp.h
executable file
·2277 lines (2042 loc) · 65.4 KB
/
jo_stdcpp.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
// Written by Jon Olick
// This is free and unencumbered software released into the public domain.
//
// Anyone is free to copy, modify, publish, use, compile, sell, or
// distribute this software, either in source code form or as a compiled
// binary, for any purpose, commercial or non-commercial, and by any
// means.
//
// In jurisdictions that recognize copyright laws, the author or authors
// of this software dedicate any and all copyright interest in the
// software to the public domain. We make this dedication for the benefit
// of the public at large and to the detriment of our heirs and
// successors. We intend this dedication to be an overt act of
// relinquishment in perpetuity of all present and future rights to this
// software under copyright law.
//
// 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 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.
//
// For more information, please refer to <http://unlicense.org/>
#ifndef JO_STDCPP
#define JO_STDCPP
#pragma once
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <stddef.h>
#include <limits.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <atomic>
#include <mutex>
#include <condition_variable>
#ifdef _WIN32
#include <conio.h>
#include <direct.h>
#include <io.h>
#include <fcntl.h>
#include <sys/stat.h>
#define jo_strdup _strdup
#define jo_chdir _chdir
#define jo_alloca _alloca
#define jo_ftell64 _ftelli64
#define jo_popen _popen
#define jo_pclose _pclose
#pragma warning(push)
#pragma warning(disable : 4345)
#elif defined(__APPLE__)
#include <mach/mach_time.h>
#include <unistd.h>
#include <termios.h>
#define jo_ftell64 ftello
#define jo_popen popen
#define jo_pclose pclose
#else
#include <unistd.h>
#include <termios.h>
#define jo_ftell64 ftello64
#define jo_popen popen
#define jo_pclose pclose
#endif
// if clang or GCC
#if defined(__clang__) || defined(__GNUC__)
#define jo_strdup strdup
#define jo_chdir chdir
#define jo_alloca __builtin_alloca
#define jo_memcpy __builtin_memcpy
#define jo_memmove __builtin_memmove
#define jo_memset __builtin_memset
#define jo_assume __builtin_assume
#define jo_expect __builtin_expect
#else
#define jo_memcpy memcpy
#define jo_memmove memmove
#define jo_memset memset
#define jo_assume sizeof
#define jo_expect(expr, val) expr
#endif
template<typename T1, typename T2> static constexpr inline T1 jo_min(T1 a, T2 b) { return a < b ? a : b; }
template<typename T1, typename T2> static constexpr inline T1 jo_max(T1 a, T2 b) { return a > b ? a : b; }
#ifdef _WIN32
#include <mutex>
#define jo_mutex std::mutex
#else
#include <pthread.h>
class jo_mutex {
pthread_mutex_t mutex;
public:
jo_mutex() { pthread_mutex_init(&mutex, nullptr); }
~jo_mutex() { pthread_mutex_destroy(&mutex); }
void lock() { pthread_mutex_lock(&mutex); }
void unlock() { pthread_mutex_unlock(&mutex); }
};
#endif
class jo_lock_guard {
jo_mutex& mutex;
public:
jo_lock_guard(jo_mutex& mutex) : mutex(mutex) { mutex.lock(); }
~jo_lock_guard() { mutex.unlock(); }
};
static const char *va(const char *fmt, ...) {
static thread_local char tmp[0x10000];
static thread_local int at = 0;
char *ret = tmp+at;
va_list args;
va_start(args, fmt);
at += 1 + vsnprintf(ret, sizeof(tmp)-at-1, fmt, args);
va_end(args);
if(at > sizeof(tmp) - 0x400) {
at = 0;
}
return ret;
}
#ifdef _WIN32
static int jo_setenv(const char *name, const char *value, int overwrite) {
int errcode = 0;
if(!overwrite) {
size_t envsize = 0;
errcode = getenv_s(&envsize, NULL, 0, name);
if(errcode || envsize) return errcode;
}
return _putenv_s(name, value);
}
#else
#define jo_setenv setenv
#endif
static bool jo_file_exists(const char *path) {
FILE *f = fopen(path, "r");
if(f) {
fclose(f);
return true;
}
return false;
}
static size_t jo_file_size(const char *path) {
FILE *f = fopen(path, "r");
if(!f) return 0;
fseek(f, 0, SEEK_END);
size_t size = jo_ftell64(f);
fclose(f);
return size;
}
static bool jo_file_readable(const char *path) {
FILE *f = fopen(path, "r");
if(!f) return false;
fclose(f);
return true;
}
// tests to see if it can write to a file without truncating it
static bool jo_file_writable(const char *path) {
FILE *f = fopen(path, "r+");
if(!f) return false;
fclose(f);
return true;
}
// checks to see if file can be executed (cross-platform)
static bool jo_file_executable(const char *path) {
#ifdef _WIN32
// check stat to see if it has executable bit set
struct _stat s;
if(_stat(path, &s) != 0) return false;
return s.st_mode & _S_IEXEC;
#else
// check access to see if it can be executed
return access(path, X_OK) == 0;
#endif
}
static bool jo_file_empty(const char *path) {
FILE *f = fopen(path, "r");
if(!f) return true;
fseek(f, 0, SEEK_END);
size_t size = jo_ftell64(f);
fclose(f);
return size == 0;
}
// copy file 16k at a time
static bool jo_file_copy(const char *src, const char *dst) {
FILE *fsrc = fopen(src, "rb");
if(!fsrc) return false;
FILE *fdst = fopen(dst, "wb");
if(!fdst) {
fclose(fsrc);
return false;
}
char buf[16384];
size_t nread = 0;
while((nread = fread(buf, 1, sizeof(buf), fsrc)) != 0) {
fwrite(buf, 1, nread, fdst);
}
fclose(fsrc);
fclose(fdst);
return true;
}
// move file
static bool jo_file_move(const char *src, const char *dst) {
if(!jo_file_copy(src, dst)) return false;
return remove(src) == 0;
}
static int jo_kbhit() {
#ifdef _WIN32
return _kbhit();
#else
struct timeval tv;
fd_set fds;
tv.tv_sec = 0;
tv.tv_usec = 0;
FD_ZERO(&fds);
FD_SET(0, &fds); //STDIN_FILENO is 0
select(1, &fds, NULL, NULL, &tv);
return FD_ISSET(0, &fds);
#endif
}
static int jo_getch() {
#ifdef _WIN32
return _getch();
#else
struct termios oldt, newt;
int ch;
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
ch = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
return ch;
#endif
}
#ifndef _WIN32
#include <dirent.h>
static bool jo_dir_exists(const char *path) {
DIR *d = opendir(path);
if(d) {
closedir(d);
return true;
}
return false;
}
#else
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
static bool jo_dir_exists(const char *path) {
DWORD attrib = GetFileAttributes(path);
return (attrib != INVALID_FILE_ATTRIBUTES && (attrib & FILE_ATTRIBUTE_DIRECTORY));
}
#undef min
#undef max
#endif
// always adds a 0 terminator
static void *jo_slurp_file(const char *path, size_t *size) {
FILE *f = fopen(path, "rb");
if(!f) return NULL;
fseek(f, 0, SEEK_END);
size_t fsize = jo_ftell64(f);
fseek(f, 0, SEEK_SET);
void *data = malloc(fsize + 1);
if(!data) {
fclose(f);
return NULL;
}
size_t read = fread(data, 1, fsize, f);
fclose(f);
if(read != fsize) {
free(data);
return NULL;
}
((char *)data)[fsize] = 0;
if(size) *size = fsize;
return data;
}
static char *jo_slurp_file(const char *path) {
size_t size = 0;
void *data = jo_slurp_file(path, &size);
if(!data) return NULL;
char *str = (char *)data;
str[size] = 0;
return str;
}
static int jo_spit_file(const char *path, const void *data, size_t size) {
FILE *f = fopen(path, "wb");
if(!f) return 1;
size_t written = fwrite(data, 1, size, f);
fclose(f);
return written != size;
}
static int jo_spit_file(const char *path, const char *data) {
return jo_spit_file(path, data, strlen(data));
}
static int jo_tolower(int c) {
if(c >= 'A' && c <= 'Z') return c + 32;
return c;
}
static int jo_toupper(int c) {
if(c >= 'a' && c <= 'z') return c - 32;
return c;
}
static int jo_isspace(int c) {
return (c == ' ' || c == '\t' || c == '\n' || c == '\v' || c == '\f' || c == '\r');
}
static int jo_isletter(int c) {
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
}
// returns a pointer to the last occurrence of needle in haystack
// or NULL if needle is not found
static const char *jo_strrstr(const char *haystack, const char *needle) {
const char *h = haystack + strlen(haystack);
const char *n = needle + strlen(needle);
while(h > haystack) {
const char *h2 = h - 1;
const char *n2 = n - 1;
while(n2 > needle && *h2 == *n2) h2--, n2--;
if(n2 == needle) return h2;
h--;
}
return NULL;
}
// returns in floating point seconds
static inline double jo_time() {
#if defined(__APPLE__)
static mach_timebase_info_data_t sTimebaseInfo;
if (sTimebaseInfo.denom == 0) {
(void) mach_timebase_info(&sTimebaseInfo);
}
uint64_t time = mach_absolute_time();
return (double)time * sTimebaseInfo.numer / sTimebaseInfo.denom / 1000000000.0;
#elif defined(_WIN32)
static LARGE_INTEGER sFrequency;
static BOOL sInitialized = FALSE;
if (!sInitialized) {
sInitialized = QueryPerformanceFrequency(&sFrequency);
}
LARGE_INTEGER time;
QueryPerformanceCounter(&time);
return (double)time.QuadPart / sFrequency.QuadPart;
#else
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (double)ts.tv_sec + (double)ts.tv_nsec / 1000000000.0;
#endif
}
void jo_sleep(double seconds) {
#ifdef _WIN32
#if 0
LARGE_INTEGER due;
due.QuadPart = -int64_t(seconds * 1e7);
HANDLE timer = CreateWaitableTimer(NULL, FALSE, NULL);
SetWaitableTimerEx(timer, &due, 0, NULL, NULL, NULL, 0);
WaitForSingleObject(timer, INFINITE);
CloseHandle(timer);
#elif 1
static thread_local double estimate = 5e-3;
static thread_local double mean = 5e-3;
static thread_local double m2 = 0;
static thread_local int64_t count = 1;
double A,B;
while (seconds - estimate > 1e-7) {
double toWait = seconds - estimate;
LARGE_INTEGER due;
due.QuadPart = -int64_t(toWait * 1e7);
A = jo_time();
HANDLE timer = CreateWaitableTimer(NULL, FALSE, NULL);
SetWaitableTimerEx(timer, &due, 0, NULL, NULL, NULL, 0);
WaitForSingleObject(timer, INFINITE);
CloseHandle(timer);
B = jo_time();
double observed = B - A;
seconds -= observed;
++count;
double error = observed - toWait;
double delta = error - mean;
mean += delta / count;
m2 += delta * (error - mean);
double stddev = sqrt(m2 / (count - 1));
estimate = mean + stddev;
}
if(seconds > 0) {
A = B = jo_time();
while(B - A < seconds) {
std::this_thread::yield();
B = jo_time();
}
}
#else
Sleep(seconds * 1000);
#endif
#else
usleep(seconds * 1000000);
#endif
}
// yield exponential backoff
static void jo_yield_backoff(int *count) {
if(*count <= 3) {
// do nothing, just try again
} else if(*count <= 16) {
std::this_thread::yield();
} else {
const int lmin_ns = 1000;
const int lmax_ns = 1000000;
int sleep_ns = jo_min(lmin_ns + (int)((pow(*count + 1, 2) - 1) / 2), lmax_ns);
jo_sleep(sleep_ns / 1000000.0f);
}
(*count)++;
}
static FILE *jo_fmemopen(void *buf, size_t size, const char *mode) {
if (!size) {
return 0;
}
#ifdef _WIN32
(void)mode;
int fd;
FILE *fp;
char tp[MAX_PATH - 13];
char fn[MAX_PATH + 1];
int *pfd = &fd;
int retner = -1;
char tfname[] = "MemTF_";
if (!GetTempPathA(sizeof(tp), tp) || !GetTempFileNameA(tp, tfname, 0, fn)) {
return NULL;
}
retner = _sopen_s(pfd, fn, _O_CREAT | _O_SHORT_LIVED | _O_TEMPORARY | _O_RDWR | _O_BINARY | _O_NOINHERIT, _SH_DENYRW, _S_IREAD | _S_IWRITE);
if (retner != 0 || fd == -1) {
return NULL;
}
fp = _fdopen(fd, "wb+");
if (!fp) {
_close(fd);
return NULL;
}
/*File descriptors passed into _fdopen are owned by the returned FILE * stream.
If _fdopen is successful, do not call _close on the file descriptor.
Calling fclose on the returned FILE * also closes the file descriptor.
*/
fwrite(buf, size, 1, fp);
rewind(fp);
return fp;
#else
return fmemopen(buf, size, mode);
#endif
}
static char *jo_tmpnam() {
#ifdef _WIN32
char *buf = (char *)malloc(MAX_PATH);
if(!buf) return NULL;
if(!GetTempFileNameA(NULL, "jotmp", 0, buf)) {
free(buf);
return NULL;
}
return buf;
#else // not ideal, but shuts up warnings...
char *tmpfile = jo_strdup("/tmp/indi_XXXXXX");
int fd = mkstemp(tmpfile);
if(fd == -1) return NULL;
close(fd);
return tmpfile;
#endif
}
static unsigned jo_lrotl(unsigned x, int r) {
return (x << r) | (x >> (32 - r));
}
//
// Simple C++std replacements...
//
#define JO_M_PI 3.14159265358979323846
#define JO_M_PI_2 1.57079632679489661923
#define JO_M_PI_4 0.785398163397448309616
#define JO_M_1_PI 0.318309886183790671538
#define JO_M_2_PI 0.636619772367581343076
#define JO_M_2_SQRTPI 1.12837916709551257390
#define JO_M_SQRT2 1.41421356237309504880
#define JO_M_SQRT1_2 0.707106781186547524401
#define JO_M_LOG2E 1.44269504088896340736
#define JO_M_LOG10E 0.434294481903251827651
#define JO_M_LN2 0.693147180559945309417
#define JO_M_LN10 2.30258509299404568402
#define JO_M_E 2.7182818284590452354
template<typename T> struct jo_numeric_limits;
template<> struct jo_numeric_limits<int> {
static int max() { return INT_MAX; }
static int min() { return INT_MIN; }
};
#define jo_endl ("\n")
#define jo_npos ((size_t)(-1))
// jo_pair is a simple pair of values
template<typename T1, typename T2>
struct jo_pair {
T1 first;
T2 second;
jo_pair() : first(), second() {}
jo_pair(const T1 &a, const T2 &b) : first(a), second(b) {}
bool operator==(const jo_pair<T1, T2> &other) const { return first == other.first && second == other.second; }
bool operator!=(const jo_pair<T1, T2> &other) const { return !(*this == other); }
bool operator<(const jo_pair<T1, T2> &other) const {
if(first < other.first) return true;
if(first > other.first) return false;
return second < other.second;
}
};
// jo_make_pair
template<typename T1, typename T2>
inline jo_pair<T1, T2> jo_make_pair(const T1 &a, const T2 &b) {
return jo_pair<T1, T2>(a, b);
}
// jo_tuple
template<typename T1, typename T2, typename T3>
struct jo_tuple {
T1 first;
T2 second;
T3 third;
jo_tuple() : first(), second(), third() {}
jo_tuple(const T1 &a, const T2 &b, const T3 &c) : first(a), second(b), third(c) {}
bool operator==(const jo_tuple<T1, T2, T3> &other) const { return first == other.first && second == other.second && third == other.third; }
bool operator!=(const jo_tuple<T1, T2, T3> &other) const { return !(*this == other); }
bool operator<(const jo_tuple<T1, T2, T3> &other) const {
if(first < other.first) return true;
if(first > other.first) return false;
if(second < other.second) return true;
if(second > other.second) return false;
return third < other.third;
}
};
// jo_swap, std::swap alternative
template<typename T>
inline void jo_swap(T &a, T &b) {
T tmp = a;
a = b;
b = tmp;
}
static uint64_t thread_local jo_rnd_state = 0x4d595df4d0f33173;
static uint32_t jo_rotr32(uint32_t x, unsigned r) {
#ifdef _WIN32
return _rotr(x, r);
#else
return (x >> r) | (x << (32 - r));
#endif
}
uint32_t jo_pcg32(uint64_t *state) {
uint64_t x = *state;
unsigned count = (unsigned)(x >> 59); // 59 = 64 - 5
*state = x * 6364136223846793005u + 1442695040888963407u;
x ^= x >> 18; // 18 = (64 - 27)/2
return jo_rotr32((uint32_t)(x >> 27), count); // 27 = 32 - 5
}
uint64_t jo_pcg32_init(uint64_t seed) {
uint64_t state = seed + 1442695040888963407u;
(void)jo_pcg32(&state);
return state;
}
// jo_random_int
inline int jo_random_int(int min, int max) {
return min + (jo_pcg32(&jo_rnd_state) % (max - min + 1));
}
inline int jo_random_int(int max) {
return jo_random_int(0, max);
}
inline int jo_random_int() {
return jo_random_int(0, 0x7ffffff0);
}
inline double jo_random_float() {
return (double)jo_pcg32(&jo_rnd_state) / (double)UINT32_MAX;
}
// jo_random_shuffle
template<typename T>
void jo_random_shuffle(T *begin, T *end) {
for(T *i = begin; i != end; ++i) {
T *j = begin + jo_random_int(end - begin - 1);
jo_swap(*i, *j);
}
}
// count leading zeros
inline int jo_clz32(int x) {
#ifdef _WIN32
unsigned long r = 0;
_BitScanReverse(&r, x);
return 31 - r;
#else
return __builtin_clz(x);
#endif
}
inline long long jo_clz64(long long x) {
#ifdef _WIN32
unsigned long r = 0;
_BitScanReverse64(&r, x);
return 63 - r;
#else
return __builtin_clzll(x);
#endif
}
struct jo_object {
virtual ~jo_object() {}
};
struct jo_string {
char *str;
size_t size;
jo_string() { str = jo_strdup(""); size = 1; }
jo_string(const char *ss) { str = jo_strdup(ss); size = strlen(ss) + 1; }
jo_string(char c) { str = jo_strdup(" "); str[0] = c; size = 2; }
jo_string(const jo_string *other) { str = jo_strdup(other->str); size = other->size; }
jo_string(const jo_string &other) { str = jo_strdup(other.str); size = other.size; }
jo_string(jo_string &&other) {
str = other.str;
size = other.size;
other.str = NULL;
other.size = 0;
}
jo_string(const char *a, size_t s) {
size = s+1;
str = (char*)malloc(size);
jo_memcpy(str, a, s);
str[s] = 0;
}
jo_string(const char *a, const char *b) {
ptrdiff_t s = b - a;
size = s + 1;
str = (char*)malloc(size);
jo_memcpy(str, a, s);
str[s] = 0;
}
~jo_string() {
free(str);
str = 0;
size = 0;
}
const char *c_str() const { return str; };
int compare(const jo_string &other) { return memcmp(str, other.str, jo_min(size, other.size)); }
size_t length() const { return size-1; }
jo_string &operator=(const char *s) {
size = strlen(s) + 1;
char *tmp = (char*)malloc(size);
jo_memcpy(tmp, s, size);
free(str);
str = tmp;
return *this;
}
jo_string &operator=(const jo_string &s) {
char *tmp = (char*)malloc(s.size);
size = s.size;
jo_memcpy(tmp, s.str, size);
free(str);
str = tmp;
return *this;
}
jo_string &operator+=(const char *s) {
size_t l0 = size-1;
size_t l1 = strlen(s);
char *new_str = (char*)realloc(str, l0 + l1 + 1);
if(!new_str) {
// malloc failed!
return *this;
}
str = new_str;
size = l0 + l1 + 1;
jo_memcpy(str+l0, s, l1);
str[l0+l1] = 0;
return *this;
}
jo_string &operator+=(const jo_string &s) {
size_t l0 = size-1;
size_t l1 = s.size-1;
char *new_str = (char*)realloc(str, l0 + l1 + 1);
if(!new_str) {
// malloc failed!
return *this;
}
str = new_str;
size = l0 + l1 + 1;
jo_memcpy(str+l0, s.str, l1);
str[l0+l1] = 0;
return *this;
}
jo_string &operator+=(char c) {
size_t l0 = size-1;
char *new_str = (char*)realloc(str, l0 + 2);
if(!new_str) {
// malloc failed!
return *this;
}
str = new_str;
str[l0] = c;
str[l0+1] = 0;
size = l0 + 2;
return *this;
}
size_t find_last_of(char c) const {
for(long long i = size - 2; i >= 0; --i) {
if(str[i] == c) return i;
}
return jo_npos;
}
size_t find_last_of(const char *s) const {
size_t l = strlen(s);
if(l == 1) return find_last_of(s[0]);
for(long long i = size - l - 2; i >= 0; --i) {
size_t j = 0;
for(; j < l; ++j) {
if(str[i+j] != s[j]) break;
}
if(j == l) return i;
}
return jo_npos;
}
jo_string &erase(size_t n) {
str[n] = 0;
size = n+1;
return *this;
}
jo_string &erase(size_t n, size_t m) {
size_t l = size-1;
if(n >= l) return *this;
if(m > l) m = l;
jo_memmove(str+n, str+m, l-m+1);
size = l - m + n + 1;
return *this;
}
jo_string &insert(size_t n, const char *s) {
size_t l0 = size-1;
size_t l1 = strlen(s);
if(n > l0) n = l0;
char *new_str = (char*)malloc(l0 + l1 + 1);
if(!new_str) {
// malloc failed!
return *this;
}
jo_memcpy(new_str, str, n);
jo_memcpy(new_str+n, s, l1);
jo_memcpy(new_str+n+l1, str+n, l0-n+1);
free(str);
str = new_str;
size = l0 + l1 + 1;
return *this;
}
jo_string substr(size_t pos = 0, size_t len = jo_npos) const {
if(len == jo_npos) {
len = size - 1 - pos;
}
if(pos >= size - 1) return jo_string();
return jo_string(str + pos, len);
}
size_t find(char c, size_t pos = 0) const {
const char *tmp = strchr(str+pos, c);
if(!tmp) return jo_npos;
return (size_t)(tmp - str);
}
size_t find(const char *s, size_t pos = 0) const {
const char *tmp = strstr(str+pos, s);
if(!tmp) return jo_npos;
return (size_t)(tmp - str);
}
size_t find(const jo_string &s, size_t pos = 0) const { return find(s.c_str(), pos); }
static jo_string format(const char *fmt, ...) {
va_list args;
va_start(args, fmt);
int len = vsnprintf(0, 0, fmt, args);
va_end(args);
if(len < 0) {
// error
return jo_string();
}
char *tmp = (char*)malloc(len+1);
if(!tmp) {
// malloc failed!
return jo_string();
}
va_start(args, fmt);
vsnprintf(tmp, len+1, fmt, args);
va_end(args);
return jo_string(tmp);
}
int compare(const char *s) const { return strcmp(str, s); }
jo_string &lower() {
for(size_t i = 0; i < size-1; i++) {
str[i] = (char)jo_tolower(str[i]);
}
return *this;
}
jo_string &upper() {
for(size_t i = 0; i < size-1; i++) {
str[i] = (char)jo_toupper(str[i]);
}
return *this;
}
jo_string &reverse() {
char *tmp = str;
char *end = str + length();
while(tmp < end) {
char c = *tmp;
*tmp = *end;
*end = c;
tmp++;
end--;
}
return *this;
}
// True if s empty or contains only whitespace.
bool empty() const {
for(size_t i = 0; i < size-1; i++) {
if(!jo_isspace(str[i])) return false;
}
return true;
}
// Converts first character of the string to upper-case, all other characters to lower-case.
jo_string &capitalize() {
if(size-1 == 0) return *this;
str[0] = (char)jo_toupper(str[0]);
for(size_t i = 1; i < size-1; i++) {
str[i] = (char)jo_tolower(str[i]);
}
return *this;
}
bool ends_with(const char *s) const {
size_t l1 = strlen(s);
size_t l2 = size-1;
if(l1 > l2) return false;
return strcmp(str+l2-l1, s) == 0;
}
bool starts_with(const char *s) const {
size_t l1 = strlen(s);
size_t l2 = size-1;
if(l1 > l2) return false;
return strncmp(str, s, l1) == 0;
}
bool includes(const char *s) const {
return find(s) != jo_npos;
}
int index_of(char c) const {
for(size_t i = 0; i < size-1; i++) {
if(str[i] == c) return (int)i;
}
return -1;
}
int index_of(const char *s) const {
size_t pos = find(s);
if(pos == jo_npos) return -1;
return (int)pos;
}
int last_index_of(char c) const {
for(int i = (int)size-1; i >= 0; i--) {
if(str[i] == c) return i;
}
return -1;
}
int last_index_of(const char *s) const {
size_t pos = find_last_of(s);
if(pos == jo_npos) return -1;
return (int)pos;
}
jo_string &trim() {
size_t start = 0;
while(start < size-1 && jo_isspace(str[start])) {
start++;
}
size_t end = size-1;
while(end > start && jo_isspace(str[end])) {
end--;
}
if(start > 0 || end < size-1) {
char *tmp = (char*)malloc(end-start+2);
if(!tmp) {
// malloc failed!
return *this;
}
jo_memcpy(tmp, str+start, end-start+1);
tmp[end-start+1] = 0;
free(str);
str = tmp;
size = end-start+2;
}
return *this;
}
jo_string <rim() {
size_t start = 0;
while(start < size-1 && jo_isspace(str[start])) {
start++;
}
if(start > 0) {
char *tmp = (char*)malloc(size-1-start+1);
if(!tmp) {
// malloc failed!
return *this;
}
jo_memcpy(tmp, str+start, size-1-start);
tmp[size-1-start] = 0;
free(str);
str = tmp;
size = size-1-start+1;
}
return *this;
}
jo_string &rtrim() {
size_t end = size-2;
while(end > 0 && jo_isspace(str[end])) {
end--;
}
if(end < size-2) {
char *tmp = (char*)malloc(end+2);
if(!tmp) {