- 在 `core_mem.h` 中新增 `smcc_strlen` 函数,用于计算字符串长度 - 调整 `VEC` 宏定义参数,移除冗余的 name 参数,增强结构体声明一致性 - 修改 `cstring_from_cstr` 返回值字段顺序,保持代码风格统一 - 在 `libcore.h` 中增加日志相关宏定义的保护判断,防止重复定义冲突
135 lines
2.8 KiB
C
135 lines
2.8 KiB
C
#ifndef __CORE_STR_H__
|
|
#define __CORE_STR_H__
|
|
|
|
#include "core_impl.h"
|
|
#include "core_log.h"
|
|
#include "core_type.h"
|
|
|
|
typedef struct cstring {
|
|
usize size;
|
|
usize cap;
|
|
char *data;
|
|
} cstring_t;
|
|
|
|
/**
|
|
* 创建一个新的空字符串
|
|
*/
|
|
static inline cstring_t cstring_new(void) {
|
|
return (cstring_t){.data = null, .size = 0, .cap = 0};
|
|
}
|
|
|
|
/**
|
|
* 从 C 字符串创建 Rust 风格字符串
|
|
*/
|
|
static inline cstring_t cstring_from_cstr(const char *s) {
|
|
if (s == null) {
|
|
return cstring_new();
|
|
}
|
|
|
|
usize len = 0;
|
|
const char *p = s;
|
|
while (*p++)
|
|
len++;
|
|
|
|
char *data = (char *)smcc_malloc(len + 1);
|
|
Assert(data != null);
|
|
smcc_memcpy(data, s, len);
|
|
data[len] = '\0';
|
|
|
|
return (cstring_t){.size = len + 1, .cap = len + 1, .data = data};
|
|
}
|
|
|
|
/**
|
|
* 释放字符串资源
|
|
*/
|
|
static inline void cstring_free(cstring_t *str) {
|
|
if (str && str->data && str->cap != 0) {
|
|
smcc_free(str->data);
|
|
str->data = null;
|
|
str->size = 0;
|
|
str->cap = 0;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 向字符串追加内容
|
|
*/
|
|
static inline void cstring_push_cstr(cstring_t *str, const char *data,
|
|
usize len) {
|
|
if (str == null || data == null || len == 0) {
|
|
return;
|
|
}
|
|
|
|
if (str->cap == 0) {
|
|
str->size = 1;
|
|
}
|
|
|
|
// 如果需要扩容
|
|
if (str->size + len > str->cap) {
|
|
usize new_cap = str->cap;
|
|
while (new_cap < str->size + len) {
|
|
new_cap *= 2;
|
|
// FIXME write by AI 处理溢出情况
|
|
if (new_cap == 0) {
|
|
new_cap = str->size + len;
|
|
break;
|
|
}
|
|
}
|
|
|
|
char *new_data = (char *)smcc_realloc(str->data, new_cap);
|
|
Assert(new_data != null);
|
|
|
|
str->data = new_data;
|
|
str->cap = new_cap;
|
|
}
|
|
|
|
smcc_memcpy(str->data + str->size - 1, data, len);
|
|
str->size += len;
|
|
str->data[str->size - 1] = '\0'; // 保证 C 字符串兼容性
|
|
}
|
|
|
|
/**
|
|
* 向字符串追加单个字符
|
|
*/
|
|
static inline void cstring_push(cstring_t *str, char ch) {
|
|
cstring_push_cstr(str, &ch, 1);
|
|
}
|
|
|
|
/**
|
|
* 获取字符串长度
|
|
*/
|
|
static inline usize cstring_len(const cstring_t *str) {
|
|
return str ? str->size - 1 : 0;
|
|
}
|
|
|
|
/**
|
|
* 检查字符串是否为空
|
|
*/
|
|
static inline cbool cstring_is_empty(const cstring_t *str) {
|
|
return str == null || str->size == 0;
|
|
}
|
|
|
|
/**
|
|
* 清空字符串内容但保留分配的内存
|
|
*/
|
|
static inline void cstring_clear(cstring_t *str) {
|
|
if (str) {
|
|
str->size = 1;
|
|
if (str->data) {
|
|
str->data[0] = '\0';
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 获取 C 风格字符串
|
|
*/
|
|
static inline char *cstring_as_cstr(const cstring_t *str) {
|
|
if (str == null || str->data == null) {
|
|
return "";
|
|
}
|
|
return str->data;
|
|
}
|
|
|
|
#endif /* __CORE_STR_H__ */
|