#include "fontmisc.h"
#include <bufio.h>
#include <zlib.h>
typedef struct _xzip_buf {
z_stream z;
int zstat;
BufChar b[BUFFILESIZE];
BufChar b_in[BUFFILESIZE];
BufFilePtr f;
} xzip_buf;
static int BufZipFileClose ( BufFilePtr f, int flag );
static int BufZipFileFill ( BufFilePtr f );
static int BufZipFileSkip ( BufFilePtr f, int c );
static int BufCheckZipHeader ( BufFilePtr f );
BufFilePtr
BufFilePushZIP (BufFilePtr f)
{
xzip_buf *x;
x = (xzip_buf *) xalloc (sizeof (xzip_buf));
if (!x) return 0;
x->z.zalloc = Z_NULL;
x->z.zfree = Z_NULL;
x->z.opaque = Z_NULL;
x->f = f;
x->z.next_in = Z_NULL;
x->z.next_out = Z_NULL;
x->z.avail_in = x->z.avail_out = 0;
x->zstat = inflateInit2(&(x->z), -MAX_WBITS);
if (x->zstat != Z_OK) {
xfree(x);
return 0;
}
x->z.next_out = x->b;
x->z.avail_out = BUFFILESIZE;
x->z.next_out = x->b_in;
x->z.avail_in = 0;
if (BufCheckZipHeader(x->f)) {
xfree(x);
return 0;
}
return BufFileCreate((char *)x,
BufZipFileFill,
0,
BufZipFileSkip,
BufZipFileClose);
}
static int
BufZipFileClose(BufFilePtr f, int flag)
{
xzip_buf *x = (xzip_buf *)f->private;
inflateEnd (&(x->z));
BufFileClose (x->f, flag);
xfree (x);
return 1;
}
static int
BufZipFileFill (BufFilePtr f)
{
xzip_buf *x = (xzip_buf *)f->private;
if (f->left >= 0) {
f->left--;
return *(f->bufp++);
}
switch (x->zstat) {
case Z_OK:
break;
case Z_STREAM_END:
case Z_DATA_ERROR:
case Z_ERRNO:
f->left = 0;
return BUFFILEEOF;
default:
return BUFFILEEOF;
}
x->z.next_out = x->b;
x->z.avail_out = BUFFILESIZE;
while (x->z.avail_out > 0) {
if (x->z.avail_in == 0) {
int i, c;
for (i = 0; i < sizeof(x->b_in); i++) {
c = BufFileGet(x->f);
if (c == BUFFILEEOF) break;
x->b_in[i] = c;
}
x->z.avail_in += i;
x->z.next_in = x->b_in;
}
x->zstat = inflate(&(x->z), Z_NO_FLUSH);
if (x->zstat == Z_STREAM_END) {
break;
}
if (x->zstat != Z_OK) {
break;
}
}
f->bufp = x->b;
f->left = BUFFILESIZE - x->z.avail_out;
if (f->left >= 0) {
f->left--;
return *(f->bufp++);
} else {
return BUFFILEEOF;
}
}
static int
BufZipFileSkip (BufFilePtr f, int c)
{
int retval = c;
while(c--) {
int get = BufFileGet(f);
if (get == BUFFILEEOF) return get;
}
return retval;
}
#define ASCII_FLAG 0x01
#define HEAD_CRC 0x02
#define EXTRA_FIELD 0x04
#define ORIG_NAME 0x08
#define COMMENT 0x10
#define RESERVED 0xE0
#define GET(f) do {c = BufFileGet(f); if (c == BUFFILEEOF) return c;} while(0)
static int
BufCheckZipHeader(BufFilePtr f)
{
int c, flags;
GET(f); if (c != 0x1f) return 1;
GET(f); if (c != 0x8b) return 2;
GET(f); if (c != Z_DEFLATED) return 3;
GET(f); if (c & RESERVED) return 4;
flags = c;
GET(f); GET(f); GET(f); GET(f);
GET(f);
GET(f);
if (flags & EXTRA_FIELD) {
int len;
GET(f); len = c;
GET(f); len += (c<<8);
while (len-- >= 0) {
GET(f);
}
}
if (flags & ORIG_NAME) {
do { GET(f); } while (c != 0);
}
if (flags & COMMENT) {
do { GET(f); } while (c != 0);
}
if (flags & HEAD_CRC) {
GET(f); GET(f);
}
return 0;
}