summaryrefslogtreecommitdiff
path: root/controller/unzbuffer.c
blob: 6578e616deeef50139d5815efd351626b96e1554 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include <stdio.h>
#include <assert.h>
#include <zlib.h>
#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;
}