Files
scc/runtime/libcore/include/core_vec.h
zzy a3322f0d4c feat(runtime): 添加字符串和内存操作工具函数
- 在 `core_mem.h` 中新增 `smcc_strhash32`、`smcc_strlen` 和 `smcc_strcmp` 函数,
  提供 C 字符串的哈希、长度获取和比较功能
- 完善 `core_str.h` 中 `cstring_t` 结构体及相关操作函数的注释说明
- 更新 `core_str.h` 头文件保护宏命名,增强模块标识一致性
- 修改 `core_vec.h` 文件头部保护宏名称以匹配实际文件名

另外,在 lexer 测试运行代码中引入日志相关头文件并调整日志级别设置逻辑。
2025-11-21 17:52:42 +08:00

118 lines
4.1 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* @file vec.h
* @brief 动态数组Dynamic Array实现
*
* 提供类型安全的动态数组容器实现,支持自动扩容和基本操作
*/
#ifndef __SMCC_CORE_VEC_H__
#define __SMCC_CORE_VEC_H__
#include "core_impl.h"
#include "core_type.h"
#define __vec_realloc smcc_realloc
#define __vec_free smcc_free
/** @defgroup vec_struct 数据结构定义 */
/**
* @def VEC(type)
* @brief 声明向量结构体
* @param type 存储的数据类型
*
* 生成包含size/cap/data三个字段的结构体定义
* - size: 当前元素数量
* - cap: 数组容量
* - data: 存储数组指针
* @example
* VEC(char) string; <=> char[dynamic_array] string;
* struct people { VEC(char) name; int age; VEC(struct people) children; };
*/
#define VEC(type) \
struct { \
usize size; \
usize cap; \
type *data; \
}
/** @defgroup vec_operations 动态数组操作宏 */
/**
* @def vec_init(vec)
* @brief 初始化向量结构体
* @param vec 要初始化的向量结构体变量
*
* @note 此宏不会分配内存,仅做零初始化
*/
#define vec_init(vec) \
do { \
(vec).size = 0, (vec).cap = 0, (vec).data = 0; \
} while (0)
/**
* @def vec_push(vec, value)
* @brief 添加元素到向量末尾
* @param vec 目标向量结构体
* @param value 要添加的值(需匹配存储类型)
*
* @note 当容量不足时自动扩容为2倍初始容量为4
* @warning 内存分配失败时会触发LOG_FATAL
*/
#define vec_push(vec, value) \
do { \
if (vec.size >= vec.cap) { \
int cap = vec.cap ? vec.cap * 2 : 4; \
void *data = __vec_realloc(vec.data, cap * sizeof(*vec.data)); \
if (!data) { \
LOG_FATAL("vector_push: realloc failed\n"); \
} \
(vec).cap = cap; \
(vec).data = data; \
} \
(vec).data[(vec).size++] = value; \
} while (0)
/**
* @def vec_pop(vec)
* @brief 弹出最后一个元素
* @param vec 目标向量结构体
* @return 最后元素的引用
* @warning 需确保size > 0时使用
*/
#define vec_pop(vec) ((vec).data[--(vec).size])
/**
* @def vec_at(vec, idx)
* @brief 获取指定索引元素
* @param vec 目标向量结构体
* @param idx 元素索引0 <= idx < size
* @return 对应元素的引用
*/
#define vec_at(vec, idx) (((vec).data)[idx])
/**
* @def vec_idx(vec, ptr)
* @brief 获取元素指针对应的索引
* @param vec 目标向量结构体
* @param ptr 元素指针需在data数组范围内
* @return 元素索引值
*/
#define vec_idx(vec, ptr) ((ptr) - (vec).data)
/**
* @def vec_free(vec)
* @brief 释放向量内存
* @param vec 目标向量结构体
*
* @note 释放后需重新初始化才能再次使用
*/
#define vec_free(vec) \
do { \
__vec_free((vec).data); \
(vec).data = NULL; \
(vec).size = (vec).cap = 0; \
} while (0)
#endif // __SMCC_CORE_VEC_H__