admin 管理员组

文章数量: 1184232

rlu链表,hash, sqlite

最近看了下代码,发现挺有意思的几个地方,比如rlu链表,hash代码里借用了kernel的一些代码等。

RLU链表,如果满了的话,先删除最后链表一个元素,新增元素放入最前面

rlu((Least recently used,最近最少使用)双向链表, 增/删/替换 双向链表加:
add_host_to_lru_lst(STRU_HOST_ENTRY *host)                          --- 加至链表第一个元素host->prev_lru_host = &g_host_ctrl.host_list_head;              --- host的prev指向 headhost->next_lru_head = g_host_ctrl.host_list_head.next_lru_head; --- host的next指向 之前next headhost->next_lru_head->prev_lru_host = host;	             --- host的next 的prev指向hostg_host_ctrl.host_list_head.next_lru_head = host;         --- head的next指向host删:
remove_host_from_lru_last(STRU_HOST_ENTRY *host)             --- 删除 hosthost->prev_lru_host->next_lru_head = host->next_lru_head;--- host的前一个节点next指向host的nexthost->next_lru_head->prev_lru_host = host->prev_lru_host;--- host的后一个节点prev指向host的prev替换:
replace_host_lru(u_int8_t mac[ETH_ALEN])	--- 删掉最后一个节点,新节点插入最前面host = g_host_ctrl.last_lru_host;remove_host(host);	-->remove_host_from_lru_lastinit_host(host, mac);add_host(host);		-->add_host_to_lru_lst

hash里面取key值用了一个32 位操作系统的黄金分割系数,取结构体的地址用了container_of函数:

计算key值:
host_hash(u_int8_t mac[ETH_ALEN])hash_32(hash_in, IPT_STAT_HASH_BITNUM);u_int32_t hash = val * GOLDEN_RATIO_PRIME_32;	--- 32 位操作系统的黄金分割系数,0x9e370001UL,相乘溢出后值保存为hashreturn hash >> (32 - bits);	                    --- 保留最高的几位,出现冲突最小增:
add_host_to_hash_tbl(STRU_HOST_ENTRY *host)	hash_key = host_hash(host->mac);head = &g_host_ctrl.host_hash_tbl[hash_key];hlist_add_head(&host->host_hash_node, head);	--- 插入到第一个元素删:
remove_host_from_hash_tbl(host)hlist_del_init(&host->host_hash_node);			--- 删掉对应节点,同时prev,next置NULL查找:
find_existed_host(u_int8_t mac[ETH_ALEN])hash_key = host_hash(mac);head = &g_host_ctrl.host_hash_tbl[hash_key];hlist_for_each(_p, head)                        --- for循环,_p=head->first,_p=_p->nexthost = hlist_entry(_p, struct _STRU_HOST_ENTRY, host_hash_node);	--- container_of(ptr,type,member)#define container_of(ptr, type, member) ({			\const typeof( ((type *)0)->member ) *__mptr = (ptr);	\(type *)( (char *)__mptr - offsetof(type,member) );})#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)

然后用到了嵌入式的轻型数据库sqlite,举一个例子:

/dbsqlite3 iot_new_router.db						--- 打开 iot_new_router.db 数据库
.tab											--- 查看 table 表
select * from TABLE_DEVICE_CATEGORY;			--- 查看 TABLE_DEVICE_CATEGORY 表中所有内容

 

本文标签: rlu链表,hash sqlite