Home | History | Annotate | Line # | Download | only in sort
fsort.c revision 1.6
      1 /*	$NetBSD: fsort.c,v 1.6 2000/10/17 15:22:57 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.6 2000/10/17 15:22:57 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 size_t bufsize, linebuf_size;
     60 struct tempfile fstack[MAXFCT];
     61 extern char *toutpath;
     62 #define FSORTMAX 4
     63 int PANIC = FSORTMAX;
     64 
     65 void
     66 fsort(binno, depth, infiles, nfiles, outfp, ftbl)
     67 	int binno, depth, nfiles;
     68 	union f_handle infiles;
     69 	FILE *outfp;
     70 	struct field *ftbl;
     71 {
     72 	const u_char **keypos;
     73 	u_char *bufend, *tmpbuf;
     74 	u_char *weights;
     75 	int ntfiles, mfct = 0, total, i, maxb, lastb, panic = 0;
     76 	int c, nelem;
     77 	long sizes [NBINS+1];
     78 	union f_handle tfiles, mstart = {MAXFCT-16};
     79 	int (*get)(int, union f_handle, int, RECHEADER *,
     80 		u_char *, struct field *);
     81 	struct recheader *crec;
     82 	struct field tfield[2];
     83 	FILE *prevfp, *tailfp[FSORTMAX+1];
     84 
     85 	memset(tailfp, 0, sizeof(tailfp));
     86 	prevfp = outfp;
     87 	memset(tfield, 0, sizeof(tfield));
     88 	if (ftbl[0].flags & R)
     89 		tfield[0].weights = Rascii;
     90 	else
     91 		tfield[0].weights = ascii;
     92 	tfield[0].icol.num = 1;
     93 	weights = ftbl[0].weights;
     94 	if (!buffer) {
     95 		bufsize = BUFSIZE;
     96 		buffer = malloc(bufsize);
     97 		keylist = malloc(MAXNUM * sizeof(u_char *));
     98 		if (!SINGL_FLD) {
     99 			linebuf_size = DEFLLEN;
    100 			linebuf = malloc(linebuf_size);
    101 		}
    102 	}
    103 	bufend = buffer + bufsize;
    104 	if (binno >= 0) {
    105 		tfiles.top = infiles.top + nfiles;
    106 		get = getnext;
    107 	} else {
    108 		tfiles.top = 0;
    109 		if (SINGL_FLD)
    110 			get = makeline;
    111 		else
    112 			get = makekey;
    113 	}
    114 	for (;;) {
    115 		memset(sizes, 0, sizeof(sizes));
    116 		c = ntfiles = 0;
    117 		if (binno == weights[REC_D] &&
    118 		    !(SINGL_FLD && ftbl[0].flags & F)) {	/* pop */
    119 			rd_append(weights[REC_D],
    120 			    infiles, nfiles, prevfp, buffer, bufend);
    121 			break;
    122 		} else if (binno == weights[REC_D]) {
    123 			depth = 0;		/* start over on flat weights */
    124 			ftbl = tfield;
    125 			weights = ftbl[0].weights;
    126 		}
    127 		while (c != EOF) {
    128 			keypos = keylist;
    129 			nelem = 0;
    130 			crec = (RECHEADER *) buffer;
    131 			while((c = get(binno, infiles, nfiles, crec, bufend,
    132 			    ftbl)) == 0) {
    133 				*keypos++ = crec->data + depth;
    134 				if (++nelem == MAXNUM) {
    135 					c = BUFFEND;
    136 					break;
    137 				}
    138 				crec =(RECHEADER *)	((char *) crec +
    139 				SALIGN(crec->length) + sizeof(TRECHEADER));
    140 			}
    141 			if (c == BUFFEND && nelem == 0) {
    142 				/* buffer was too small for data, allocate
    143 				 * bigger buffer */
    144 				bufsize *= 2;
    145 				buffer = realloc(buffer, bufsize);
    146 				if (!buffer) {
    147 					err(2, "failed to realloc buffer to %ld bytes",
    148 						(unsigned long) bufsize);
    149 				}
    150 				bufend = buffer + bufsize;
    151 				continue;
    152 			}
    153 			if (c == BUFFEND || ntfiles || mfct) {	/* push */
    154 				if (panic >= PANIC) {
    155 					fstack[MAXFCT-16+mfct].fp = ftmp();
    156 					if (radixsort(keylist, nelem, weights,
    157 					    REC_D))
    158 						err(2, NULL);
    159 					append(keylist, nelem, depth, fstack[
    160 					 MAXFCT-16+mfct].fp, putrec, ftbl);
    161 					mfct++;
    162 					/* reduce number of open files */
    163 					if (mfct == 16 ||(c == EOF && ntfiles)) {
    164 						tmpbuf = malloc(bufend -
    165 						    crec->data);
    166 						memmove(tmpbuf, crec->data,
    167 						    bufend - crec->data);
    168 						fstack[tfiles.top + ntfiles].fp
    169 						    = ftmp();
    170 						fmerge(0, mstart, mfct, geteasy,
    171 						  fstack[tfiles.top+ntfiles].fp,
    172 						  putrec, ftbl);
    173 						++ntfiles;
    174 						mfct = 0;
    175 						memmove(crec->data, tmpbuf,
    176 						    bufend - crec->data);
    177 						free(tmpbuf);
    178 					}
    179 				} else {
    180 					fstack[tfiles.top + ntfiles].fp= ftmp();
    181 					onepass(keylist, depth, nelem, sizes,
    182 					weights, fstack[tfiles.top+ntfiles].fp);
    183 					++ntfiles;
    184 				}
    185 			}
    186 		}
    187 		get = getnext;
    188 		if (!ntfiles && !mfct) {	/* everything in memory--pop */
    189 			if (nelem > 1)
    190 			   if (radixsort(keylist, nelem, weights, REC_D))
    191 				err(2, NULL);
    192 			append(keylist, nelem, depth, outfp, putline, ftbl);
    193 			break;					/* pop */
    194 		}
    195 		if (panic >= PANIC) {
    196 			if (!ntfiles)
    197 				fmerge(0, mstart, mfct, geteasy,
    198 				    outfp, putline, ftbl);
    199 			else
    200 				fmerge(0, tfiles, ntfiles, geteasy,
    201 				    outfp, putline, ftbl);
    202 			break;
    203 
    204 		}
    205 		total = maxb = lastb = 0;	/* find if one bin dominates */
    206 		for (i = 0; i < NBINS; i++)
    207 		  if (sizes[i]) {
    208 			if (sizes[i] > sizes[maxb])
    209 				maxb = i;
    210 			lastb = i;
    211 			total += sizes[i];
    212 		}
    213 		if (sizes[maxb] < max((total / 2) , BUFSIZE))
    214 			maxb = lastb;	/* otherwise pop after last bin */
    215 		fstack[tfiles.top].lastb = lastb;
    216 		fstack[tfiles.top].maxb = maxb;
    217 
    218 			/* start refining next level. */
    219 		get(-1, tfiles, ntfiles, crec, bufend, 0);	/* rewind */
    220 		for (i = 0; i < maxb; i++) {
    221 			if (!sizes[i])	/* bin empty; step ahead file offset */
    222 				get(i, tfiles, ntfiles, crec, bufend, 0);
    223 			else
    224 				fsort(i, depth+1, tfiles, ntfiles, outfp, ftbl);
    225 		}
    226 		if (lastb != maxb) {
    227 			if (prevfp != outfp)
    228 				tailfp[panic] = prevfp;
    229 			prevfp = ftmp();
    230 			for (i = maxb+1; i <= lastb; i++)
    231 				if (!sizes[i])
    232 					get(i, tfiles, ntfiles, crec, bufend,0);
    233 				else
    234 					fsort(i, depth+1, tfiles, ntfiles,
    235 					    prevfp, ftbl);
    236 		}
    237 
    238 		/* sort biggest (or last) bin at this level */
    239 		depth++;
    240 		panic++;
    241 		binno = maxb;
    242 		infiles.top = tfiles.top;	/* getnext will free tfiles, */
    243 		nfiles = ntfiles;		/* so overwrite them */
    244 	}
    245 	if (prevfp != outfp) {
    246 		concat(outfp, prevfp);
    247 		fclose(prevfp);
    248 	}
    249 	for (i = panic; i >= 0; --i)
    250 		if (tailfp[i]) {
    251 			concat(outfp, tailfp[i]);
    252 			fclose(tailfp[i]);
    253 		}
    254 }
    255 
    256 /*
    257  This is one pass of radix exchange, dumping the bins to disk.
    258  */
    259 #define swap(a, b, t) t = a, a = b, b = t
    260 void
    261 onepass(a, depth, n, sizes, tr, fp)
    262 	const u_char **a;
    263 	int depth;
    264 	long n, sizes[];
    265 	u_char *tr;
    266 	FILE *fp;
    267 {
    268 	size_t tsizes[NBINS+1];
    269 	const u_char **bin[257], ***bp, ***bpmax, **top[256], ***tp;
    270 	static int histo[256];
    271 	int *hp;
    272 	int c;
    273 	const u_char **an, *t, **aj;
    274 	const u_char **ak, *r;
    275 
    276 	memset(tsizes, 0, sizeof(tsizes));
    277 	depth += sizeof(TRECHEADER);
    278 	an = &a[n];
    279 	for (ak = a; ak < an; ak++) {
    280 		histo[c = tr[**ak]]++;
    281 		tsizes[c] += ((const RECHEADER *) (*ak -= depth))->length;
    282 	}
    283 
    284 	bin[0] = a;
    285 	bpmax = bin + 256;
    286 	tp = top, hp = histo;
    287 	for (bp = bin; bp < bpmax; bp++) {
    288 		*tp++ = *(bp+1) = *bp + (c = *hp);
    289 		*hp++ = 0;
    290 		if (c <= 1)
    291 			continue;
    292 	}
    293 	for(aj = a; aj < an; *aj = r, aj = bin[c+1])
    294 		for(r = *aj; aj < (ak = --top[c = tr[r[depth]]]) ;)
    295 			swap(*ak, r, t);
    296 
    297 	for (ak = a, c = 0; c < 256; c++) {
    298 		an = bin[c+1];
    299 		n = an - ak;
    300 		tsizes[c] += n * sizeof(TRECHEADER);
    301 		/* tell getnext how many elements in this bin, this segment. */
    302 		EWRITE(&tsizes[c], sizeof(size_t), 1, fp);
    303 		sizes[c] += tsizes[c];
    304 		for (; ak < an; ++ak)
    305 			putrec((const RECHEADER *) *ak, fp);
    306 	}
    307 }
    308