xref: /original-bsd/usr.bin/look/look.c (revision 3705696b)
1 /*-
2  * Copyright (c) 1991, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * David Hitz of Auspex Systems, Inc.
7  *
8  * %sccs.include.redist.c%
9  */
10 
11 #ifndef lint
12 static char copyright[] =
13 "@(#) Copyright (c) 1991, 1993\n\
14 	The Regents of the University of California.  All rights reserved.\n";
15 #endif /* not lint */
16 
17 #ifndef lint
18 static char sccsid[] = "@(#)look.c	8.1 (Berkeley) 06/14/93";
19 #endif /* not lint */
20 
21 /*
22  * look -- find lines in a sorted list.
23  *
24  * The man page said that TABs and SPACEs participate in -d comparisons.
25  * In fact, they were ignored.  This implements historic practice, not
26  * the manual page.
27  */
28 
29 #include <sys/types.h>
30 #include <sys/mman.h>
31 #include <sys/stat.h>
32 
33 #include <limits.h>
34 #include <errno.h>
35 #include <fcntl.h>
36 #include <stdio.h>
37 #include <stdlib.h>
38 #include <string.h>
39 #include <ctype.h>
40 #include "pathnames.h"
41 
42 /*
43  * FOLD and DICT convert characters to a normal form for comparison,
44  * according to the user specified flags.
45  *
46  * DICT expects integers because it uses a non-character value to
47  * indicate a character which should not participate in comparisons.
48  */
49 #define	EQUAL		0
50 #define	GREATER		1
51 #define	LESS		(-1)
52 #define NO_COMPARE	(-2)
53 
54 #define	FOLD(c)	(isascii(c) && isupper(c) ? tolower(c) : (c))
55 #define	DICT(c)	(isascii(c) && isalnum(c) ? (c) : NO_COMPARE)
56 
57 int dflag, fflag;
58 
59 char	*binary_search __P((char *, char *, char *));
60 int	 compare __P((char *, char *, char *));
61 void	 err __P((const char *fmt, ...));
62 char	*linear_search __P((char *, char *, char *));
63 int	 look __P((char *, char *, char *));
64 void	 print_from __P((char *, char *, char *));
65 
66 static void usage __P((void));
67 
68 main(argc, argv)
69 	int argc;
70 	char *argv[];
71 {
72 	struct stat sb;
73 	int ch, fd, termchar;
74 	char *back, *file, *front, *string, *p;
75 
76 	file = _PATH_WORDS;
77 	termchar = '\0';
78 	while ((ch = getopt(argc, argv, "dft:")) != EOF)
79 		switch(ch) {
80 		case 'd':
81 			dflag = 1;
82 			break;
83 		case 'f':
84 			fflag = 1;
85 			break;
86 		case 't':
87 			termchar = *optarg;
88 			break;
89 		case '?':
90 		default:
91 			usage();
92 		}
93 	argc -= optind;
94 	argv += optind;
95 
96 	switch (argc) {
97 	case 2:				/* Don't set -df for user. */
98 		string = *argv++;
99 		file = *argv;
100 		break;
101 	case 1:				/* But set -df by default. */
102 		dflag = fflag = 1;
103 		string = *argv;
104 		break;
105 	default:
106 		usage();
107 	}
108 
109 	if (termchar != '\0' && (p = strchr(string, termchar)) != NULL)
110 		*++p = '\0';
111 
112 	if ((fd = open(file, O_RDONLY, 0)) < 0 || fstat(fd, &sb))
113 		err("%s: %s", file, strerror(errno));
114 	if (sb.st_size > SIZE_T_MAX)
115 		err("%s: %s", file, strerror(EFBIG));
116 	if ((front = mmap(NULL,
117 	    (size_t)sb.st_size, PROT_READ, 0, fd, (off_t)0)) == NULL)
118 		err("%s: %s", file, strerror(errno));
119 	back = front + sb.st_size;
120 	exit(look(string, front, back));
121 }
122 
123 look(string, front, back)
124 	char *string, *front, *back;
125 {
126 	register int ch;
127 	register char *readp, *writep;
128 
129 	/* Reformat string string to avoid doing it multiple times later. */
130 	for (readp = writep = string; ch = *readp++;) {
131 		if (fflag)
132 			ch = FOLD(ch);
133 		if (dflag)
134 			ch = DICT(ch);
135 		if (ch != NO_COMPARE)
136 			*(writep++) = ch;
137 	}
138 	*writep = '\0';
139 
140 	front = binary_search(string, front, back);
141 	front = linear_search(string, front, back);
142 
143 	if (front)
144 		print_from(string, front, back);
145 	return (front ? 0 : 1);
146 }
147 
148 
149 /*
150  * Binary search for "string" in memory between "front" and "back".
151  *
152  * This routine is expected to return a pointer to the start of a line at
153  * *or before* the first word matching "string".  Relaxing the constraint
154  * this way simplifies the algorithm.
155  *
156  * Invariants:
157  * 	front points to the beginning of a line at or before the first
158  *	matching string.
159  *
160  * 	back points to the beginning of a line at or after the first
161  *	matching line.
162  *
163  * Base of the Invariants.
164  * 	front = NULL;
165  *	back = EOF;
166  *
167  * Advancing the Invariants:
168  *
169  * 	p = first newline after halfway point from front to back.
170  *
171  * 	If the string at "p" is not greater than the string to match,
172  *	p is the new front.  Otherwise it is the new back.
173  *
174  * Termination:
175  *
176  * 	The definition of the routine allows it return at any point,
177  *	since front is always at or before the line to print.
178  *
179  * 	In fact, it returns when the chosen "p" equals "back".  This
180  *	implies that there exists a string is least half as long as
181  *	(back - front), which in turn implies that a linear search will
182  *	be no more expensive than the cost of simply printing a string or two.
183  *
184  * 	Trying to continue with binary search at this point would be
185  *	more trouble than it's worth.
186  */
187 #define	SKIP_PAST_NEWLINE(p, back) \
188 	while (p < back && *p++ != '\n');
189 
190 char *
191 binary_search(string, front, back)
192 	register char *string, *front, *back;
193 {
194 	register char *p;
195 
196 	p = front + (back - front) / 2;
197 	SKIP_PAST_NEWLINE(p, back);
198 
199 	/*
200 	 * If the file changes underneath us, make sure we don't
201 	 * infinitely loop.
202 	 */
203 	while (p < back && back > front) {
204 		if (compare(string, p, back) == GREATER)
205 			front = p;
206 		else
207 			back = p;
208 		p = front + (back - front) / 2;
209 		SKIP_PAST_NEWLINE(p, back);
210 	}
211 	return (front);
212 }
213 
214 /*
215  * Find the first line that starts with string, linearly searching from front
216  * to back.
217  *
218  * Return NULL for no such line.
219  *
220  * This routine assumes:
221  *
222  * 	o front points at the first character in a line.
223  *	o front is before or at the first line to be printed.
224  */
225 char *
226 linear_search(string, front, back)
227 	char *string, *front, *back;
228 {
229 	while (front < back) {
230 		switch (compare(string, front, back)) {
231 		case EQUAL:		/* Found it. */
232 			return (front);
233 			break;
234 		case LESS:		/* No such string. */
235 			return (NULL);
236 			break;
237 		case GREATER:		/* Keep going. */
238 			break;
239 		}
240 		SKIP_PAST_NEWLINE(front, back);
241 	}
242 	return (NULL);
243 }
244 
245 /*
246  * Print as many lines as match string, starting at front.
247  */
248 void
249 print_from(string, front, back)
250 	register char *string, *front, *back;
251 {
252 	for (; front < back && compare(string, front, back) == EQUAL; ++front) {
253 		for (; front < back && *front != '\n'; ++front)
254 			if (putchar(*front) == EOF)
255 				err("stdout: %s", strerror(errno));
256 		if (putchar('\n') == EOF)
257 			err("stdout: %s", strerror(errno));
258 	}
259 }
260 
261 /*
262  * Return LESS, GREATER, or EQUAL depending on how the string1 compares with
263  * string2 (s1 ??? s2).
264  *
265  * 	o Matches up to len(s1) are EQUAL.
266  *	o Matches up to len(s2) are GREATER.
267  *
268  * Compare understands about the -f and -d flags, and treats comparisons
269  * appropriately.
270  *
271  * The string "s1" is null terminated.  The string s2 is '\n' terminated (or
272  * "back" terminated).
273  */
274 int
275 compare(s1, s2, back)
276 	register char *s1, *s2, *back;
277 {
278 	register int ch;
279 
280 	for (; *s1 && s2 < back && *s2 != '\n'; ++s1, ++s2) {
281 		ch = *s2;
282 		if (fflag)
283 			ch = FOLD(ch);
284 		if (dflag)
285 			ch = DICT(ch);
286 
287 		if (ch == NO_COMPARE) {
288 			++s2;		/* Ignore character in comparison. */
289 			continue;
290 		}
291 		if (*s1 != ch)
292 			return (*s1 < ch ? LESS : GREATER);
293 	}
294 	return (*s1 ? GREATER : EQUAL);
295 }
296 
297 static void
298 usage()
299 {
300 	(void)fprintf(stderr, "usage: look [-df] [-t char] string [file]\n");
301 	exit(2);
302 }
303 
304 #if __STDC__
305 #include <stdarg.h>
306 #else
307 #include <varargs.h>
308 #endif
309 
310 void
311 #if __STDC__
312 err(const char *fmt, ...)
313 #else
314 err(fmt, va_alist)
315 	char *fmt;
316 	va_dcl
317 #endif
318 {
319 	va_list ap;
320 #if __STDC__
321 	va_start(ap, fmt);
322 #else
323 	va_start(ap);
324 #endif
325 	(void)fprintf(stderr, "look: ");
326 	(void)vfprintf(stderr, fmt, ap);
327 	va_end(ap);
328 	(void)fprintf(stderr, "\n");
329 	exit(2);
330 	/* NOTREACHED */
331 }
332