Home | History | Annotate | Line # | Download | only in sort
msort.c revision 1.14
      1 /*	$NetBSD: msort.c,v 1.14 2003/08/07 11:32:34 jdolecek Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2000-2003 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Ben Harris and Jaromir Dolecek.
      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 NetBSD
     21  *        Foundation, Inc. and its contributors.
     22  * 4. Neither the name of The NetBSD Foundation nor the names of its
     23  *    contributors may be used to endorse or promote products derived
     24  *    from this software without specific prior written permission.
     25  *
     26  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     27  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     28  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     29  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     30  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     36  * POSSIBILITY OF SUCH DAMAGE.
     37  */
     38 
     39 /*-
     40  * Copyright (c) 1993
     41  *	The Regents of the University of California.  All rights reserved.
     42  *
     43  * This code is derived from software contributed to Berkeley by
     44  * Peter McIlroy.
     45  *
     46  * Redistribution and use in source and binary forms, with or without
     47  * modification, are permitted provided that the following conditions
     48  * are met:
     49  * 1. Redistributions of source code must retain the above copyright
     50  *    notice, this list of conditions and the following disclaimer.
     51  * 2. Redistributions in binary form must reproduce the above copyright
     52  *    notice, this list of conditions and the following disclaimer in the
     53  *    documentation and/or other materials provided with the distribution.
     54  * 3. Neither the name of the University nor the names of its contributors
     55  *    may be used to endorse or promote products derived from this software
     56  *    without specific prior written permission.
     57  *
     58  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     59  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     60  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     61  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     62  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     63  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     64  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     65  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     66  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     67  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     68  * SUCH DAMAGE.
     69  */
     70 
     71 #include "sort.h"
     72 #include "fsort.h"
     73 
     74 #ifndef lint
     75 __RCSID("$NetBSD: msort.c,v 1.14 2003/08/07 11:32:34 jdolecek Exp $");
     76 __SCCSID("@(#)msort.c	8.1 (Berkeley) 6/6/93");
     77 #endif /* not lint */
     78 
     79 #include <stdlib.h>
     80 #include <string.h>
     81 #include <unistd.h>
     82 
     83 /* Subroutines using comparisons: merge sort and check order */
     84 #define DELETE (1)
     85 
     86 typedef struct mfile {
     87 	u_char *end;
     88 	short flno;
     89 	struct recheader rec[1];
     90 } MFILE;
     91 
     92 static u_char *wts, *wts1 = NULL;
     93 
     94 static int cmp __P((RECHEADER *, RECHEADER *));
     95 static int insert __P((struct mfile **, struct mfile **, int, int));
     96 static void merge(int, int, get_func_t, FILE *, put_func_t, struct field *);
     97 
     98 void
     99 fmerge(binno, top, filelist, nfiles, get, outfp, fput, ftbl)
    100 	int binno, top;
    101 	struct filelist *filelist;
    102 	int nfiles;
    103 	get_func_t get;
    104 	FILE *outfp;
    105 	put_func_t fput;
    106 	struct field *ftbl;
    107 {
    108 	FILE *tout;
    109 	int i, j, last;
    110 	put_func_t put;
    111 	struct tempfile *l_fstack;
    112 
    113 	wts = ftbl->weights;
    114 	if (!UNIQUE && SINGL_FLD && ftbl->flags & F)
    115 		wts1 = (ftbl->flags & R) ? Rascii : ascii;
    116 
    117 	if (!buffer) {
    118 		buffer = malloc(bufsize);
    119 		if (!buffer)
    120 			err(2, "fmerge(): malloc");
    121 
    122 		if (!linebuf && !SINGL_FLD) {
    123 			linebuf_size = DEFLLEN;
    124 			linebuf = malloc(linebuf_size);
    125 		}
    126 	}
    127 
    128 	if (binno >= 0)
    129 		l_fstack = fstack + top;
    130 	else
    131 		l_fstack = fstack;
    132 
    133 	while (nfiles) {
    134 		put = putrec;
    135 		for (j = 0; j < nfiles; j += MERGE_FNUM) {
    136 			if (nfiles <= MERGE_FNUM) {
    137 				tout = outfp;
    138 				put = fput;
    139 			}
    140 			else
    141 				tout = ftmp();
    142 			last = min(MERGE_FNUM, nfiles - j);
    143 			if (binno < 0) {
    144 				for (i = 0; i < last; i++)
    145 					if (!(l_fstack[i+MAXFCT-1-MERGE_FNUM].fp =
    146 					    fopen(filelist->names[j+i], "r")))
    147 						err(2, "%s",
    148 							filelist->names[j+i]);
    149 				merge(MAXFCT-1-MERGE_FNUM, last, get, tout, put, ftbl);
    150 			} else {
    151 				for (i = 0; i< last; i++)
    152 					rewind(l_fstack[i+j].fp);
    153 				merge(top+j, last, get, tout, put, ftbl);
    154 			}
    155 			if (nfiles > MERGE_FNUM)
    156 				l_fstack[j/MERGE_FNUM].fp = tout;
    157 		}
    158 		nfiles = (nfiles + (MERGE_FNUM - 1)) / MERGE_FNUM;
    159 		if (nfiles == 1)
    160 			nfiles = 0;
    161 		if (binno < 0) {
    162 			binno = 0;
    163 			get = geteasy;
    164 			top = 0;
    165 		}
    166 	}
    167 }
    168 
    169 static void
    170 merge(infl0, nfiles, get, outfp, put, ftbl)
    171 	int infl0, nfiles;
    172 	get_func_t get;
    173 	put_func_t put;
    174 	FILE *outfp;
    175 	struct field *ftbl;
    176 {
    177 	int c, i, j, nf = nfiles;
    178 	struct mfile *flistb[MERGE_FNUM], **flist = flistb, *cfile;
    179 	size_t availsz = bufsize;
    180 	static void *bufs[MERGE_FNUM+1];
    181 	static size_t bufs_sz[MERGE_FNUM+1];
    182 
    183 	/*
    184 	 * We need nfiles + 1 buffers. One is 'buffer', the
    185 	 * rest needs to be allocated.
    186 	 */
    187 	bufs[0] = buffer;
    188 	bufs_sz[0] = bufsize;
    189 	for(i=1; i < nfiles+1; i++) {
    190 		if (bufs[i])
    191 			continue;
    192 
    193 		bufs[i] = malloc(DEFLLEN);
    194 		if (!bufs[i])
    195 			err(2, "merge: malloc");
    196 		bufs_sz[i] = DEFLLEN;
    197 	}
    198 
    199 	for (i = j = 0; i < nfiles; i++, j++) {
    200 		cfile = (struct mfile *) bufs[j];
    201 		cfile->flno = infl0 + j;
    202 		cfile->end = (u_char *) bufs[j] + bufs_sz[j];
    203 		for (c = 1; c == 1;) {
    204 			if (EOF == (c = get(cfile->flno, 0, NULL, nfiles,
    205 			   cfile->rec, cfile->end, ftbl))) {
    206 				--i;
    207 				--nfiles;
    208 				break;
    209 			}
    210 
    211 			if (c == BUFFEND) {
    212 				cfile = realloc(bufs[j], bufs_sz[j] *= 2);
    213 				if (!cfile)
    214 					err(2, "merge: realloc");
    215 
    216 				bufs[j] = (void *) cfile;
    217 				cfile->end = (u_char *)cfile + bufs_sz[j];
    218 
    219 				c = 1;
    220 				continue;
    221 			}
    222 
    223 			if (i)
    224 				c = insert(flist, &cfile, i, !DELETE);
    225 			else
    226 				flist[0] = cfile;
    227 		}
    228 	}
    229 
    230 	cfile = (struct mfile *) bufs[nf];
    231 	cfile->flno = flist[0]->flno;
    232 	cfile->end = (u_char *) cfile + bufs_sz[nf];
    233 	while (nfiles) {
    234 		for (c = 1; c == 1;) {
    235 			if (EOF == (c = get(cfile->flno, 0, NULL, nfiles,
    236 			   cfile->rec, cfile->end, ftbl))) {
    237 				put(flist[0]->rec, outfp);
    238 				if (--nfiles > 0) {
    239 					flist++;
    240 					cfile->flno = flist[0]->flno;
    241 				}
    242 				break;
    243 			}
    244 			if (c == BUFFEND) {
    245 				char *oldbuf = (char *) cfile;
    246 				availsz = (char *) cfile->end - oldbuf;
    247 				availsz *= 2;
    248 				cfile = realloc(oldbuf, availsz);
    249 				if (!cfile)
    250 					err(2, "merge: realloc");
    251 
    252 				for(i=0; i < nf+1; i++) {
    253 					if (bufs[i] == oldbuf) {
    254 						bufs[i] = (char *)cfile;
    255 						bufs_sz[i] = availsz;
    256 						break;
    257 					}
    258 				}
    259 
    260 				cfile->end = (u_char *)cfile + availsz;
    261 				c = 1;
    262 				continue;
    263 			}
    264 
    265 			if (!(c = insert(flist, &cfile, nfiles, DELETE)))
    266 				put(cfile->rec, outfp);
    267 		}
    268 	}
    269 
    270 	if (bufs_sz[0] > bufsize) {
    271 		buffer = bufs[0];
    272 		bufsize = bufs_sz[0];
    273 	}
    274 }
    275 
    276 /*
    277  * if delete: inserts *rec in flist, deletes flist[0], and leaves it in *rec;
    278  * otherwise just inserts *rec in flist.
    279  */
    280 static int
    281 insert(flist, rec, ttop, delete)
    282 	struct mfile **flist, **rec;
    283 	int delete, ttop;			/* delete = 0 or 1 */
    284 {
    285 	struct mfile *tmprec = *rec;
    286 	int mid, top = ttop, bot = 0, cmpv = 1;
    287 
    288 	for (mid = top/2; bot +1 != top; mid = (bot+top)/2) {
    289 		cmpv = cmp(tmprec->rec, flist[mid]->rec);
    290 		if (cmpv < 0)
    291 			top = mid;
    292 		else if (cmpv > 0)
    293 			bot = mid;
    294 		else {
    295 			if (UNIQUE)
    296 				break;
    297 
    298 			if (stable_sort) {
    299 				/*
    300 				 * Apply sort by fileno, to give priority
    301 				 * to earlier specified files, hence providing
    302 				 * more stable sort.
    303 				 * If fileno is same, the new record should
    304 				 * be put _after_ the previous entry.
    305 				 */
    306 				cmpv = tmprec->flno - flist[mid]->flno;
    307 				if (cmpv >= 0)
    308 					bot = mid;
    309 				else /* cmpv == 0 */
    310 					bot = mid - 1;
    311 			} else {
    312 				/* non-stable sort */
    313 				bot = mid - 1;
    314 			}
    315 
    316 			break;
    317 		}
    318 	}
    319 
    320 	if (delete) {
    321 		if (UNIQUE) {
    322 			if (!bot && cmpv)
    323 				cmpv = cmp(tmprec->rec, flist[0]->rec);
    324 			if (!cmpv)
    325 				return (1);
    326 		}
    327 		tmprec = flist[0];
    328 		if (bot)
    329 			memmove(flist, flist+1, bot * sizeof(MFILE **));
    330 		flist[bot] = *rec;
    331 		*rec = tmprec;
    332 		(*rec)->flno = flist[0]->flno;
    333 		return (0);
    334 	} else {
    335 		if (!bot && !(UNIQUE && !cmpv)) {
    336 			cmpv = cmp(tmprec->rec, flist[0]->rec);
    337 			if (cmpv < 0)
    338 				bot = -1;
    339 		}
    340 		if (UNIQUE && !cmpv)
    341 			return (1);
    342 		bot++;
    343 		memmove(flist + bot+1, flist + bot,
    344 		    (ttop - bot) * sizeof(MFILE **));
    345 		flist[bot] = *rec;
    346 		return (0);
    347 	}
    348 }
    349 
    350 /*
    351  * check order on one file
    352  */
    353 void
    354 order(filelist, get, ftbl)
    355 	struct filelist *filelist;
    356 	get_func_t get;
    357 	struct field *ftbl;
    358 {
    359 	u_char *crec_end, *prec_end, *trec_end;
    360 	int c;
    361 	RECHEADER *crec, *prec, *trec;
    362 
    363 	if (!SINGL_FLD)
    364 		linebuf = malloc(DEFLLEN);
    365 	buffer = malloc(2 * (DEFLLEN + sizeof(TRECHEADER)));
    366 	crec = (RECHEADER *) buffer;
    367 	crec_end = buffer + DEFLLEN + sizeof(TRECHEADER);
    368 	prec = (RECHEADER *) (buffer + DEFLLEN + sizeof(TRECHEADER));
    369 	prec_end = buffer + 2*(DEFLLEN + sizeof(TRECHEADER));
    370 	wts = ftbl->weights;
    371 	if (SINGL_FLD && (ftbl->flags & F))
    372 		wts1 = (ftbl->flags & R) ? Rascii : ascii;
    373 	else
    374 		wts1 = NULL;
    375 	if (0 == get(-1, 0, filelist, 1, prec, prec_end, ftbl))
    376 	while (0 == get(-1, 0, filelist, 1, crec, crec_end, ftbl)) {
    377 		if (0 < (c = cmp(prec, crec))) {
    378 			crec->data[crec->length-1] = 0;
    379 			errx(1, "found disorder: %s", crec->data+crec->offset);
    380 		}
    381 		if (UNIQUE && !c) {
    382 			crec->data[crec->length-1] = 0;
    383 			errx(1, "found non-uniqueness: %s",
    384 			    crec->data+crec->offset);
    385 		}
    386 		/*
    387 		 * Swap pointers so that this record is on place pointed
    388 		 * to by prec and new record is read to place pointed to by
    389 		 * crec.
    390 		 */
    391 		trec = prec;
    392 		prec = crec;
    393 		crec = trec;
    394 		trec_end = prec_end;
    395 		prec_end = crec_end;
    396 		crec_end = trec_end;
    397 	}
    398 	exit(0);
    399 }
    400 
    401 static int
    402 cmp(rec1, rec2)
    403 	RECHEADER *rec1, *rec2;
    404 {
    405 	int r;
    406 	u_char *pos1, *pos2, *end;
    407 	u_char *cwts;
    408 	for (cwts = wts; cwts; cwts = (cwts == wts1 ? NULL : wts1)) {
    409 		pos1 = rec1->data;
    410 		pos2 = rec2->data;
    411 		if (!SINGL_FLD && (UNIQUE || stable_sort))
    412 			end = pos1 + min(rec1->offset, rec2->offset);
    413 		else
    414 			end = pos1 + min(rec1->length, rec2->length);
    415 
    416 		for (; pos1 < end; ) {
    417 			if ((r = cwts[*pos1++] - cwts[*pos2++]))
    418 				return (r);
    419 		}
    420 	}
    421 	return (0);
    422 }
    423