summaryrefslogtreecommitdiff
path: root/server/zbuffer.c
blob: d65c7cc0cbb8e405bfc158479b3a7e899d2741aa (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
#include <stdio.h>
#include <assert.h>
#include <zlib.h>
#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);
}