forked from RubyMetric/chsrc
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathxy.h
More file actions
1943 lines (1671 loc) · 41.6 KB
/
Copy pathxy.h
File metadata and controls
1943 lines (1671 loc) · 41.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/** ------------------------------------------------------------
* Copyright © 2023-2026 曾奥然, 郭恒
* SPDX-License-Identifier: MIT
* -------------------------------------------------------------
* Lib Authors : 曾奥然 <ccmywish@qq.com>
* | 郭恒 <2085471348@qq.com>
* Contributors : Mikachu2333 <linkchou@yandex.com>
* | juzeon <skyjuzheng@gmail.com>
* | BingChunMoLi <bingchunmoli@bingchunmoli.com>
* | AnonTokio <anontokio@163.com>
* |
* Created On : <2023-08-28>
* Last Modified : <2026-06-22>
*
*
* xy: 襄阳、咸阳
*
* 为跨平台命令行应用程序准备的 C11 实用函数和宏 (utilities)
*
* 该库的特点是混合多种编程语言风味 (绝大多数为 Ruby),每个 API
* 均使用 @flavor 标注其参考依据
*
*
* 关于内存管理的说明:
* 1. 完全不考虑OOM等内存分配失败的情况
* 2. 不追求完全的内存无泄漏。各个函数尽量使用 @memory SAFE|LEAK标注
* return caller-free: 调用者需要负责释放返回的内存
* return caller-dont-care: 调用者不需要负责释放返回的内存
* param[out] `abc` caller-free: 调用者需要负责释放回传给参数 `abc` 的内存
* param[out] `abc` caller-dont-care: 调用者不需要负责释放回传给参数 `abc` 的内存
* ------------------------------------------------------------*/
#ifndef XY_H
#define XY_H
#define _XY_Version "v0.2.3.1-2026/06/22"
#define _XY_Maintain_URL "https://github.com/RubyMetric/chsrc/blob/dev/lib/xy.h"
#define _XY_Maintain_URL2 "https://gitee.com/RubyMetric/chsrc/blob/dev/lib/xy.h"
#if defined(__STDC__) && __STDC_VERSION__ < 201112L
# error "xy.h requires C11 or later, please use a new compiler which at least supports C11"
#endif
#if defined(__STDC__) && __STDC_VERSION__ < 201710L
# warning "xy.h recommends a C17 or later compiler"
#endif
#include <assert.h>
#include <ctype.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <dirent.h> // opendir() closedir()
#if defined(__STDC__) && __STDC_VERSION__ >= 202311
#define XY_Deprecate_This(msg) [[deprecated(msg)]]
#elif defined(__GNUC__) || defined(__clang__)
#define XY_Deprecate_This(msg) __attribute__((deprecated(msg)))
#elif defined(_MSC_VER)
#define XY_Deprecate_This(msg) __declspec(deprecated(msg))
#else
#define XY_Deprecate_This(msg)
#endif
/* 全局变量 与 全局状态 */
struct
{
bool enable_color;
bool inited;
bool on_windows;
bool on_linux;
bool on_macos;
bool on_bsd;
bool on_android;
/* @flavor 同 just 中的 os_family(),只区分 windows, unix */
char *os_family;
char *os_devnull;
}
xy =
{
.enable_color = true,
/* 由 xy_init() 赋值 */
.inited = false,
.on_windows = false,
.on_linux = false,
.on_macos = false,
.on_bsd = false,
.on_android = false,
.os_family = NULL,
.os_devnull = NULL
};
#ifdef _WIN32
#define XY_Build_On_Windows 1
#include <windows.h>
#include <shlobj.h>
#elif defined(__linux__) || defined(__linux)
#define XY_Build_On_Linux 1
#define XY_Build_On_Unix 1
#elif defined(__APPLE__)
#define XY_Build_On_macOS 1
#define XY_Build_On_Unix 1
#elif defined(__OpenBSD__) || defined(__NetBSD__) || defined(__FreeBSD__)
#define XY_Build_On_BSD 1
#define XY_Build_On_Unix 1
#endif
/**
* assert() 会被 NDEBUG 关闭,但我们也没有必要强制开启它,还是留给用户定义
*/
// #undef NDEBUG
#define xy_noop() ((void)0)
#define assert_str(a, b) assert (xy_streql ((a), (b)))
#define xy_throw(reason) assert(!reason)
/**
* @depreacated 避免消极用语
*
* @flavor Perl, PHP, Raku
*/
// #define die xy_throw
/**
* @depreacated 避免消极用语
*/
// #define xy_panic xy_throw
#define xy_unsupported() xy_throw("Unsuppoted")
#define xy_unimplemented() xy_throw("Unimplemented temporarily")
#define xy_unreached() xy_throw("This code shouldn't be reached")
#define xy_cant_be_null(p) if(!p) xy_throw("This pointer can't be null")
static inline void
_xy_internal_warn (char *str)
{
fprintf (stderr, "[xy.h] %s\n", str);
}
static void _xy_print_int (int n) {printf ("%d", n);}
static void _xy_print_long (long n) {printf ("%ld", n);}
static void _xy_print_long_long (long long n) {printf ("%lld", n);}
static void _xy_print_float (float n) {printf ("%f", n);}
static void _xy_print_double (double n) {printf ("%f", n);}
static void _xy_print_bool (bool b) {printf("%s", (b) ? "true" : "false");}
static void _xy_print_str (char *str) {printf ("%s", str);}
static void _xy_print_const_str (const char *str) {printf ("%s", str);}
static void _xy_println_int (int n) {printf ("%d\n", n);}
static void _xy_println_long (long n) {printf ("%ld\n", n);}
static void _xy_println_long_long (long long n) {printf ("%lld\n", n);}
static void _xy_println_float (float n) {printf ("%f\n", n);}
static void _xy_println_double (double n) {printf ("%f\n", n);}
static void _xy_println_bool (bool b) {printf("%s\n", (b) ? "true" : "false");}
static void _xy_println_str (char *str) {printf ("%s\n", str);}
static void _xy_println_const_str (const char *str) {printf ("%s\n", str);}
/**
* @flavor Ruby, Python
*/
#define print(x) _Generic((x), \
int: _xy_print_int, \
long: _xy_print_long, \
long long: _xy_print_long_long, \
float: _xy_print_float, \
double: _xy_print_double, \
bool: _xy_print_bool, \
char *: _xy_print_str, \
const char *: _xy_print_const_str, \
default: xy_throw("Unsupported type for print()!") \
)(x)
/**
* @flavor JVM family, Rust
*/
#define println(x) _Generic((x), \
int: _xy_println_int, \
long: _xy_println_long, \
long long: _xy_println_long_long, \
float: _xy_println_float, \
double: _xy_println_double, \
bool: _xy_println_bool, \
char *: _xy_println_str, \
const char *: _xy_println_const_str, \
default: xy_throw("Unsupported type for println()/say()!") \
)(x)
/* @flavor Raku, Perl */
#define say println
/* @flavor PHP */
#define echo println
/**
* @flavor HTML
*/
void br () { puts (""); }
void p (const char *s) { printf ("%s\n", s); }
#define xy_c_array_len(arr) (sizeof (arr) / sizeof (arr[0]))
/**
* @memory SAFE
* return caller-free
*/
static inline void *
xy_malloc0 (size_t size)
{
void *ptr = malloc (size);
memset (ptr, 0, size);
return ptr;
}
/**
* @brief 替换指针内容并自动释放旧内存
*
* @param pptr 指向要被替换内存区域的指针的指针
* *pptr 可为 NULL
* @param new_mem 新的内存区域
*
* @memory SAFE
*/
static inline void
xy_ptr_replace (char **pptr, char *new_mem)
{
xy_cant_be_null (pptr);
if (*pptr)
free (*pptr);
*pptr = new_mem;
}
/******************************************************
* String
******************************************************/
/**
* @brief 将 str 中所有的 pat 字符串替换成 replace,返回一个全新的字符串
*
* @flavor Ruby: String#gsub
*
* @param str 原字符串
* @param pat 要替换的字符串
* @param replace 替换成的字符串
*
* @return 替换后的新字符串
*
* @memory SAFE
* return caller-free
*/
static char *
xy_str_gsub (const char *str, const char *pat, const char *replace)
{
size_t replace_len = strlen (replace);
size_t pat_len = strlen (pat);
size_t unit = (replace_len > pat_len) ? (replace_len - pat_len) : 0;
size_t len = strlen (str);
const char *cur = str;
size_t count = 0;
while (cur < str + len)
{
char *fnd = strstr (cur, pat);
if (fnd)
{
count++;
cur = fnd + pat_len;
}
else
break;
}
// print(count); /* DEBUG 匹配次数 */
char *ret = malloc (unit * count + len + 1);
char *retcur = ret;
cur = str;
while (cur < str + len)
{
char *fnd = strstr (cur, pat);
if (fnd)
{
ptrdiff_t diff = fnd - cur;
strncpy (retcur, cur, diff);
cur = fnd + pat_len;
retcur += diff;
strcpy (retcur, replace);
retcur += replace_len;
}
else
break;
}
strcpy (retcur, cur);
return ret;
}
/**
* @flavor 见 xy_strcat()
*
* @memory SAFE
* return caller-free
*/
static char *
xy_2strcat (const char *str1, const char *str2)
{
size_t len = strlen (str1);
size_t size = len + strlen (str2) + 1;
char *ret = malloc (size);
strcpy (ret, str1);
strcpy (ret + len, str2);
return ret;
}
/**
* @brief 将多个字符串连接成一个字符串
*
* @flavor C语言存在 strcat(),然而限制比较大,我们重新实现
* 'concat' 这个API广泛应用于包括 Ruby、JavaScript、JVM family、C#
*
* 但由于 xy_str_concat() 显著长于 xy_strcat(),而这个 API 在 chsrc 中
* 又大量使用,所以我们选择后者这个更简短的形式
*
* @param count 连接的字符串数量
* @param ... 连接的字符串
*
* @return 拼接的新字符串
*
* @memory SAFE
* return caller-free
*/
static char *
xy_strcat (unsigned int count, ...)
{
size_t al_fixed = 256;
char *ret = calloc (1, al_fixed);
// 已分配次数
int al_times = 1;
// 当前已分配量
size_t al_cur = al_fixed;
const char *str = NULL;
// 需要分配的量
size_t al_need = 0;
// 用于 strcpy() 到 ret 的哪个位置
char *cur = ret + 0;
va_list args;
va_start (args, count);
for (int i = 0; i < count; i++)
{
bool need_realloc = false;
str = va_arg (args, const char *);
al_need += strlen (str) + 1;
while (al_need > al_cur)
{
al_times += 1;
al_cur = al_times * al_fixed;
need_realloc = true;
}
// printf("al_times %d, al_need %zd, al_cur %zd\n", al_times, al_need,
// al_cur);
if (need_realloc)
{
ptrdiff_t diff = cur - ret;
ret = realloc (ret, al_cur);
cur = ret + diff;
}
strcpy (cur, str);
// puts(ret);
cur += strlen (str);
}
va_end (args);
*cur = '\0';
return ret;
}
/**
* @brief 复制一个字符串,返回复制的新字符串
*
* @param str 要复制的字符串
*
* @return 复制的新字符串
*
* @memory SAFE
* return caller-free
*/
static char *
xy_strdup (const char *str)
{
if (!str)
{
_xy_internal_warn ("xy_strdup(): called with NULL!");
return NULL;
}
size_t len = strlen (str);
char *new = xy_malloc0 (len + 1);
strcpy (new, str);
return new;
}
#define _XY_Str_Bold 1
#define _XY_Str_Faint 2
#define _XY_Str_Italic 3
#define _XY_Str_Underline 4
#define _XY_Str_Blink 5
#define _XY_Str_Cross 9
#define xy_str_to_bold(str) _xy_str_to_terminal_style (_XY_Str_Bold, str)
#define xy_str_to_faint(str) _xy_str_to_terminal_style (_XY_Str_Faint, str)
#define xy_str_to_italic(str) _xy_str_to_terminal_style (_XY_Str_Italic, str)
#define xy_str_to_underline(str) _xy_str_to_terminal_style (_XY_Str_Underline, str)
#define xy_str_to_blink(str) _xy_str_to_terminal_style (_XY_Str_Blink, str)
#define xy_str_to_cross(str) _xy_str_to_terminal_style (_XY_Str_Cross, str)
#define _XY_Str_Red 31
#define _XY_Str_Green 32
#define _XY_Str_Yellow 33
#define _XY_Str_Blue 34
#define _XY_Str_Magenta 35
#define _XY_Str_Cyan 36
#define xy_str_to_red(str) _xy_str_to_terminal_style (_XY_Str_Red, str)
#define xy_str_to_green(str) _xy_str_to_terminal_style (_XY_Str_Green, str)
#define xy_str_to_yellow(str) _xy_str_to_terminal_style (_XY_Str_Yellow, str)
#define xy_str_to_blue(str) _xy_str_to_terminal_style (_XY_Str_Blue, str)
#define xy_str_to_magenta(str) _xy_str_to_terminal_style (_XY_Str_Magenta, str)
#define xy_str_to_purple xy_str_to_magenta
#define xy_str_to_cyan(str) _xy_str_to_terminal_style (_XY_Str_Cyan, str)
/**
* @memory SAFE
* return caller-free
*/
static char *
_xy_str_to_terminal_style (int style, const char *str)
{
char *color_fmt_str = NULL;
if (!xy.enable_color)
{
color_fmt_str = "%s";
goto new_str;
}
switch (style)
{
case _XY_Str_Red:
color_fmt_str = "\e[31m%s\e[0m"; break;
case _XY_Str_Green:
color_fmt_str = "\e[32m%s\e[0m"; break;
case _XY_Str_Yellow:
color_fmt_str = "\e[33m%s\e[0m"; break;
case _XY_Str_Blue:
color_fmt_str = "\e[34m%s\e[0m"; break;
case _XY_Str_Magenta:
color_fmt_str = "\e[35m%s\e[0m"; break;
case _XY_Str_Cyan:
color_fmt_str = "\e[36m%s\e[0m"; break;
case _XY_Str_Bold:
color_fmt_str = "\e[1m%s\e[0m"; break;
case _XY_Str_Faint:
color_fmt_str = "\e[2m%s\e[0m"; break;
case _XY_Str_Italic:
color_fmt_str = "\e[3m%s\e[0m"; break;
case _XY_Str_Underline:
color_fmt_str = "\e[4m%s\e[0m"; break;
case _XY_Str_Blink:
color_fmt_str = "\e[5m%s\e[0m"; break;
case _XY_Str_Cross:
color_fmt_str = "\e[9m%s\e[0m"; break;
}
// 标签后第一句必须为statement,否则会编译不通过
size_t len;
new_str:
// -2 把中间%s减掉
len = strlen (color_fmt_str) - 2;
char *buf = malloc (strlen (str) + len + 1);
sprintf (buf, color_fmt_str, str);
return buf;
}
static bool
xy_streql (const char *str1, const char *str2)
{
if (NULL==str1 || NULL==str2)
{
return false;
}
return strcmp (str1, str2) == 0 ? true : false;
}
static bool
xy_streql_ic (const char *str1, const char *str2)
{
if (NULL == str1 || NULL == str2)
{
return false;
}
size_t len1 = strlen (str1);
size_t len2 = strlen (str2);
if (len1 != len2)
{
return false;
}
for (size_t i = 0; i < len1; i++)
{
if (tolower (str1[i]) != tolower (str2[i]))
{
return false;
}
}
return true;
}
/**
* @flavor Ruby: String#end_with?
*
* @memory SAFE
*/
static bool
xy_str_end_with (const char *str, const char *suffix)
{
size_t len1 = strlen (str);
size_t len2 = strlen (suffix);
if (0 == len2)
return true; // 空字符串直接返回
if (len1 < len2)
return false;
const char *cur1 = str + len1 - 1;
const char *cur2 = suffix + len2 - 1;
for (int i = 0; i < len2; i++)
{
if (*cur1 != *cur2)
return false;
cur1--;
cur2--;
}
return true;
}
/**
* @flavor Ruby: String#start_with?
*
* @memory SAFE
*/
static bool
xy_str_start_with (const char *str, const char *prefix)
{
if (NULL==str || NULL==prefix)
{
return false;
}
size_t len1 = strlen (str);
size_t len2 = strlen (prefix);
if (0 == len2)
return true; // 空字符串直接返回
if (len1 < len2)
return false;
const char *cur1 = str;
const char *cur2 = prefix;
for (int i = 0; i < len2; i++)
{
if (*cur1 != *cur2)
return false;
cur1++;
cur2++;
}
return true;
}
/**
* @flavor Ruby: String#delete_prefix
*
* @memory SAFE
* return caller-free
*/
static char *
xy_str_delete_prefix (const char *str, const char *prefix)
{
bool yes = xy_str_start_with (str, prefix);
if (!yes)
{
return xy_strdup (str);
}
else
{
size_t len = strlen (prefix);
return xy_strdup (str + len);
}
}
/**
* @flavor Ruby: String#delete_suffix
*
* @memory SAFE
* return caller-free
*/
static char *
xy_str_delete_suffix (const char *str, const char *suffix)
{
char *new = xy_strdup (str);
bool yes = xy_str_end_with (str, suffix);
if (!yes)
return new;
size_t len1 = strlen (str);
size_t len2 = strlen (suffix);
char *cur = new + len1 - len2;
*cur = '\0';
return new;
}
/**
* @flavor Ruby: String#strip
*
* @memory SAFE
* return caller-free
*/
static char *
xy_str_strip (const char *str)
{
xy_cant_be_null (str);
const char *start = str;
while (*start && strchr ("\n\r\v\t\f ", *start))
start++;
if ('\0' == *start)
return xy_strdup ("");
const char *end = start + strlen (start) - 1;
while (end >= start && strchr ("\n\r\v\t\f ", *end))
end--;
size_t len = (size_t) (end - start + 1);
char *ret = xy_malloc0 (len + 1);
memcpy (ret, start, len);
ret[len] = '\0';
return ret;
}
typedef struct
{
bool found;
size_t begin;
size_t end;
}
XyStrFindResult_t;
/**
* @brief 查找子串,返回是否命中以及子串在原串中的起止位置(0 基,end 为闭区间)
*
* @memory SAFE
*/
static XyStrFindResult_t
xy_str_find (const char *str, const char *substr)
{
XyStrFindResult_t result = { .found = false, .begin = 0, .end = 0 };
if (!str || !substr)
return result;
if ('\0' == substr[0])
{
result.found = true;
return result;
}
const char *pos = strstr (str, substr);
if (!pos)
return result;
result.found = true;
result.begin = (size_t) (pos - str);
result.end = result.begin + strlen (substr) - 1;
return result;
}
/**
* @brief 获取字符串下一行的内容
*
* @note 将忽略开头的换行,截取至下一个换行前(不含换行符)
*
* @memory SAFE
* return caller-free
*/
static char *
xy_str_next_nonempty_line (const char *str)
{
if (!str)
return xy_strdup ("");
const char *cur = str;
while (*cur == '\n')
cur++;
if ('\0' == *cur)
return xy_strdup ("");
const char *newline = strchr (cur, '\n');
size_t len = newline ? (size_t) (newline - cur) : strlen (cur);
char *ret = xy_malloc0 (len + 1);
strncpy (ret, cur, len);
ret[len] = '\0';
return ret;
}
/**
* @brief 读取文件内容并返回字符串,失败时返回空字符串
*
* @note 已处理 \r\n 和 \r,返回的字符串均为 \n 换行
*
* @flavor Ruby: IO::read
*
* @memory SAFE
* return caller-free
*/
static char *
xy_file_read (const char *path)
{
FILE *fp = fopen (path, "rb");
if (!fp)
return xy_strdup ("");
if (fseek (fp, 0, SEEK_END) != 0)
{
fclose (fp);
return xy_strdup ("");
}
long size = ftell (fp);
if (size < 0)
{
fclose (fp);
return xy_strdup ("");
}
rewind (fp);
char *buf = xy_malloc0 ((size_t) size + 1);
size_t read_bytes = fread (buf, 1, (size_t) size, fp);
if (read_bytes < (size_t) size && ferror (fp))
{
fclose (fp);
free (buf);
return xy_strdup ("");
}
fclose (fp);
buf[read_bytes] = '\0';
char *formatted_str = xy_str_gsub (buf, "\r\n", "\n");
xy_ptr_replace (&formatted_str, xy_str_gsub (formatted_str, "\r", "\n"));
free (buf);
return formatted_str;
}
/******************************************************
* Logging
******************************************************/
#define _XY_Log_Plain 000000001
#define _XY_Log_Success 000000001 << 1
#define _XY_Log_Info 000000001 << 2
#define _XY_Log_Warn 000000001 << 3
#define _XY_Log_Error 000000001 << 4
#define xy_log(prompt, str) _xy_log (_XY_Log_Plain, prompt, str)
#define xy_succ(prompt,str) _xy_log (_XY_Log_Success, prompt, str)
#define xy_info(prompt,str) _xy_log (_XY_Log_Info, prompt, str)
#define xy_warn(prompt,str) _xy_log (_XY_Log_Warn, prompt, str)
#define xy_error(prompt,str) _xy_log (_XY_Log_Error, prompt, str)
/**
* @memory LEAK
* xy_str_to_*() 返回的中间色彩字符串传入xy_strcat() 后没有被释放;
* 最终的 str 本身已 free
*/
static void
_xy_log (int level, const char *prompt, const char *content)
{
char *str = NULL;
bool to_stderr = false;
/**
* 'app: content'
*/
if (level & _XY_Log_Plain)
{
str = xy_strcat (3, prompt, ": ", content);
}
else if (level & _XY_Log_Success)
{
str = xy_strcat (3, prompt, ": ", xy_str_to_green (content));
}
else if (level & _XY_Log_Info)
{
str = xy_strcat (3, prompt, ": ", xy_str_to_blue (content));
}
else if (level & _XY_Log_Warn)
{
str = xy_strcat (3, prompt, ": ", xy_str_to_yellow (content));
to_stderr = true;
}
else if (level & _XY_Log_Error)
{
str = xy_strcat (3, prompt, ": ", xy_str_to_red (content));
to_stderr = true;
}
else
{
xy_unreached();
}
if (to_stderr)
{
fprintf (stderr, "%s\n", str);
}
else
{
puts (str);
}
free (str);
}
/**
* @flavor brkt 系列输出受 Python 的 pip 启发,为了输出方便,使用 xy.h 的程序应该
*
* 1.若想完全自定义颜色和输出位置:
*
* 应基于下述 xy_log_brkt_to 定义自己的输出函数
*
* 2.若想自定义颜色,而保持输出到stdout:
*
* 应基于下述 xy_log_brkt 定义
*
* 3.若对log无细致要求,想要快速使用log功能:
*
* 应基于下述 xy_<level>_brkt 定义自己的 app_<level>_brkt(),或直接使用 xy_<level>_brkt
*/
/**
* @memory SAFE
*/
static void
xy_log_brkt_to (const char *prompt, const char *content, FILE *stream)
{
char *str = xy_strcat (4, "[", prompt, "] ", content);
fprintf (stream, "%s\n", str);
free (str);
}
#define xy_log_brkt(prompt1,prompt2,content) _xy_log_brkt(_XY_Log_Plain, prompt1,prompt2,content)
#define xy_succ_brkt(prompt1,prompt2,content) _xy_log_brkt(_XY_Log_Success,prompt1,prompt2,content)
#define xy_info_brkt(prompt1,prompt2,content) _xy_log_brkt(_XY_Log_Info, prompt1,prompt2,content)
#define xy_warn_brkt(prompt1,prompt2,content) _xy_log_brkt(_XY_Log_Warn, prompt1,prompt2,content)
#define xy_error_brkt(prompt1,prompt2,content) _xy_log_brkt(_XY_Log_Error, prompt1,prompt2,content)
/**
* @memory LEAK
* 同 _xy_log,xy_str_to_*() 嵌套调用产生的中间字符串没有被释放
*/
static void
_xy_log_brkt (int level, const char *prompt1, const char *prompt2, const char *content)
{
char *str = NULL;
bool to_stderr = false;
if (level & _XY_Log_Plain)
{
str = xy_strcat (6, "[", prompt1, " ", prompt2, "] ", content);
}
else if (level & _XY_Log_Success)
{
/* [app 成功] [app success] */
str = xy_strcat (6,
"[", xy_str_to_green (prompt1), " ", xy_str_to_bold (xy_str_to_green (prompt2)), "] ", xy_str_to_green (content));
}
else if (level & _XY_Log_Info)
{
/* [app 信息] [app info]
[app 提示] [app notice]
*/
str = xy_strcat (6,
"[", xy_str_to_blue (prompt1), " ", xy_str_to_bold (xy_str_to_blue (prompt2)), "] ", xy_str_to_blue (content));
}
else if (level & _XY_Log_Warn)
{
/* [app 警告] [app warn] */
str = xy_strcat (6,
"[", xy_str_to_yellow (prompt1), " ", xy_str_to_bold (xy_str_to_yellow (prompt2)), "] ", xy_str_to_yellow (content));
to_stderr = true;
}
else if (level & _XY_Log_Error)
{
/* [app 错误] [app error] */
str = xy_strcat (6,
"[", xy_str_to_red (prompt1), " ", xy_str_to_bold (xy_str_to_red (prompt2)), "] ", xy_str_to_red (content));
to_stderr = true;
}
else
{
xy_unreached();
}
if (to_stderr)
{
fprintf (stderr, "%s\n", str);
}
else
{
puts (str);
}
free (str);
}
/******************************************************
* cross OS
******************************************************/
/**
* @memory SAFE
* return caller-free
*/
static char *
xy_quiet_cmd (const char *cmd)
{
char *ret = NULL;
if (xy.on_windows)
ret = xy_2strcat (cmd, " >nul 2>nul ");
else
ret = xy_2strcat (cmd, " 1>/dev/null 2>&1 ");
return ret;
}