1 Star 0 Fork 0

prookie01/个人播客web服务器

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
hashAddr.c 3.22 KB
一键复制 编辑 原始数据 按行查看 历史
prookie01 提交于 2023-05-15 13:40 . webServer简单的实现文件
#include"hashAddr.h"
static void reverse(char *buf,int len)
{
int i=0,j=len-1;
while(i<=j)
{
int tmp = buf[i];
buf[i] = buf[j];
buf[j] = tmp;
i++;
j--;
}
}
static void itoa(int num,char *buf,int len)
{
int idx=0;
while(num)
{
int m = num%10;
buf[idx] = m+'0';
num/=10;
idx++;
}
reverse(buf,idx);
}
static unsigned int Hash(char *str)
{
unsigned int hash =1315423911;
while(*str)
{
hash = ((hash)<<5)+(*str++)+(hash>>2);
}
return hash & 0x7FFFFFFF;
}
Node *initNode(int fd,char *ip,unsigned short port)
{
Node *p = calloc(1,sizeof(Node));
if(!p)return NULL;
p->addr = initAddr();
p->fd = fd;
p->addr->port = port;
strcpy(p->addr->ip,ip);
return p;
}
void distroyNode(Node *p)
{
if(p!=NULL)
{
free(p);
p = NULL;
}
}
hashAddr *initHashAddr(void)
{
hashAddr *Map = calloc(1,sizeof(hashAddr));
if(Map == NULL)
{
printf("mem is error!\n");
return NULL;
}
memset(Map->map,0,MAXSIZE);
return Map;
}
int createHashAddr(hashAddr *Map,Node *node)
{
if(Map == NULL || node == NULL)return -1;
char num[10]="";
itoa((node->fd),num,10);
//printf("hash:%s\n",num);
int idx = Hash(num)%MAXSIZE;
//头插
//printf("idx:%d\n",idx);
Node *phead = Map->map[idx];
node->next = phead;
Map->map[idx] = node;
//printf("create success\n");
return 0;
}
Node* hashAddrAt(hashAddr *Map,int fd)
{
if(Map == NULL || fd<0)return NULL;
char num[10]="";
itoa(fd,num,10);
int idx = Hash(num)%MAXSIZE;
Node *p = Map->map[idx];
//printf("fd:%d\n",fd);
if(p == NULL)
{
//printf("i am ok\n");
return NULL;
}
while(p)
{
if(p->fd == fd)
{
break;
}
p = p->next;
}
//printf("find ok\n");
return p;
}
bool delHashNode_fd(hashAddr *Map,int fd)
{
if(Map == NULL || fd < 0)return false;
char num[10]="";
itoa(fd,num,10);
int idx = Hash(num)%MAXSIZE;
//查找对应位置的元素
Node *p = Map->map[idx];
while(p)
{
if(p->fd == fd)
{
break;
}
p = p->next;
}
if(p == NULL)
{
return false;
}
//p指向的是待删除节点
Node *plast = Map->map[idx];
if(plast == p)
{
//头节点直接删除
Map->map[idx] = p->next;
free(p);
return true;
}
while(plast->next!=NULL && plast->next != p)
{
plast = plast->next;
}
plast->next = p->next;
free(p);
//printf("del ok\n");
return true;
}
void for_each(hashAddr *Map)
{
if(Map == NULL)return ;
for(int i=0;i<MAXSIZE;i++)
{
if(Map->map[i]!=NULL)
{
printf("----\n");
Node *p = Map->map[i];
while(p)
{
printf("fd:%d\n",Map->map[i]->fd);
printf("addr:%s port:%d\n",Map->map[i]->addr->ip,Map->map[i]->addr->port);
p = p->next;
}
}
}
}
void distroyHashAddr(hashAddr *hash)
{
if(hash!=NULL)
{
free(hash);
hash = NULL;
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C
1
https://gitee.com/prookie01/personal-podcast-web-server.git
git@gitee.com:prookie01/personal-podcast-web-server.git
prookie01
personal-podcast-web-server
个人播客web服务器
master

搜索帮助