#include #include #include #include "unzbuffer.h" #define BUFSZ_ZOUT (256*1024) struct unzbuffer { u8 *out; i64 outfill; z_stream strm; bool just_resetted; unzbuffer_writefunc *wf; void *payload; }; struct unzbuffer* unzbuffer_init(unzbuffer_writefunc *wf,void *payload){ struct unzbuffer *z=malloc(1,struct unzbuffer); z->out=malloc(BUFSZ_ZOUT,u8); z->outfill=0; z->strm.zalloc=Z_NULL; z->strm.zfree=Z_NULL; z->strm.opaque=Z_NULL; z->strm.avail_in=0; z->strm.next_in=Z_NULL; // so unzbuffer_write can start writing immediately z->strm.avail_out=BUFSZ_ZOUT; z->strm.next_out=z->out; if(inflateInit(&z->strm)!=Z_OK){ return NULL; } z->just_resetted=true; z->wf=wf; z->payload=payload; return z; } bool unzbuffer_write(struct unzbuffer *z,u8 *data,i64 len){ z->just_resetted=false; z->strm.avail_in=len; z->strm.next_in=data; assert(z->strm.avail_out>0); while(true){ int ret=inflate(&z->strm,Z_NO_FLUSH); if(ret!=Z_OK&&ret!=Z_STREAM_END){ inflateEnd(&z->strm); fprintf(stderr,"unz error: %d\n",ret); return false; } if(ret!=Z_STREAM_END&&z->strm.avail_out>0)break; z->wf(z->out,BUFSZ_ZOUT-z->strm.avail_out,z->payload); if(ret==Z_STREAM_END){ inflateReset(&z->strm); z->strm.avail_in=0; z->strm.next_in=Z_NULL; z->strm.avail_out=BUFSZ_ZOUT; z->strm.next_out=z->out; z->just_resetted=true; break; } z->strm.avail_out=BUFSZ_ZOUT; z->strm.next_out=z->out; } assert(z->strm.avail_in==0); return true; } bool unzbuffer_finish_destroy(struct unzbuffer *z){ if(!z->just_resetted){ assert(z->strm.avail_out>0); while(true){ int ret=inflate(&z->strm,Z_FINISH); if(ret!=Z_OK&&ret!=Z_STREAM_END){ inflateEnd(&z->strm); fprintf(stderr,"unz error: %d\n",ret); return false; } 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; } } free(z->out); free(z); return true; }