#include #include #include #include "zbuffer.h" #define BUFSZ_ZOUT (256*1024) struct zbuffer { u8 *out; i64 outfill; z_stream strm; zbuffer_writefunc *wf; void *payload; }; struct zbuffer* zbuffer_init(zbuffer_writefunc *wf,void *payload){ struct zbuffer *z=malloc(1,struct zbuffer); z->out=malloc(BUFSZ_ZOUT,u8); z->outfill=0; z->strm.zalloc=Z_NULL; z->strm.zfree=Z_NULL; z->strm.opaque=Z_NULL; // so zbuffer_write can start writing immediately z->strm.avail_out=BUFSZ_ZOUT; z->strm.next_out=z->out; if(deflateInit(&z->strm,Z_DEFAULT_COMPRESSION)!=Z_OK){ return NULL; } z->wf=wf; z->payload=payload; return z; } void zbuffer_write(struct zbuffer *z,u8 *data,i64 len){ z->strm.avail_in=len; z->strm.next_in=data; assert(z->strm.avail_out>0); while(true){ int ret=deflate(&z->strm,Z_NO_FLUSH); assert(ret==Z_OK); if(z->strm.avail_out>0)break; z->wf(z->out,BUFSZ_ZOUT,z->payload); z->strm.avail_out=BUFSZ_ZOUT; z->strm.next_out=z->out; } // fprintf(stderr,"zbuffer_write: avail_out = %d\n",z->strm.avail_out); assert(z->strm.avail_in==0); } void zbuffer_flush(struct zbuffer *z){ assert(z->strm.avail_out>0); while(true){ int ret=deflate(&z->strm,Z_SYNC_FLUSH); assert(ret==Z_OK); z->wf(z->out,BUFSZ_ZOUT-z->strm.avail_out,z->payload); bool done=z->strm.avail_out>0; z->strm.avail_out=BUFSZ_ZOUT; z->strm.next_out=z->out; if(done)break; } } void zbuffer_finish_destroy(struct zbuffer *z){ assert(z->strm.avail_out>0); while(true){ int ret=deflate(&z->strm,Z_FINISH); assert(ret==Z_OK||ret==Z_STREAM_END); z->wf(z->out,BUFSZ_ZOUT-z->strm.avail_out,z->payload); if(z->strm.avail_out>0)break; z->strm.avail_out=BUFSZ_ZOUT; z->strm.next_out=z->out; } deflateEnd(&z->strm); free(z->out); free(z); }