Home | History | Annotate | Line # | Download | only in sort
fsort.c revision 1.1
      1 /*-
      2  * Copyright (c) 1993
      3  *	The Regents of the University of California.  All rights reserved.
      4  *
      5  * This code is derived from software contributed to Berkeley by
      6  * Peter McIlroy.
      7  *
      8  * Redistribution and use in source and binary forms, with or without
      9  * modification, are permitted provided that the following conditions
     10  * are met:
     11  * 1. Redistributions of source code must retain the above copyright
     12  *    notice, this list of conditions and the following disclaimer.
     13  * 2. Redistributions in binary form must reproduce the above copyright
     14  *    notice, this list of conditions and the following disclaimer in the
     15  *    documentation and/or other materials provided with the distribution.
     16  * 3. All advertising materials mentioning features or use of this software
     17  *    must display the following acknowledgement:
     18  *	This product includes software developed by the University of
     19  *	California, Berkeley and its contributors.
     20  * 4. Neither the name of the University nor the names of its contributors
     21  *    may be used to endorse or promote products derived from this software
     22  *    without specific prior written permission.
     23  *
     24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     34  * SUCH DAMAGE.
     35  */
     36 
     37 #ifndef lint
     38 static char sccsid[] = "@(#)fsort.c	8.1 (Berkeley) 6/6/93";
     39 #endif /* not lint */
     40 
     41 /*
     42  * Read in the next bin.  If it fits in one segment sort it;
     43  * otherwise refine it by segment deeper by one character,
     44  * and try again on smaller bins.  Sort the final bin at this level
     45  * of recursion to keep the head of fstack at 0.
     46  * After PANIC passes, abort to merge sort.
     47 */
     48 #include "sort.h"
     49 #include "fsort.h"
     50 
     51 #include <stdlib.h>
     52 #include <string.h>
     53 
     54 u_char **keylist = 0, *buffer = 0, *linebuf = 0;
     55 struct tempfile fstack[MAXFCT];
     56 extern char *toutpath;
     57 #define FSORTMAX 4
     58 int PANIC = FSORTMAX;
     59 
     60 void
     61 fsort(binno, depth, infiles, nfiles, outfd, ftbl)
     62 	register int binno, depth, nfiles;
     63 	register union f_handle infiles;
     64 	FILE *outfd;
     65 	register struct field *ftbl;
     66 {
     67 	register u_char *bufend, **keypos, *tmpbuf;
     68 	u_char *weights;
     69 	int ntfiles, mfct = 0, total, i, maxb, lastb, panic = 0;
     70 	register int c, nelem;
     71 	long sizes [NBINS+1];
     72 	union f_handle tfiles, mstart = {MAXFCT-16};
     73 	register int (*get)(int, union f_handle, int, RECHEADER *,
     74 		u_char *, struct field *);
     75 	register struct recheader *crec;
     76 	struct field tfield[2];
     77 	FILE *prevfd, *tailfd[FSORTMAX+1];
     78 
     79 	memset(tailfd, 0, sizeof(tailfd));
     80 	prevfd = outfd;
     81 	memset(tfield, 0, sizeof(tfield));
     82 	if (ftbl[0].flags & R)
     83 		tfield[0].weights = Rascii;
     84 	else
     85 		tfield[0].weights = ascii;
     86 	tfield[0].icol.num = 1;
     87 	weights = ftbl[0].weights;
     88 	if (!buffer) {
     89 		buffer = malloc(BUFSIZE);
     90 		keylist = malloc(MAXNUM * sizeof(u_char *));
     91 		if (!SINGL_FLD)
     92 			linebuf = malloc(MAXLLEN);
     93 	}
     94 	bufend = buffer + BUFSIZE;
     95 	if (binno >= 0) {
     96 		tfiles.top = infiles.top + nfiles;
     97 		get = getnext;
     98 	} else {
     99 		tfiles.top = 0;
    100 		if (SINGL_FLD)
    101 			get = makeline;
    102 		else
    103 			get = makekey;
    104 	}
    105 	for (;;) {
    106 		memset(sizes, 0, sizeof(sizes));
    107 		c = ntfiles = 0;
    108 		if (binno == weights[REC_D] &&
    109 		    !(SINGL_FLD && ftbl[0].flags & F)) {	/* pop */
    110 			rd_append(weights[REC_D],
    111 			    infiles, nfiles, prevfd, buffer, bufend);
    112 			break;
    113 		} else if (binno == weights[REC_D]) {
    114 			depth = 0;		/* start over on flat weights */
    115 			ftbl = tfield;
    116 			weights = ftbl[0].weights;
    117 		}
    118 		while (c != EOF) {
    119 			keypos = keylist;
    120 			nelem = 0;
    121 			crec = (RECHEADER *) buffer;
    122 			while((c = get(binno, infiles, nfiles, crec, bufend,
    123 			    ftbl)) == 0) {
    124 				*keypos++ = crec->data + depth;
    125 				if (++nelem == MAXNUM) {
    126 					c = BUFFEND;
    127 					break;
    128 				}
    129 				crec =(RECHEADER *)	((char *) crec +
    130 				SALIGN(crec->length) + sizeof(TRECHEADER));
    131 			}
    132 			if (c == BUFFEND || ntfiles || mfct) {	/* push */
    133 				if (panic >= PANIC) {
    134 					fstack[MAXFCT-16+mfct].fd = ftmp();
    135 					if (radixsort(keylist, nelem, weights,
    136 					    REC_D))
    137 						err(2, NULL);
    138 					append(keylist, nelem, depth, fstack[
    139 					 MAXFCT-16+mfct].fd, putrec, ftbl);
    140 					mfct++;
    141 					/* reduce number of open files */
    142 					if (mfct == 16 ||(c == EOF && ntfiles)) {
    143 						tmpbuf = malloc(bufend -
    144 						    crec->data);
    145 						memmove(tmpbuf, crec->data,
    146 						    bufend - crec->data);
    147 						fstack[tfiles.top + ntfiles].fd
    148 						    = ftmp();
    149 						fmerge(0, mstart, mfct, geteasy,
    150 						  fstack[tfiles.top+ntfiles].fd,
    151 						  putrec, ftbl);
    152 						++ntfiles;
    153 						mfct = 0;
    154 						memmove(crec->data, tmpbuf,
    155 						    bufend - crec->data);
    156 						free(tmpbuf);
    157 					}
    158 				} else {
    159 					fstack[tfiles.top + ntfiles].fd= ftmp();
    160 					onepass(keylist, depth, nelem, sizes,
    161 					weights, fstack[tfiles.top+ntfiles].fd);
    162 					++ntfiles;
    163 				}
    164 			}
    165 		}
    166 		get = getnext;
    167 		if (!ntfiles && !mfct) {	/* everything in memory--pop */
    168 			if (nelem > 1)
    169 			   if (radixsort(keylist, nelem, weights, REC_D))
    170 				err(2, NULL);
    171 			append(keylist, nelem, depth, outfd, putline, ftbl);
    172 			break;					/* pop */
    173 		}
    174 		if (panic >= PANIC) {
    175 			if (!ntfiles)
    176 				fmerge(0, mstart, mfct, geteasy,
    177 				    outfd, putline, ftbl);
    178 			else
    179 				fmerge(0, tfiles, ntfiles, geteasy,
    180 				    outfd, putline, ftbl);
    181 			break;
    182 
    183 		}
    184 		total = maxb = lastb = 0;	/* find if one bin dominates */
    185 		for (i = 0; i < NBINS; i++)
    186 		  if (sizes[i]) {
    187 			if (sizes[i] > sizes[maxb])
    188 				maxb = i;
    189 			lastb = i;
    190 			total += sizes[i];
    191 		}
    192 		if (sizes[maxb] < max((total / 2) , BUFSIZE))
    193 			maxb = lastb;	/* otherwise pop after last bin */
    194 		fstack[tfiles.top].lastb = lastb;
    195 		fstack[tfiles.top].maxb = maxb;
    196 
    197 			/* start refining next level. */
    198 		get(-1, tfiles, ntfiles, crec, bufend, 0);	/* rewind */
    199 		for (i = 0; i < maxb; i++) {
    200 			if (!sizes[i])	/* bin empty; step ahead file offset */
    201 				get(i, tfiles, ntfiles, crec, bufend, 0);
    202 			else
    203 				fsort(i, depth+1, tfiles, ntfiles, outfd, ftbl);
    204 		}
    205 		if (lastb != maxb) {
    206 			if (prevfd != outfd)
    207 				tailfd[panic] = prevfd;
    208 			prevfd = ftmp();
    209 			for (i = maxb+1; i <= lastb; i++)
    210 				if (!sizes[i])
    211 					get(i, tfiles, ntfiles, crec, bufend,0);
    212 				else
    213 					fsort(i, depth+1, tfiles, ntfiles,
    214 					    prevfd, ftbl);
    215 		}
    216 
    217 		/* sort biggest (or last) bin at this level */
    218 		depth++;
    219 		panic++;
    220 		binno = maxb;
    221 		infiles.top = tfiles.top;	/* getnext will free tfiles, */
    222 		nfiles = ntfiles;		/* so overwrite them */
    223 	}
    224 	if (prevfd != outfd) {
    225 		concat(outfd, prevfd);
    226 		fclose(prevfd);
    227 	}
    228 	for (i = panic; i >= 0; --i)
    229 		if (tailfd[i]) {
    230 			concat(outfd, tailfd[i]);
    231 			fclose(tailfd[i]);
    232 		}
    233 }
    234 
    235 /*
    236  This is one pass of radix exchange, dumping the bins to disk.
    237  */
    238 #define swap(a, b, t) t = a, a = b, b = t
    239 void
    240 onepass(a, depth, n, sizes, tr, fd)
    241 	u_char **a;
    242 	int depth;
    243 	long n, sizes[];
    244 	u_char *tr;
    245 	FILE *fd;
    246 {
    247 	long tsizes[NBINS+1];
    248 	u_char **bin[257], **top[256], ***bp, ***bpmax, ***tp;
    249 	static histo[256];
    250 	int *hp;
    251 	register int c;
    252 	u_char **an, *t, **aj;
    253 	register u_char **ak, *r;
    254 
    255 	memset(tsizes, 0, sizeof(tsizes));
    256 	depth += sizeof(TRECHEADER);
    257 	an = a + n;
    258 	for (ak = a; ak < an; ak++) {
    259 		histo[c = tr[**ak]]++;
    260 		tsizes[c] += ((RECHEADER *) (*ak -= depth))->length;
    261 	}
    262 
    263 	bin[0] = a;
    264 	bpmax = bin + 256;
    265 	tp = top, hp = histo;
    266 	for (bp = bin; bp < bpmax; bp++) {
    267 		*tp++ = *(bp+1) = *bp + (c = *hp);
    268 		*hp++ = 0;
    269 		if (c <= 1)
    270 			continue;
    271 	}
    272 	for(aj = a; aj < an; *aj = r, aj = bin[c+1])
    273 		for(r = *aj; aj < (ak = --top[c = tr[r[depth]]]) ;)
    274 			swap(*ak, r, t);
    275 
    276 	for (ak = a, c = 0; c < 256; c++) {
    277 		an = bin[c+1];
    278 		n = an - ak;
    279 		tsizes[c] += n * sizeof(TRECHEADER);
    280 		/* tell getnext how many elements in this bin, this segment. */
    281 		EWRITE(tsizes+c, sizeof(long), 1, fd);
    282 		sizes[c] += tsizes[c];
    283 		for (; ak < an; ++ak)
    284 			putrec((RECHEADER *) *ak, fd);
    285 	}
    286 }
    287