#include #include #include #include #include "buf.h" #define TWO28 268435456.0 #define MAXINT 2147483647 /* static char *null="\0"; */ int buf_get_int(buf_type *buf) { char *b; int *res; b=buf->buf; if (b==NULL) return(0); if (b[0]!=1 || buf->size<5) {buf->buf=NULL; return(0); } b++; res=(int *)b; b+=4; buf->size-=5; buf->buf=b; return(*res); } char *buf_get_str(buf_type *buf) { char *b; int l; b=buf->buf; if (b==NULL) return(""); if (b[0]==1 || b[0]==2) return(""); l=strlen(b); if (buf->size<=l) {buf->buf=NULL; return(""); } buf->buf+=l+1; buf->size-=l+1; return(b); } float buf_get_float(buf_type *buf) { char *b; float res; int *mant, iexp; b=buf->buf; if (b==NULL) return(0.0); if (b[0]!=2 || buf->size<6) { buf->buf=NULL; return(0.0); } iexp=b[1]; b+=2; mant=(int *)b; b+=4; buf->size-=6; res=(float)ldexp(*mant/TWO28, iexp); buf->buf=b; return res; } int buf_size(buf_type *buf) { if (buf->buf==NULL) return(-1); return (buf->size); } void buf_put_int(buf_type *buf, int val) { char *b; b=buf->buf; if (b==NULL) return; b[0]=1; b++; if (buf->size<=4) {buf->buf=NULL; return; } *(int *)b=val; b+=4; buf->size-=5; buf->buf=b; return; } void buf_put_str(buf_type *buf, const char *str) { char *b; int l; if (str[0]<=2 && str[0]!='\0') { buf->buf=NULL; return; }; b=buf->buf; if (b==NULL) return; l=strlen(str); if (buf->size<=l) { buf->buf=NULL; return; } strcpy(b, str); buf->buf+=l+1; buf->size-=l+1; } int buf_nint(float val) { int res; if (val<0) { if (val<-MAXINT) { return(-MAXINT); } else { return(val-0.5); } } else { if (val>MAXINT) { return(MAXINT); } else { return(val+0.5); } } } void buf_put_float(buf_type *buf, float val) { char *b; double d; int iexp; int mant; b=buf->buf; if (b==NULL) return; if (buf->size<=4) {buf->buf=NULL; return; } d=frexp((double)val, &iexp); mant=buf_nint(d*TWO28); if (iexp>127) iexp=127; if (iexp<-128) iexp=-128; b[0]=2; b[1]=iexp; b+=2; *(int *)b=mant; b+=4; buf->size-=6; buf->buf=b; } void buf_put_end(buf_type *buf) { buf->buf=buf->start; buf->usize=buf->isize-buf->size; buf->size=buf->usize; } void buf_put_start(buf_type *buf) { buf->buf=buf->start; buf->size=buf->isize; } void buf_reset(buf_type *buf) { buf->buf=buf->start; buf->size=buf->usize; } buf_type *buf_create(size_t size) { buf_type *buf; buf=malloc(sizeof(*buf)); buf->start=malloc(size); buf->isize=size; return(buf); } void buf_free(buf_type *buf) { free(buf->buf); free(buf); }