Files
sics/tecs/buf.c
2000-03-20 07:38:12 +00:00

185 lines
3.1 KiB
C

#include <math.h>
#include <string.h>
#include <strings.h>
#include <stdlib.h>
#include "buf.h"
#define TWO28 268435456.0
#define MAXINT 2147483647
int buf_encode_int(char b[4]) {
int i;
i=(unsigned char)b[0];
if (i>=128) i=i-256;
i=i*256+(unsigned char)b[1];
i=i*256+(unsigned char)b[2];
i=i*256+(unsigned char)b[3];
return(i);
}
void buf_decode_int(char b[4], int i) {
if (i<0) {
i+=0x10000000;
b[0]=i/0x01000000+128;
i=i % 0x01000000;
} else {
b[0]=i/0x01000000;
i=i % 0x01000000;
}
b[1]=i/0x10000; i=i % 0x10000;
b[2]=i/0x100;
b[3]=i % 0x100;
}
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=buf_encode_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=buf_encode_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; }
buf_decode_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;
buf_decode_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);
}