Files
scc/runtime/libcore/include/core_vec.h
zzy d88fa3b8d3 feat: rename core types to scc prefix for consistency
Updated type names from `core_*` to `scc_*` across lex_parser and stream modules to maintain naming consistency within the SCC codebase. This includes changes to function signatures and internal usage of types like `core_probe_stream_t`, `core_pos_t`, and `cstring_t` to their `scc_*` counterparts.
2025-12-11 13:00:29 +08:00

121 lines
4.4 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 __SCC_CORE_VEC_H__
#define __SCC_CORE_VEC_H__
#include "core_impl.h"
#include "core_type.h"
#define __scc_vec_realloc scc_realloc
#define __scc_vec_free scc_free
/** @defgroup vec_struct 数据结构定义 */
/**
* @def SCC_VEC(type)
* @brief 声明向量结构体
* @param type 存储的数据类型
*
* 生成包含size/cap/data三个字段的结构体定义
* - size: 当前元素数量
* - cap: 数组容量
* - data: 存储数组指针
* @example
* SCC_VEC(char) string; <=> char[dynamic_array] string;
* struct people { SCC_VEC(char) name; int age; SCC_VEC(struct people) children;
* };
*/
#define SCC_VEC(type) \
struct { \
usize size; \
usize cap; \
type *data; \
}
/** @defgroup vec_operations 动态数组操作宏 */
/**
* @def scc_vec_init(vec)
* @brief 初始化向量结构体
* @param vec 要初始化的向量结构体变量
*
* @note 此宏不会分配内存,仅做零初始化
*/
#define scc_vec_init(vec) \
do { \
(vec).size = 0, (vec).cap = 0, (vec).data = 0; \
} while (0)
/**
* @def scc_vec_push(vec, value)
* @brief 添加元素到向量末尾
* @param vec 目标向量结构体
* @param value 要添加的值(需匹配存储类型)
*
* @note 当容量不足时自动扩容为2倍初始容量为4
* @warning 内存分配失败时会触发LOG_FATAL
*/
#define scc_vec_push(vec, value) \
do { \
if ((vec).size >= (vec).cap) { \
int cap = (vec).cap ? (vec).cap * 2 : 4; \
void *data = \
__scc_vec_realloc((vec).data, cap * sizeof(*(vec).data)); \
if (!data) { \
LOG_FATAL("vector_push: realloc failed\n"); \
} \
(vec).cap = cap; \
(vec).data = data; \
} \
Assert((vec).data != null); \
(vec).data[(vec).size++] = value; \
} while (0)
/**
* @def scc_vec_pop(vec)
* @brief 弹出最后一个元素
* @param vec 目标向量结构体
* @return 最后元素的引用
* @warning 需确保size > 0时使用
*/
#define scc_vec_pop(vec) ((vec).data[--(vec).size])
/**
* @def scc_vec_at(vec, idx)
* @brief 获取指定索引元素
* @param vec 目标向量结构体
* @param idx 元素索引0 <= idx < size
* @return 对应元素的引用
*/
#define scc_vec_at(vec, idx) (((vec).data)[idx])
/**
* @def scc_vec_idx(vec, ptr)
* @brief 获取元素指针对应的索引
* @param vec 目标向量结构体
* @param ptr 元素指针需在data数组范围内
* @return 元素索引值
*/
#define scc_vec_idx(vec, ptr) ((ptr) - (vec).data)
/**
* @def scc_vec_free(vec)
* @brief 释放向量内存
* @param vec 目标向量结构体
*
* @note 释放后需重新初始化才能再次使用
*/
#define scc_vec_free(vec) \
do { \
__scc_vec_free((vec).data); \
(vec).data = NULL; \
(vec).size = (vec).cap = 0; \
} while (0)
#endif /* __SCC_CORE_VEC_H__ */