Files

95 lines
3.5 KiB
C
Raw Permalink Normal View History

2026-08-10 01:21:15 +08:00
#include "c_HashSet.h"
#include <stdlib.h>
#include <stdio.h>
typedef struct {
char ip_address[17];
} IpAddress_t;
// 簡單字串雜湊回呼 (DJB2)
uint32_t hash_ip(const void* key, int key_size) {
const char* str = ((IpAddress_t*)key)->ip_address;
uint32_t hash = 5381;
int c;
while ((c = (unsigned char)*str++)) hash = ((hash << 5) + hash) + c;
return hash;
}
int compare_ip(const void* a, const void* b, int key_size) {
return strcmp(((IpAddress_t*)a)->ip_address, ((IpAddress_t*)b)->ip_address);
}
void test_log(const char* name) {
printf("[PASS] %s\n", name);
}
int main() {
printf("==================================================\n");
printf(" 開始執行 c_HashSet_t 唯一性集合組件單元測試\n");
printf("==================================================\n\n");
c_HashSet_t ip_blacklist;
c_err_t err = c_HashSet_Init(&ip_blacklist, sizeof(IpAddress_t), 4, hash_ip, compare_ip);
assert(err == C_ERR_SUCCESS);
assert(c_HashSet_GetSize(&ip_blacklist) == 0);
test_log("1. 集合容器架構初始化成功");
IpAddress_t ip1 = {"192.168.1.1"};
IpAddress_t ip2 = {"10.0.0.1"};
IpAddress_t ip3 = {"172.16.0.1"};
// ==========================================
// 2. 測試元素新增與唯一性驗證 (Add)
// ==========================================
c_HashSet_Add(&ip_blacklist, &ip1);
c_HashSet_Add(&ip_blacklist, &ip2);
err = c_HashSet_Add(&ip_blacklist, &ip3);
assert(err == C_ERR_SUCCESS);
assert(c_HashSet_GetSize(&ip_blacklist) == 3);
// 核心斷言:重複新增相同的 IP 必須被攔截並回傳 C_ERR_ALREADY_EXISTS
assert(c_HashSet_Add(&ip_blacklist, &ip1) == C_ERR_ALREADY_EXISTS);
assert(c_HashSet_GetSize(&ip_blacklist) == 3); // 大小依然要是 3
test_log("2. 元素值複製推入與重複唯一性攔截驗證成功");
// ==========================================
// 3. 測試成員包含判斷 (Contains)
// ==========================================
assert(c_HashSet_Contains(&ip_blacklist, &ip1) == C_TRUE);
IpAddress_t safe_ip = {"8.8.8.8"};
assert(c_HashSet_Contains(&ip_blacklist, &safe_ip) == C_FALSE);
test_log("3. O(1) 集合成員包含度 (Contains) 檢索成功");
// ==========================================
// 4. 測試集合迭代器走訪與安全刪除 (Remove "10.0.0.1")
// ==========================================
c_HashSetIter_t iter;
c_HashSetIter_Init(&iter, &ip_blacklist);
printf("當前黑名單集合包含:\n");
while (c_HashSetIter_HasNext(&iter)) {
IpAddress_t* current_ip = (IpAddress_t*)c_HashSetIter_Get(&iter);
printf(" - IP: %s\n", current_ip->ip_address);
if (strcmp(current_ip->ip_address, "10.0.0.1") == 0) {
c_HashSetIter_Remove(&iter); // 在走訪期間從集合中安全剔除
printf(" [Log] 已透過迭代器將 10.0.0.1 從集合中移除\n");
} else {
c_HashSetIter_Next(&iter);
}
}
assert(c_HashSet_GetSize(&ip_blacklist) == 2);
assert(c_HashSet_Contains(&ip_blacklist, &ip2) == C_FALSE); // 10.0.0.1 應確實消失
test_log("4. 集合重定向迭代器走訪與 O(1) 安全剔除成功");
c_HashSet_Destroy(&ip_blacklist);
test_log("5. 集合控制單元資源釋放成功");
printf("\n==================================================\n");
printf(" 恭喜!基於組合模式複用的 c_HashSet_t 測試全數完美通過!\n");
printf("==================================================\n");
return 0;
}