#define yypad64(n) ((8-((n)%8))%8)
+int yytbl_fwrite32 (FILE *out, uint32_t v);
+int yytbl_fwrite16 (FILE *out, uint16_t v);
+int yytbl_fwrite8 (FILE *out, uint8_t v);
+
void yytbl_hdr_init(struct yytbl_hdr *th, const char * version_str, const char *name)
{
memset(th, 0, sizeof(struct yytbl_hdr));
th->th_name = copy_string(name);
}
-int yytbl_hdr_write(FILE* fp, struct yytbl_hdr * th)
+int yytbl_hdr_fwrite(FILE* out, struct yytbl_hdr * th)
{
- uint32_t i32; /* temp variables. */
- uint16_t i16;
size_t sz,rv;
int pad,bwritten=0;
-#define WRITEORERR(val,Bsz) \
- do { i ##Bsz = htonl(val);\
- if ((rv=fwrite(&i ##Bsz, Bsz/8, 1, fp)) != (Bsz)/8)\
- return 1;\
- bwritten += rv;\
- }while(0)
-
-
- WRITEORERR(th->th_magic, 32);
- WRITEORERR(th->th_hsize, 32);
- WRITEORERR(th->th_ssize, 32);
- WRITEORERR(th->th_flags, 16);
+ if ( yytbl_fwrite32(out, th->th_magic) < 0
+ || yytbl_fwrite32(out, th->th_hsize) < 0
+ || yytbl_fwrite32(out, th->th_ssize) < 0
+ || yytbl_fwrite16(out, th->th_flags) < 0)
+ return -1;
+ else
+ bwritten += 3*4 + 2;
sz = strlen(th->th_version)+1;
- if ((rv=fwrite(th->th_version,1,sz,fp)) != sz)
- return 1;
+ if ((rv=fwrite(th->th_version,1,sz,out)) != sz)
+ return -1;
bwritten += rv;
sz = strlen(th->th_name)+1;
- if ((rv=fwrite(th->th_name,1,sz,fp)) != sz)
+ if ((rv=fwrite(th->th_name,1,sz,out)) != sz)
return 1;
bwritten += rv;
/* add padding */
pad = yypad64(bwritten) - bwritten;
- while(pad-- > 0) {
- uint8_t c =0;
- if ((rv=fwrite(&c,sizeof(uint8_t),1,fp)) != 1)
- return 1;
- bwritten++;
- }
+ while(pad-- > 0)
+ if (yytbl_fwrite8(out, 0) < 0)
+ return -1;
+ else
+ bwritten++;
/* Sanity check */
if (bwritten != th->th_hsize){
/* Oops. */
- return 1;
+ return -1;
}
- return 0;
+ return bwritten;
+}
+
+int yytbl_fwrite32(FILE *out, uint32_t v)
+{
+ uint32_t vnet;
+ size_t bytes, rv;
+
+ vnet = htonl(v);
+ bytes = sizeof(uint32_t);
+ rv = fwrite(&vnet,bytes,1,out);
+ if( rv != bytes)
+ return -1;
+ return bytes;
}
+int yytbl_fwrite16(FILE *out, uint16_t v)
+{
+ uint16_t vnet;
+ size_t bytes, rv;
+
+ vnet = htons(v);
+ bytes = sizeof(uint16_t);
+ rv = fwrite(&vnet,bytes,1,out);
+ if( rv != bytes)
+ return -1;
+ return bytes;
+}
+
+int yytbl_fwrite8(FILE *out, uint8_t v)
+{
+ size_t bytes, rv;
+
+ bytes = sizeof(uint8_t);
+ rv = fwrite(&v,bytes,1,out);
+ if( rv != bytes)
+ return -1;
+ return bytes;
+}
+
+
/* vim:set expandtab cindent tabstop=4 softtabstop=4 shiftwidth=4 textwidth=0: */