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