#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "../public/nsapi.h"
#include "io.h"
#define NETBUF_RDTIMEOUT 120
NSAPI_PUBLIC netbuf *netbuf_open(
SYS_NETFD sd,
int sz) {
netbuf *buf = (netbuf *) malloc(
sizeof(netbuf));
buf->rdtimeout =
NETBUF_RDTIMEOUT;
buf->pos = sz;
buf->cursize = sz;
buf->maxsize = sz;
buf->sd = sd;
buf->inbuf =
NULL;
buf->errmsg =
NULL;
return buf;
}
NSAPI_PUBLIC void netbuf_close(netbuf *buf) {
if(buf->inbuf)
free(buf->inbuf);
free(buf);
}
NSAPI_PUBLIC unsigned char * netbuf_replace(netbuf *buf,
unsigned char *inbuf,
int pos,
int cursize,
int maxsize)
{
unsigned char *oldbuf = buf->inbuf;
buf->inbuf = inbuf;
buf->pos = pos;
buf->cursize = cursize;
buf->maxsize = maxsize;
return oldbuf;
}
NSAPI_PUBLIC int netbuf_next(netbuf *buf,
int advance) {
int n;
if(!buf->inbuf)
buf->inbuf = (
unsigned char *) malloc(buf->maxsize);
while(
1) {
switch(n = net_read(buf->sd, (
char *)(buf->inbuf), buf->maxsize)) {
case 0:
return IO_EOF;
case -
1:
return IO_ERROR;
default:
buf->pos = advance;
buf->cursize = n;
return buf->inbuf[
0];
}
}
}
NSAPI_PUBLIC int netbuf_getbytes(netbuf *buf,
char *buffer,
int size)
{
int bytes;
if (!buf->inbuf) {
buf->inbuf = (
unsigned char *) malloc(buf->maxsize);
}
else {
if (buf->pos < buf->cursize) {
int bytes_in_buffer = buf->cursize - buf->pos;
if (bytes_in_buffer > size)
bytes_in_buffer = size;
memcpy(buffer, &(buf->inbuf[buf->pos]), bytes_in_buffer);
buf->pos += bytes_in_buffer;
return bytes_in_buffer;
}
}
if(!buf->sd) {
return NETBUF_EOF;
}
bytes = net_read(buf->sd, buffer, size);
if (bytes ==
0)
return NETBUF_EOF;
if (bytes <
0) {
return NETBUF_ERROR;
}
return bytes;
}
NSAPI_PUBLIC int netbuf_grab(netbuf *buf,
int sz) {
int n;
if(!buf->inbuf) {
buf->inbuf = (
unsigned char *) malloc(sz);
buf->maxsize = sz;
}
else if(sz > buf->maxsize) {
buf->inbuf = (
unsigned char *) realloc(buf->inbuf, sz);
buf->maxsize = sz;
}
buf->pos =
0;
buf->cursize =
0;
while(
1) {
switch(n = net_read(buf->sd, (
char *)(buf->inbuf), sz)) {
case 0:
return IO_EOF;
case -
1: {
return IO_ERROR;
}
default:
buf->cursize = n;
return n;
}
}
}