| Revision 16 (by moose, 2009/04/07 03:28:53) |
fix cseproto_create_item compile error, fix warning in cseproto_add_item |
#include "cseproto/cseproto.h"
#include "cseproto/cseproto_encode.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
cseproto_t *cseproto_create(uint32_t buckets)
{
cseproto_t *cp = NULL;
if(buckets <= 0)
return NULL;
cp = calloc(1, sizeof(cseproto_t));
if(!cp)
return NULL;
cp->buckets = calloc(buckets, sizeof(cseproto_bucket_t));
if(!cp->buckets) {
free(cp);
return NULL;
}
cp->bucket_count = buckets;
cselog("LOG", "bucket_count: %i\n", cp->bucket_count);
return cp;
}
void cseproto_destroy(cseproto_t *proto)
{
if(proto->bucket_count) {
for(uint32_t i = 0; i < proto->bucket_count; ++i) {
cseproto_item_t *ptr = proto->buckets[i].head;
while(ptr) {
cseproto_item_t *next = ptr->next;
cseproto_destroy_item(ptr);
ptr = next;
}
proto->buckets[i].head = proto->buckets[i].tail = NULL;
}
}
free(proto->buckets);
free(proto);
}
cseproto_item_t *cseproto_create_item(uint32_t key, cseproto_wiretype_t wiretype, size_t len, void *data)
{
cseproto_item_t *item = NULL;
item = calloc(1, sizeof(cseproto_item_t));
if(!item)
return NULL;
item->wiretype = wiretype;
item->key = key;
item->data_len = len;
switch(wiretype) {
case CSE_WIRETYPE_SVARINT:
case CSE_WIRETYPE_VARINT:
case CSE_WIRETYPE_64BIT: // double, [su]int64_t
item->v.uint64 = *((uint64_t*)data);
break;
case CSE_WIRETYPE_32BIT: // float, [su]int32_t
item->v.uint32 = *((uint32_t*)data);
break;
case CSE_WIRETYPE_LENDELIM:
if(len <= 0) {
free(item);
return NULL;
}
item->v.data = calloc(1, len);
if(!item->v.data) {
free(item);
return NULL;
}
cselog("LOG", "len: %i", len);
memcpy(item->v.data, data, len);
break;
}
return item;
}
void cseproto_destroy_item(cseproto_item_t *item)
{
if(item->wiretype == CSE_WIRETYPE_LENDELIM) {
free(item->v.data);
item->v.uint64 = 0L;
}
free(item);
}
int cseproto_add_item(cseproto_t *proto, cseproto_item_t *item)
{
uint32_t key = item->key-1;
if(key >= proto->bucket_count)
return 0;
if(proto->buckets[key].head) {
item->next = NULL;
item->prev = proto->buckets[key].tail;
proto->buckets[key].tail->next = item;
proto->buckets[key].tail = item;
}
else {
proto->buckets[key].head = proto->buckets[key].tail = item;
item->prev = item->next = NULL;
}
return 1;
}
int cseproto_remove_item(cseproto_t *proto, cseproto_item_t *item)
{
return -1;
}
cseproto_item_t *cseproto_get_item(cseproto_t *proto, uint32_t key)
{
if(key-1 >= proto->bucket_count) {
return NULL;
}
return proto->buckets[key-1].tail;
}
cseproto_item_t *cseproto_get_item_head(cseproto_t *proto, uint32_t key)
{
if(key-1 >= proto->bucket_count) {
return NULL;
}
return proto->buckets[key-1].head;
}
cseproto_item_t *cseproto_get_item_tail(cseproto_t *proto, uint32_t key)
{
if(key-1 >= proto->bucket_count) {
return NULL;
}
return proto->buckets[key-1].tail;
}