xref: /original-bsd/usr.bin/look/look.c (revision 860e07fc)
1 /*-
2  * Copyright (c) 1991 The Regents of the University of California.
3  * 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 char copyright[] =
13 "@(#) Copyright (c) 1991 The Regents of the University of California.\n\
14  All rights reserved.\n";
15 #endif /* not lint */
16 
17 #ifndef lint
18 static char sccsid[] = "@(#)look.c	5.2 (Berkeley) 06/24/92";
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 void	 usage __P((void));
66 
67 main(argc, argv)
68 	int argc;
69 	char *argv[];
70 {
71 	struct stat sb;
72 	int ch, fd;
73 	char *back, *file, *front, *string;
74 
75 	file = _PATH_WORDS;
76 	while ((ch = getopt(argc, argv, "df")) != EOF)
77 		switch(ch) {
78 		case 'd':
79 			dflag = 1;
80 			break;
81 		case 'f':
82 			fflag = 1;
83 			break;
84 		case '?':
85 		default:
86 			usage();
87 		}
88 	argc -= optind;
89 	argv += optind;
90 
91 	switch (argc) {
92 	case 2:				/* Don't set -df for user. */
93 		string = *argv++;
94 		file = *argv;
95 		break;
96 	case 1:				/* But set -df by default. */
97 		dflag = fflag = 1;
98 		string = *argv;
99 		break;
100 	default:
101 		usage();
102 	}
103 
104 	if ((fd = open(file, O_RDONLY, 0)) < 0 || fstat(fd, &sb))
105 		err("%s: %s", file, strerror(errno));
106 	if (sb.st_size > SIZE_T_MAX)
107 		err("%s: %s", file, strerror(EFBIG));
108 	if ((front = mmap(NULL,
109 	    (size_t)sb.st_size, PROT_READ, 0, fd, (off_t)0)) == NULL)
110 		err("%s: %s", file, strerror(errno));
111 	back = front + sb.st_size;
112 	exit(look(string, front, back));
113 }
114 
115 look(string, front, back)
116 	char *string, *front, *back;
117 {
118 	register int ch;
119 	register char *readp, *writep;
120 
121 	/* Reformat string string to avoid doing it multiple times later. */
122 	for (readp = writep = string; ch = *readp++;) {
123 		if (fflag)
124 			ch = FOLD(ch);
125 		if (dflag)
126 			ch = DICT(ch);
127 		if (ch != NO_COMPARE)
128 			*(writep++) = ch;
129 	}
130 	*writep = '\0';
131 
132 	front = binary_search(string, front, back);
133 	front = linear_search(string, front, back);
134 
135 	if (front)
136 		print_from(string, front, back);
137 	return (front ? 0 : 1);
138 }
139 
140 
141 /*
142  * Binary search for "string" in memory between "front" and "back".
143  *
144  * This routine is expected to return a pointer to the start of a line at
145  * *or before* the first word matching "string".  Relaxing the constraint
146  * this way simplifies the algorithm.
147  *
148  * Invariants:
149  * 	front points to the beginning of a line at or before the first
150  *	matching string.
151  *
152  * 	back points to the beginning of a line at or after the first
153  *	matching line.
154  *
155  * Base of the Invariants.
156  * 	front = NULL;
157  *	back = EOF;
158  *
159  * Advancing the Invariants:
160  *
161  * 	p = first newline after halfway point from front to back.
162  *
163  * 	If the string at "p" is not greater than the string to match,
164  *	p is the new front.  Otherwise it is the new back.
165  *
166  * Termination:
167  *
168  * 	The definition of the routine allows it return at any point,
169  *	since front is always at or before the line to print.
170  *
171  * 	In fact, it returns when the chosen "p" equals "back".  This
172  *	implies that there exists a string is least half as long as
173  *	(back - front), which in turn implies that a linear search will
174  *	be no more expensive than the cost of simply printing a string or two.
175  *
176  * 	Trying to continue with binary search at this point would be
177  *	more trouble than it's worth.
178  */
179 #define	SKIP_PAST_NEWLINE(p, back) \
180 	while (p < back && *p++ != '\n');
181 
182 char *
183 binary_search(string, front, back)
184 	register char *string, *front, *back;
185 {
186 	register char *p;
187 
188 	p = front + (back - front) / 2;
189 	SKIP_PAST_NEWLINE(p, back);
190 
191 	while (p != back) {
192 		if (compare(string, p, back) == GREATER)
193 			front = p;
194 		else
195 			back = p;
196 		p = front + (back - front) / 2;
197 		SKIP_PAST_NEWLINE(p, back);
198 	}
199 	return (front);
200 }
201 
202 /*
203  * Find the first line that starts with string, linearly searching from front
204  * to back.
205  *
206  * Return NULL for no such line.
207  *
208  * This routine assumes:
209  *
210  * 	o front points at the first character in a line.
211  *	o front is before or at the first line to be printed.
212  */
213 char *
214 linear_search(string, front, back)
215 	char *string, *front, *back;
216 {
217 	while (front < back) {
218 		switch (compare(string, front, back)) {
219 		case EQUAL:		/* Found it. */
220 			return (front);
221 			break;
222 		case LESS:		/* No such string. */
223 			return (NULL);
224 			break;
225 		case GREATER:		/* Keep going. */
226 			break;
227 		}
228 		SKIP_PAST_NEWLINE(front, back);
229 	}
230 	return (NULL);
231 }
232 
233 /*
234  * Print as many lines as match string, starting at front.
235  */
236 void
237 print_from(string, front, back)
238 	register char *string, *front, *back;
239 {
240 	for (; front < back && compare(string, front, back) == EQUAL; ++front) {
241 		for (; front < back && *front != '\n'; ++front)
242 			if (putchar(*front) == EOF)
243 				err("stdout: %s", strerror(errno));
244 		if (putchar('\n') == EOF)
245 			err("stdout: %s", strerror(errno));
246 	}
247 }
248 
249 /*
250  * Return LESS, GREATER, or EQUAL depending on how the string1 compares with
251  * string2 (s1 ??? s2).
252  *
253  * 	o Matches up to len(s1) are EQUAL.
254  *	o Matches up to len(s2) are GREATER.
255  *
256  * Compare understands about the -f and -d flags, and treats comparisons
257  * appropriately.
258  *
259  * The string "s1" is null terminated.  The string s2 is '\n' terminated (or
260  * "back" terminated).
261  */
262 int
263 compare(s1, s2, back)
264 	register char *s1, *s2, *back;
265 {
266 	register int ch;
267 
268 	for (; *s1 && s2 < back && *s2 != '\n'; ++s1, ++s2) {
269 		ch = *s2;
270 		if (fflag)
271 			ch = FOLD(ch);
272 		if (dflag)
273 			ch = DICT(ch);
274 
275 		if (ch == NO_COMPARE) {
276 			++s2;		/* Ignore character in comparison. */
277 			continue;
278 		}
279 		if (*s1 != ch)
280 			return (*s1 < ch ? LESS : GREATER);
281 	}
282 	return (*s1 ? GREATER : EQUAL);
283 }
284 
285 static void
286 usage()
287 {
288 	(void)fprintf(stderr, "usage: look [-df] string [file]\n");
289 	exit(2);
290 }
291 
292 #if __STDC__
293 #include <stdarg.h>
294 #else
295 #include <varargs.h>
296 #endif
297 
298 void
299 #if __STDC__
300 err(const char *fmt, ...)
301 #else
302 err(fmt, va_alist)
303 	char *fmt;
304 	va_dcl
305 #endif
306 {
307 	va_list ap;
308 #if __STDC__
309 	va_start(ap, fmt);
310 #else
311 	va_start(ap);
312 #endif
313 	(void)fprintf(stderr, "look: ");
314 	(void)vfprintf(stderr, fmt, ap);
315 	va_end(ap);
316 	(void)fprintf(stderr, "\n");
317 	exit(2);
318 	/* NOTREACHED */
319 }
320