xref: /netbsd-src/usr.bin/sort/fields.c (revision bcc8ec9959e7b01e313d813067bfb43a3ad70551)
1 /*	$NetBSD: fields.c,v 1.7 2001/01/13 19:04:21 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 /* Subroutines to generate sort keys. */
40 
41 #include "sort.h"
42 
43 #ifndef lint
44 __RCSID("$NetBSD: fields.c,v 1.7 2001/01/13 19:04:21 jdolecek Exp $");
45 __SCCSID("@(#)fields.c	8.1 (Berkeley) 6/6/93");
46 #endif /* not lint */
47 
48 #define blancmange(ptr) {					\
49 	if (BLANK & d_mask[*(ptr)])				\
50 		while (BLANK & d_mask[*(++(ptr))]);		\
51 }
52 
53 #define NEXTCOL(pos) {						\
54 	if (!SEP_FLAG)						\
55 		while (BLANK & l_d_mask[*(++pos)]);		\
56 	while (!((FLD_D | REC_D_F) & l_d_mask[*++pos]));	\
57 }
58 
59 static u_char *enterfield __P((u_char *, u_char *, struct field *, int));
60 static u_char *number __P((u_char *, u_char *, u_char *, u_char *, int));
61 
62 extern struct coldesc clist[(ND+1)*2];
63 extern int ncols;
64 
65 #define DECIMAL '.'
66 #define OFFSET 128
67 
68 u_char TENS[10];	/* TENS[0] = REC_D <= 128 ? 130 - '0' : 2 -'0'... */
69 u_char NEGTENS[10];	/* NEGTENS[0] = REC_D <= 128 ? 126 + '0' : 252 +'0' */
70 u_char *OFF_TENS, *OFF_NTENS;	/* TENS - '0', NEGTENS - '0' */
71 u_char fnum[NBINS], rnum[NBINS];
72 
73 /*
74  * constructs sort key with leading recheader, followed by the key,
75  * followed by the original line.
76  */
77 length_t
78 enterkey(keybuf, line, size, fieldtable)
79 	struct recheader *keybuf;	/* pointer to start of key */
80 	DBT *line;
81 	int size;
82 	struct field *fieldtable;
83 {
84 	int i;
85 	u_char *l_d_mask;
86 	u_char *lineend, *pos;
87 	u_char *endkey, *keypos;
88 	struct coldesc *clpos;
89 	int col = 1;
90 	struct field *ftpos;
91 	l_d_mask = d_mask;
92 	pos = (u_char *) line->data - 1;
93 	lineend = (u_char *) line->data + line->size-1;
94 				/* don't include rec_delimiter */
95 	keypos = keybuf->data;
96 
97 	for (i = 0; i < ncols; i++) {
98 		clpos = clist + i;
99 		for (; (col < clpos->num) && (pos < lineend); col++)
100 			{ NEXTCOL(pos); }
101 		if (pos >= lineend)
102 			break;
103 		clpos->start = SEP_FLAG ? pos + 1 : pos;
104 		NEXTCOL(pos);
105 		clpos->end = pos;
106 		col++;
107 		if (pos >= lineend) {
108 			clpos->end = lineend;
109 			++i;
110 			break;
111 		}
112 	}
113 	for (; i <= ncols; i++)
114 		clist[i].start = clist[i].end = lineend;
115 	if (clist[0].start < (u_char *) line->data)
116 		++clist[0].start;
117 	endkey = (u_char *) keybuf + size - line->size;
118 	for (ftpos = fieldtable + 1; ftpos->icol.num; ftpos++)
119 		if ((keypos = enterfield(keypos, endkey, ftpos,
120 		    fieldtable->flags)) == NULL)
121 			return (1);
122 
123 	keybuf->offset = keypos - keybuf->data;
124 
125 	/*
126 	 * Make [s]radixsort() only sort by relevant part of key if:
127 	 * 1. we want to choose unique items by relevant field[s]
128 	 * 2. we want stable sort and so the items should be sorted only by
129 	 *    the relevant field[s]
130 	 */
131 	if (UNIQUE || (stable_sort && keybuf->offset < line->size))
132 		keypos[-1] = REC_D;
133 
134 	keybuf->length = keybuf->offset + line->size;
135 	if (keybuf->length + sizeof(TRECHEADER) > size) {
136 		/* line too long for buffer */
137 		return (1);
138 	}
139 	memcpy(keybuf->data + keybuf->offset, line->data, line->size);
140 	return (0);
141 }
142 
143 /*
144  * constructs a field (as defined by -k) within a key
145  */
146 static u_char *
147 enterfield(tablepos, endkey, cur_fld, gflags)
148 	struct field *cur_fld;
149 	u_char *tablepos, *endkey;
150 	int gflags;
151 {
152 	u_char *start, *end, *lineend, *mask, *lweight;
153 	struct column icol, tcol;
154 	u_int flags;
155 	u_int Rflag;
156 	icol = cur_fld->icol;
157 	tcol = cur_fld->tcol;
158 	flags = cur_fld->flags;
159 	start = icol.p->start;
160 	lineend = clist[ncols].end;
161 	if (flags & BI)
162 		blancmange(start);
163 	start += icol.indent;
164 	start = min(start, lineend);
165 	if (!tcol.num)
166 		end = lineend;
167 	else {
168 		if (tcol.indent) {
169 			end = tcol.p->start;
170 			if (flags & BT)
171 				blancmange(end);
172 			end += tcol.indent;
173 			end = min(end, lineend);
174 		} else
175 			end = tcol.p->end;
176 	}
177 
178 	if (flags & N) {
179 		Rflag = (gflags & R ) ^ (flags & R) ? 1 : 0;
180 		return number(tablepos, endkey, start, end, Rflag);
181 	}
182 
183 	mask = cur_fld->mask;
184 	lweight = cur_fld->weights;
185 	for (; start < end; start++)
186 		if (mask[*start]) {
187 			if (*start <= 1) {
188 				if (tablepos+2 >= endkey)
189 					return (NULL);
190 				*tablepos++ = lweight[1];
191 				*tablepos++ = lweight[*start ? 2 : 1];
192 			} else {
193 				*tablepos++ = lweight[*start];
194 				if (tablepos == endkey)
195 					return (NULL);
196 			}
197 		}
198 	*tablepos++ = lweight[0];
199 	return (tablepos == endkey ? NULL : tablepos);
200 }
201 
202 /* Uses the first bin to assign sign, expsign, 0, and the first
203  * 61 out of the exponent ( (254 - 3 origins - 4 over/underflows)/4 = 61 ).
204  *   When sorting in forward order:
205  * use (0-99) -> (130->240) for sorting the mantissa if REC_D <=128;
206  * else use (0-99)->(2-102).
207  * If the exponent is >=61, use another byte for each additional 253
208  * in the exponent. Cutoff is at 567.
209  * To avoid confusing the exponent and the mantissa, use a field delimiter
210  * if the exponent is exactly 61, 61+252, etc--this is ok, since it's the
211  * only time a field delimiter can come in that position.
212  * Reverse order is done analagously.
213 */
214 
215 static u_char *
216 number(pos, bufend, line, lineend, Rflag)
217 	u_char *line, *pos, *bufend, *lineend;
218 	int Rflag;
219 {
220 	int or_sign, parity = 0;
221 	int expincr = 1, exponent = -1;
222 	int bite, expsign = 1, sign = 1;
223 	u_char lastvalue, *nonzero, *tline, *C_TENS;
224 	u_char *nweights;
225 
226 	if (Rflag)
227 		nweights = rnum;
228 	else
229 		nweights = fnum;
230 	if (pos > bufend - 8)
231 		return (NULL);
232 	/* or_sign sets the sort direction:
233 	 *	(-r: +/-)(sign: +/-)(expsign: +/-) */
234 	or_sign = sign ^ expsign ^ Rflag;
235 	blancmange(line);
236 	if (*line == '-') {	/* set the sign */
237 		or_sign ^= 1;
238 		sign = 0;
239 		line++;
240 	}
241 	/* eat initial zeroes */
242 	for (; *line == '0' && line < lineend; line++);
243 	/* calculate exponents < 0 */
244 	if (*line == DECIMAL) {
245 		exponent = 1;
246 		while (*++line == '0' && line < lineend)
247 			exponent++;
248 		expincr = 0;
249 		expsign = 0;
250 	}
251 	/* next character better be a digit */
252 	if (*line < '1' || *line > '9' || line >= lineend) {
253 		*pos++ = nweights[127];
254 		return (pos);
255 	}
256 	if (expincr) {
257 		for (tline = line-1; *++tline >= '0' &&
258 		    *tline <= '9' && tline < lineend;)
259 			exponent++;
260 	}
261 	if (exponent > 567) {
262 		*pos++ = nweights[sign ? (expsign ? 254 : 128)
263 					: (expsign ? 0 : 126)];
264 		warnx("exponent out of bounds");
265 		return (pos);
266 	}
267 	bite = min(exponent, 61);
268 	*pos++ = nweights[(sign) ? (expsign ? 189+bite : 189-bite)
269 				: (expsign ? 64-bite : 64+bite)];
270 	if (bite >= 61) {
271 		do {
272 			exponent -= bite;
273 			bite = min(exponent, 254);
274 			*pos++ = nweights[or_sign ? 254-bite : bite];
275 		} while (bite == 254);
276 	}
277 	C_TENS = or_sign ? OFF_NTENS : OFF_TENS;
278 	for (; line < lineend; line++) {
279 		if (*line >= '0' && *line <= '9') {
280 			if (parity) {
281 				*pos++ = C_TENS[lastvalue] + (or_sign ? - *line
282 						: *line);
283 				if (pos == bufend)
284 					return (NULL);
285 				if (*line != '0' || lastvalue != '0')
286 					nonzero = pos;
287 			} else
288 				lastvalue = *line;
289 			parity ^= 1;
290 		} else if(*line == DECIMAL) {
291 			if(!expincr)	/* a decimal already occurred once */
292 				break;
293 			expincr = 0;
294 		} else
295 			break;
296 	}
297 	if (parity && lastvalue != '0') {
298 		*pos++ = or_sign ? OFF_NTENS[lastvalue] - '0' :
299 					OFF_TENS[lastvalue] + '0';
300 	} else
301 		pos = nonzero;
302 	if (pos > bufend-1)
303 		return (NULL);
304 	*pos++ = or_sign ? nweights[254] : nweights[0];
305 	return (pos);
306 }
307 
308 /* This forces a gap around the record delimiter
309  * Thus fnum has vaues over (0,254) -> ((0,REC_D-1),(REC_D+1,255));
310  * rnum over (0,254) -> (255,REC_D+1),(REC_D-1,0))
311 */
312 void
313 num_init()
314 {
315 	int i;
316 	TENS[0] = REC_D <=128 ? 130 - '0' : 2 - '0';
317 	NEGTENS[0] = REC_D <=128 ? 126 + '0' : 254 + '0';
318 	OFF_TENS = TENS - '0';
319 	OFF_NTENS = NEGTENS - '0';
320 	for (i = 1; i < 10; i++) {
321 		TENS[i] = TENS[i-1] + 10;
322 		NEGTENS[i] = NEGTENS[i-1] - 10;
323 	}
324 	for (i = 0; i < REC_D; i++) {
325 		fnum[i] = i;
326 		rnum[255-i] = i;
327 	}
328 	for (i = REC_D; i <255; i++) {
329 		fnum[i] = i+1;
330 		rnum[255-i] = i-1;
331 	}
332 }
333