代码拉取完成,页面将自动刷新
#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;
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。