maomaowm/src/common/util.c

79 lines
1.5 KiB
C
Raw Normal View History

2025-02-03 23:18:47 +08:00
/* See LICENSE.dwm file for copyright and license details. */
2025-04-28 10:04:18 +08:00
#include <fcntl.h>
2025-02-03 23:18:47 +08:00
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "util.h"
2025-05-18 18:26:06 +08:00
#define PCRE2_CODE_UNIT_WIDTH 8
#include <pcre2.h>
2025-04-28 10:04:18 +08:00
void die(const char *fmt, ...) {
2025-06-07 13:53:12 +08:00
va_list ap;
2025-02-03 23:18:47 +08:00
2025-06-07 13:53:12 +08:00
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
2025-02-03 23:18:47 +08:00
2025-06-07 13:53:12 +08:00
if (fmt[0] && fmt[strlen(fmt) - 1] == ':') {
fputc(' ', stderr);
perror(NULL);
} else {
fputc('\n', stderr);
}
2025-02-03 23:18:47 +08:00
2025-06-07 13:53:12 +08:00
exit(1);
2025-02-03 23:18:47 +08:00
}
2025-04-28 10:04:18 +08:00
void *ecalloc(size_t nmemb, size_t size) {
2025-06-07 13:53:12 +08:00
void *p;
2025-02-03 23:18:47 +08:00
2025-06-07 13:53:12 +08:00
if (!(p = calloc(nmemb, size)))
die("calloc:");
return p;
2025-04-13 09:05:09 +08:00
}
2025-04-28 10:04:18 +08:00
int fd_set_nonblock(int fd) {
2025-06-07 13:53:12 +08:00
int flags = fcntl(fd, F_GETFL);
if (flags < 0) {
perror("fcntl(F_GETFL):");
return -1;
}
if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) < 0) {
perror("fcntl(F_SETFL):");
return -1;
}
2025-04-28 10:04:18 +08:00
2025-06-07 13:53:12 +08:00
return 0;
2025-02-03 23:18:47 +08:00
}
2025-05-18 18:26:06 +08:00
int regex_match(const char *pattern, const char *str) {
2025-06-07 13:53:12 +08:00
int errnum;
PCRE2_SIZE erroffset;
if (!pattern || !str) {
return 0;
}
2025-06-07 13:53:12 +08:00
pcre2_code *re = pcre2_compile((PCRE2_SPTR)pattern, PCRE2_ZERO_TERMINATED,
PCRE2_UTF, // 启用 UTF-8 支持
&errnum, &erroffset, NULL);
if (!re) {
PCRE2_UCHAR errbuf[256];
pcre2_get_error_message(errnum, errbuf, sizeof(errbuf));
fprintf(stderr, "PCRE2 error: %s at offset %zu\n", errbuf, erroffset);
return 0;
}
2025-05-18 18:26:06 +08:00
2025-06-07 13:53:12 +08:00
pcre2_match_data *match_data =
pcre2_match_data_create_from_pattern(re, NULL);
int ret =
pcre2_match(re, (PCRE2_SPTR)str, strlen(str), 0, 0, match_data, NULL);
2025-05-18 18:26:06 +08:00
2025-06-07 13:53:12 +08:00
pcre2_match_data_free(match_data);
pcre2_code_free(re);
return ret >= 0;
2025-05-18 18:26:06 +08:00
}