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