| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
#pragma once |
| 5 |
#include <ctype.h> |
| 6 |
#include <math.h> |
| 7 |
#include <stdarg.h> |
| 8 |
#include <stdbool.h> |
| 9 |
#include <stddef.h> |
| 10 |
#include <stdio.h> |
| 11 |
#include <string.h> |
| 12 |
|
| 13 |
#include "misc.h" |
| 14 |
|
| 15 |
#define mstrncmp(s1, s2) strncmp((s1), (s2), strlen(s1)) |
| 16 |
|
| 17 |
char *mstrjoin(const char *src1, const char *src2); |
| 18 |
char *mstrjoin3(const char *src1, const char *src2, const char *src3); |
| 19 |
void mstrextend(char **psrc1, const char *src2); |
| 20 |
const char *trim_both(const char *src, size_t *length); |
| 21 |
|
| 22 |
|
| 23 |
double strtod_simple(const char *, const char **); |
| 24 |
|
| 25 |
static inline int uitostr(unsigned int n, char *buf) { |
| 26 |
int ret = 0; |
| 27 |
unsigned int tmp = n; |
| 28 |
while (tmp > 0) { |
| 29 |
tmp /= 10; |
| 30 |
ret++; |
| 31 |
} |
| 32 |
|
| 33 |
if (ret == 0) { |
| 34 |
ret = 1; |
| 35 |
} |
| 36 |
|
| 37 |
int pos = ret; |
| 38 |
while (pos--) { |
| 39 |
buf[pos] = (char)(n % 10 + '0'); |
| 40 |
n /= 10; |
| 41 |
} |
| 42 |
return ret; |
| 43 |
} |
| 44 |
|
| 45 |
|
| 46 |
static inline size_t __attribute__((format(printf, 2, 3))) |
| 47 |
casprintf(char **strp, const char *fmt, ...) { |
| 48 |
va_list ap; |
| 49 |
va_start(ap, fmt); |
| 50 |
int ret = vasprintf(strp, fmt, ap); |
| 51 |
va_end(ap); |
| 52 |
|
| 53 |
BUG_ON(ret < 0); |
| 54 |
return (size_t)ret; |
| 55 |
} |
| 56 |
|
| 57 |
|
| 58 |
|
| 59 |
static inline void dtostr(double n, char **buf) { |
| 60 |
BUG_ON(safe_isnan(n)); |
| 61 |
BUG_ON(safe_isinf(n)); |
| 62 |
if (fabs(n) > 1e9) { |
| 63 |
|
| 64 |
casprintf(buf, "%.0f", n); |
| 65 |
return; |
| 66 |
} |
| 67 |
|
| 68 |
if (n > 0) { |
| 69 |
casprintf(buf, "%.0f.%03d", floor(n), (int)(fmod(n, 1) * 1000)); |
| 70 |
} else { |
| 71 |
casprintf(buf, "-%.0f.%03d", floor(-n), (int)(fmod(-n, 1) * 1000)); |
| 72 |
} |
| 73 |
} |
| 74 |
|
| 75 |
static inline const char *skip_space_const(const char *src) { |
| 76 |
if (!src) { |
| 77 |
return NULL; |
| 78 |
} |
| 79 |
while (*src && isspace((unsigned char)*src)) { |
| 80 |
src++; |
| 81 |
} |
| 82 |
return src; |
| 83 |
} |
| 84 |
|
| 85 |
static inline char *skip_space_mut(char *src) { |
| 86 |
if (!src) { |
| 87 |
return NULL; |
| 88 |
} |
| 89 |
while (*src && isspace((unsigned char)*src)) { |
| 90 |
src++; |
| 91 |
} |
| 92 |
return src; |
| 93 |
} |
| 94 |
|
| 95 |
#define skip_space(x) \ |
| 96 |
_Generic((x), char *: skip_space_mut, const char *: skip_space_const)(x) |
| 97 |
|
| 98 |
static inline bool starts_with(const char *str, const char *needle, bool ignore_case) { |
| 99 |
if (ignore_case) { |
| 100 |
return strncasecmp(str, needle, strlen(needle)) == 0; |
| 101 |
} |
| 102 |
return strncmp(str, needle, strlen(needle)) == 0; |
| 103 |
} |
| 104 |
|
| 105 |
|
| 106 |
|
| 107 |
int asnprintf(char **strp, size_t *capacity, const char *fmt, ...) |
| 108 |
__attribute__((format(printf, 3, 4))); |