Files
cKit/Foundation/c_Array.c
T

71 lines
2.5 KiB
C
Raw Normal View History

2026-08-29 01:50:50 +08:00
#include <c_Array.h>
2026-08-30 01:48:03 +08:00
c_err_t c_Array_Init(c_Array_t* self, c_size_t item_size, c_size_t size, c_Allocator_t* allocator) {
if (!self || item_size == 0 || size == 0) return C_ERR_PARAM;
2026-08-29 01:50:50 +08:00
2026-08-30 01:48:03 +08:00
// 内部绑定:如果传入 NULL,无缝降级为系统默认分配器
self->allocator = (allocator != NULL) ? *allocator : c_DefaultAllocator;
self->item_size = item_size;
self->size = size;
// 通过内部绑定的分配器,一次性开辟完全密集且等长的字节存储空间
self->array = c_Allocator_Alloc(&self->allocator, self->size * self->item_size);
if (!self->array) return C_ERR_NOMEM;
// 默认执行干净抹零
memset(self->array, 0, self->size * self->item_size);
return C_ERR_OK;
}
// 销毁固定数组资源
void c_Array_Destroy(c_Array_t* self) {
if (!self) return;
if (self->array) {
c_Allocator_Free(&self->allocator, self->array);
self->array = NULL;
2026-08-29 01:50:50 +08:00
}
2026-08-30 01:48:03 +08:00
self->size = 0;
}
// 定点安全写入 (深度值复制)
c_err_t c_Array_Write(c_Array_t* self, c_size_t index, const void* item) {
// 强御级边界防御:拦截一切非法越界或空域写入
if (!self || !item || index >= self->size) return C_ERR_PARAM;
// 计算精准的物理坑位物理地址并执行覆写
char* target = (char*)self->array + (index * self->item_size);
memcpy(target, item, self->item_size);
2026-08-29 01:50:50 +08:00
return C_ERR_OK;
}
2026-08-30 01:48:03 +08:00
// 定点安全读取 (安全拷出副本)
c_err_t c_Array_Read(const c_Array_t* self, c_size_t index, void* out_item) {
if (!self || !out_item || index >= self->size) return C_ERR_PARAM;
2026-08-29 01:50:50 +08:00
2026-08-30 01:48:03 +08:00
const char* source = (const char*)self->array + (index * self->item_size);
memcpy(out_item, source, self->item_size);
2026-08-29 01:50:50 +08:00
return C_ERR_OK;
}
2026-08-30 01:48:03 +08:00
// 只读原位窥探指针 (注意:因为大小固定,该指针在数组生命周期内绝对不可变、不跑飞,极度安全)
void* c_Array_Get(const c_Array_t* self, c_size_t index) {
if (!self || index >= self->size) return NULL;
return (char*)self->array + (index * self->item_size);
}
// 全局高速批量刷值填充 (常用于初始化状态、重置音频轨等)
c_err_t c_Array_Fill(c_Array_t* self, const void* item) {
if (!self || !item) return C_ERR_PARAM;
// 利用连续线性空间的特点,高速循环平铺拷贝
char* target = (char*)self->array;
for (c_size_t i = 0; i < self->size; i++) {
memcpy(target, item, self->item_size);
target += self->item_size;
}
2026-08-29 01:50:50 +08:00
return C_ERR_OK;
}