i += buf[j];
}
- // check whether invalid length/message given
- if((i==0)&&(buf[4]==0xff)) { return -1; }
-
return i+4;
}
#include<net.h>
int net_peek(struct peer *info, void *p, size_t size) {
- void *next;
+ int i;
if(NULL==info) { return -1; }
if(NULL==p) { return -1; }
if(0==size) { return 0; }
- next = malloc(size);
- if(NULL==next) { return -1; }
-
- if(net_wait(info,next,size)<0) { return -1; }
- if(info->in!=NULL) {
- /*
- * incomplete net_wait; p wasn't filled
- */
- free(next);
+ if((i = net_wait(info,p,size))<=0) {
+ if(i<0) { return -1; }
return 0;
}
- if(0==info->in_size) { return 0; }
-
- info->in = next;
- info->in_size = size;
-
- memcpy(p,next,size);
+ if(net_cache(
+ &(info->in), /* void **prev */
+ &(info->in_size), /* size_t *prev_size */
+ p, /* void *p */
+ size /* size_t size */
+ )<0) { return -1; }
return 1;
}
/* use up all cached data */
memcpy(p,info->in,info->in_size);
free(info->in);
- info->in = NULL;
(*size) -= info->in_size;
p += info->in_size;
+
+ info->in = NULL;
+ info->in_size = 0;
}
}
assert(info->in!=NULL);
assert(info->in_size==5);
assert(memcmp(info->in,expected,5)==0);
+
for(size_t i=0;i<5;i++) {
- assert(buf[i]==0);
+ assert(buf[i]==1);
+ assert(buf[i+5]==0);
}
- free(info->in);
- info->in = NULL;
assert(5==write(write_sock,expected,5));
- assert(1==net_peek(info,buf,5));
+ assert(1==net_peek(info,&(buf[5]),5));
assert(info->in!=NULL);
assert(info->in_size==5);
assert(memcmp(info->in,expected,5)==0);
- assert(memcmp(buf,expected,5)==0);
+ assert(memcmp(buf,expected,10)==0);
free(info->in);
info->in = NULL;
+
+ peer_free(info);
+ close(read_sock);
+ close(write_sock);
}
static void net_queue_basic_test() {