8 #define HSHIFT 3 /* HSHIFT==5 runs slightly faster, but hash table is 64x bigger */
9 #define NHASH (1<<(HSHIFT*NMATCH))
10 #define HMASK (NHASH-1)
11 #define hupdate(h, c) ((((h)<<HSHIFT)^(c))&HMASK)
12 typedef struct Hlist Hlist;
19 writememimage(int fd, Memimage *i)
21 uchar *outbuf, *outp, *eout; /* encoded data, pointer, end */
22 uchar *loutp; /* start of encoded line */
23 Hlist *hash; /* heads of hash chains of past strings */
24 Hlist *chain, *hp; /* hash chain members, pointer */
25 Hlist *cp; /* next Hlist to fall out of window */
26 int h; /* hash value */
27 uchar *line, *eline; /* input line, end pointer */
28 uchar *data, *edata; /* input buffer, end pointer */
29 u32int n; /* length of input buffer */
30 u32int nb; /* # of bytes returned by unloadimage */
31 int bpl; /* input line length */
32 int offs, runlen; /* offset, length of consumed data */
33 uchar dumpbuf[NDUMP]; /* dump accumulator */
34 int ndump; /* length of dump accumulator */
35 int miny, dy; /* y values while unloading input */
36 int ncblock; /* size of compressed blocks */
38 uchar *p, *q, *s, *es, *t;
43 bpl = bytesperline(r, i->depth);
46 ncblock = _compblocksize(r, i->depth);
47 outbuf = malloc(ncblock);
48 hash = malloc(NHASH*sizeof(Hlist));
49 chain = malloc(NMEM*sizeof(Hlist));
50 if(data == 0 || outbuf == 0 || hash == 0 || chain == 0){
58 for(miny = r.min.y; miny != r.max.y; miny += dy){
62 nb = unloadmemimage(i, Rect(r.min.x, miny, r.max.x, miny+dy),
63 data+(miny-r.min.y)*bpl, dy*bpl);
67 sprint(hdr, "compressed\n%11s %11d %11d %11d %11d ",
68 chantostr(cbuf, i->chan), r.min.x, r.min.y, r.max.x, r.max.y);
69 if(write(fd, hdr, 11+5*12) != 11+5*12)
72 eout = outbuf+ncblock;
76 memset(hash, 0, NHASH*sizeof(Hlist));
77 memset(chain, 0, NMEM*sizeof(Hlist));
81 for(n = 0; n != NMATCH; n++)
82 h = hupdate(h, line[n]);
87 for(p = line; p != eline; ){
94 for(hp = hash[h].next; hp; hp = hp->next){
118 if(eout-outp < ndump+1)
120 *outp++ = ndump-1+128;
121 memmove(outp, dumpbuf, ndump);
125 dumpbuf[ndump++] = *p;
130 if(eout-outp < ndump+1)
132 *outp++ = ndump-1+128;
133 memmove(outp, dumpbuf, ndump);
140 *outp++ = ((runlen-NMATCH)<<2) + (offs>>8);
143 for(q = p+runlen; p != q; p++){
146 cp->next = hash[h].next;
152 if(++cp == &chain[NMEM])
155 h = hupdate(h, p[NMATCH]);
159 if(eout-outp < ndump+1)
161 *outp++ = ndump-1+128;
162 memmove(outp, dumpbuf, ndump);
173 sprint(hdr, "%11d %11ld ", r.max.y, n);
174 write(fd, hdr, 2*12);
175 write(fd, outbuf, n);