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