xref: /openbsd-src/usr.bin/jot/jot.c (revision ec79d49810965d19260a18d099929e1612ac35be)
1 /*	$OpenBSD: jot.c,v 1.56 2021/08/13 12:37:28 jmc Exp $	*/
2 /*	$NetBSD: jot.c,v 1.3 1994/12/02 20:29:43 pk Exp $	*/
3 
4 /*-
5  * Copyright (c) 1993
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 
33 /*
34  * jot - print sequential or random data
35  *
36  * Author:  John Kunze, Office of Comp. Affairs, UCB
37  */
38 
39 #include <ctype.h>
40 #include <err.h>
41 #include <limits.h>
42 #include <math.h>
43 #include <stdbool.h>
44 #include <stdint.h>
45 #include <stdio.h>
46 #include <stdlib.h>
47 #include <string.h>
48 #include <unistd.h>
49 
50 #define	REPS	1
51 #define	BEGIN	2
52 #define	ENDER	4
53 #define	STEP	8
54 
55 #define	is_default(s)	(strcmp((s), "-") == 0)
56 
57 static long	reps	= 100;
58 static double	begin	= 1;
59 static double	ender	= 100;
60 static double	step	= 1;
61 
62 static char	*format = "";
63 static char	*sepstring = "\n";
64 static int	prec = -1;
65 static bool	boring;
66 static bool	chardata;
67 static bool	finalnl = true;
68 static bool	infinity;
69 static bool	intdata;
70 static bool	longdata;
71 static bool	nosign;
72 static bool	randomize;
73 static bool	word;
74 
75 static void	getformat(void);
76 static int	getprec(char *);
77 static int	putdata(double, bool);
78 static void __dead	usage(void);
79 
80 int
main(int argc,char * argv[])81 main(int argc, char *argv[])
82 {
83 	double		x;
84 	double		y;
85 	long		i;
86 	unsigned int	mask = 0;
87 	int		n = 0;
88 	int		ch;
89 	const char	*errstr;
90 
91 	if (pledge("stdio", NULL) == -1)
92 		err(1, "pledge");
93 
94 	while ((ch = getopt(argc, argv, "b:cnp:rs:w:")) != -1) {
95 		switch (ch) {
96 		case 'b':
97 			boring = true;
98 			chardata = word = false;
99 			format = optarg;
100 			break;
101 		case 'c':
102 			chardata = true;
103 			boring = word = false;
104 			format = "";
105 			break;
106 		case 'n':
107 			finalnl = false;
108 			break;
109 		case 'p':
110 			prec = strtonum(optarg, 0, INT_MAX, &errstr);
111 			if (errstr != NULL)
112 				errx(1, "bad precision value, %s: %s", errstr,
113 					optarg);
114 			break;
115 		case 'r':
116 			randomize = true;
117 			break;
118 		case 's':
119 			sepstring = optarg;
120 			break;
121 		case 'w':
122 			word = true;
123 			boring = chardata = false;
124 			format = optarg;
125 			break;
126 		default:
127 			usage();
128 		}
129 	}
130 	argc -= optind;
131 	argv += optind;
132 
133 	switch (argc) {	/* examine args right to left, falling thru cases */
134 	case 4:
135 		if (!is_default(argv[3])) {
136 			if (!sscanf(argv[3], "%lf", &step))
137 				errx(1, "Bad s value: %s", argv[3]);
138 			mask |= STEP;
139 			if (randomize)
140 				warnx("random seeding not supported");
141 		}
142 	case 3:
143 		if (!is_default(argv[2])) {
144 			if (!sscanf(argv[2], "%lf", &ender))
145 				ender = argv[2][strlen(argv[2])-1];
146 			mask |= ENDER;
147 			if (prec == -1)
148 				n = getprec(argv[2]);
149 		}
150 	case 2:
151 		if (!is_default(argv[1])) {
152 			if (!sscanf(argv[1], "%lf", &begin))
153 				begin = argv[1][strlen(argv[1])-1];
154 			mask |= BEGIN;
155 			if (prec == -1)
156 				prec = getprec(argv[1]);
157 			if (n > prec)		/* maximum precision */
158 				prec = n;
159 		}
160 	case 1:
161 		if (!is_default(argv[0])) {
162 			reps = strtonum(argv[0], 0, LONG_MAX, &errstr);
163 			if (errstr != NULL)
164 				errx(1, "Bad reps value, %s: %s", errstr,
165 				    argv[0]);
166 			mask |= REPS;
167 			if (reps == 0)
168 				infinity = true;
169 		}
170 	case 0:
171 		if (prec == -1)
172 			prec = 0;
173 		break;
174 	default:
175 		errx(1, "Too many arguments.  What do you mean by %s?",
176 		    argv[4]);
177 	}
178 
179 	if (!boring)
180 		getformat();
181 
182 	if (!randomize) {
183 		/*
184 		 * Consolidate the values of reps, begin, ender, step:
185 		 * The formula ender - begin == (reps - 1) * step shows that any
186 		 * three determine the fourth (unless reps == 1 or step == 0).
187 		 * The manual states the following rules:
188 		 * 1. If four are specified, compare the given and the computed
189 		 *    value of reps and take the smaller of the two.
190 		 * 2. If steps was omitted, it takes the default, unless both
191 		 *    begin and ender were specified.
192 		 * 3. Assign defaults to omitted values for reps, begin, ender,
193 		 *    from left to right.
194 		 */
195 		switch (mask) { /* Four cases involve both begin and ender. */
196 		case REPS | BEGIN | ENDER | STEP:
197 			if (infinity)
198 				errx(1,
199 				    "Can't specify end of infinite sequence");
200 			if (step != 0.0) {
201 				long t = (ender - begin + step) / step;
202 				if (t <= 0)
203 					errx(1, "Impossible stepsize");
204 				if (t < reps)
205 					reps = t;
206 			}
207 			break;
208 		case REPS | BEGIN | ENDER:
209 			if (infinity)
210 				errx(1,
211 				    "Can't specify end of infinite sequence");
212 			if (reps == 1)
213 				step = 0.0;
214 			else
215 				step = (ender - begin) / (reps - 1);
216 			break;
217 		case BEGIN | ENDER:
218 			step = ender > begin ? 1 : -1; /* FreeBSD's behavior. */
219 			/* FALLTHROUGH */
220 		case BEGIN | ENDER | STEP:
221 			if (step == 0.0) {
222 				reps = 0;
223 				infinity = true;
224 				break;
225 			}
226 			reps = (ender - begin + step) / step;
227 			if (reps <= 0)
228 				errx(1, "Impossible stepsize");
229 			break;
230 		case ENDER:		/* Four cases involve only ender. */
231 		case ENDER | STEP:
232 		case REPS | ENDER:
233 		case REPS | ENDER | STEP:
234 			if (infinity)
235 				errx(1,
236 				    "Must specify start of infinite sequence");
237 			begin = ender - reps * step + step;
238 			break;
239 		default:
240 			/*
241 			 * The remaining eight cases omit ender.  We don't need
242 			 * to compute anything because only reps, begin, step
243 			 * are used for producing output below.  Rules 2. and 3.
244 			 * together imply that ender will be set last.
245 			 */
246 			break;
247 		}
248 
249 		for (i = 1, x = begin; i <= reps || infinity; i++, x += step)
250 			if (putdata(x, reps == i && !infinity))
251 				errx(1, "range error in conversion: %f", x);
252 	} else { /* Random output: use defaults for omitted values. */
253 		bool		use_unif = 0;
254 		uint32_t	pow10 = 1;
255 		uint32_t	uintx = 0; /* Initialized to make gcc happy. */
256 
257 		if (prec > 9)	/* pow(10, prec) > UINT32_MAX */
258 			errx(1, "requested precision too large");
259 
260 		if (ender < begin) {
261 			x = begin;
262 			begin = ender;
263 			ender = x;
264 		}
265 		x = ender - begin;
266 
267 		if (prec > 0 || (fmod(ender, 1) == 0 && fmod(begin, 1) == 0)) {
268 			double range;
269 
270 			while (prec-- > 0)
271 				pow10 *= 10;
272 
273 			range = pow10 * (ender - begin);
274 
275 			/* If range is an integer, use arc4random_uniform(). */
276 			if (fmod(range, 1) == 0) {
277 				if (range >= UINT32_MAX)
278 					errx(1, "requested range too large");
279 				use_unif = 1;
280 				uintx = range + 1;
281 			}
282 		}
283 
284 		for (i = 1; i <= reps || infinity; i++) {
285 			double v;
286 
287 			if (use_unif) {
288 				y = arc4random_uniform(uintx) / (double)pow10;
289 				v = y + begin;
290 			} else {
291 				y = arc4random() / ((double)0xffffffff + 1);
292 				v = y * x + begin;
293 			}
294 			if (putdata(v, reps == i && !infinity))
295 				errx(1, "range error in conversion: %f", v);
296 		}
297 	}
298 
299 	if (finalnl)
300 		putchar('\n');
301 
302 	return 0;
303 }
304 
305 static int
putdata(double x,bool last)306 putdata(double x, bool last)
307 {
308 	if (boring)
309 		printf("%s", format);
310 	else if (longdata && nosign) {
311 		if (x < 0.0 || x > (double)ULONG_MAX)
312 			return 1;
313 		printf(format, (unsigned long)x);
314 	} else if (longdata) {
315 		if (x < (double)LONG_MIN || x > (double)LONG_MAX)
316 			return 1;
317 		printf(format, (long)x);
318 	} else if (chardata || (intdata && !nosign)) {
319 		if (x < (double)INT_MIN || x > (double)INT_MAX)
320 			return 1;
321 		printf(format, (int)x);
322 	} else if (intdata) {
323 		if (x < 0.0 || x > (double)UINT_MAX)
324 			return 1;
325 		printf(format, (unsigned int)x);
326 	} else
327 		printf(format, x);
328 	if (!last)
329 		fputs(sepstring, stdout);
330 
331 	return 0;
332 }
333 
334 static void __dead
usage(void)335 usage(void)
336 {
337 	(void)fprintf(stderr, "usage: jot [-cnr] [-b word] [-p precision] "
338 	    "[-s string] [-w word]\n"
339 	    "	   [reps [begin [end [step]]]]\n");
340 	exit(1);
341 }
342 
343 static int
getprec(char * s)344 getprec(char *s)
345 {
346 	if ((s = strchr(s, '.')) == NULL)
347 		return 0;
348 	return strspn(s + 1, "0123456789");
349 }
350 
351 static void
getformat(void)352 getformat(void)
353 {
354 	char	*p;
355 
356 	p = format;
357 	while ((p = strchr(p, '%')) != NULL && p[1] == '%')
358 		p += 2;
359 
360 	if (p == NULL && !chardata) {
361 		if (asprintf(&format, "%s%%.%df", format, prec) == -1)
362 			err(1, NULL);
363 	} else if (p == NULL && chardata) {
364 		if (asprintf(&format, "%s%%c", format) == -1)
365 			err(1, NULL);
366 	} else if (p[1] == '\0') {
367 		/* cannot end in single '%' */
368 		if (asprintf(&format, "%s%%", format) == -1)
369 			err(1, NULL);
370 	} else {
371 		/*
372 		 * Allow conversion format specifiers of the form
373 		 * %[#][ ][{+,-}][0-9]*[.[0-9]*]? where ? must be one of
374 		 * [l]{d,i,o,u,x} or {f,e,g,F,E,G,d,o,x,D,O,U,X,c,u}
375 		 */
376 		char	*fmt;
377 		int	dot, hash, space, sign, numbers;
378 
379 		fmt = p++;
380 		dot = hash = space = sign = numbers = 0;
381 		while (!isalpha((unsigned char)*p)) {
382 			if (isdigit((unsigned char)*p)) {
383 				numbers++;
384 				p++;
385 			} else if ((*p == '#' && !(numbers|dot|sign|space|
386 			    hash++)) ||
387 			    (*p == ' ' && !(numbers|dot|space++)) ||
388 			    ((*p == '+' || *p == '-') && !(numbers|dot|sign++))
389 			    || (*p == '.' && !(dot++)))
390 				p++;
391 			else
392 				goto fmt_broken;
393 		}
394 		if (*p == 'l') {
395 			longdata = true;
396 			if (*++p == 'l') {
397 				p++;
398 				goto fmt_broken;
399 			}
400 		}
401 		switch (*p) {
402 		case 'd':
403 		case 'i':
404 			intdata = true;
405 			break;
406 		case 'o':
407 		case 'u':
408 		case 'x':
409 		case 'X':
410 			intdata = nosign = true;
411 			break;
412 		case 'D':
413 			if (longdata)
414 				goto fmt_broken;
415 			longdata = intdata = true; /* same as %ld */
416 			break;
417 		case 'O':
418 		case 'U':
419 			if (longdata)
420 				goto fmt_broken;
421 			longdata = intdata = nosign = true; /* same as %l[ou] */
422 			break;
423 		case 'c':
424 			if (longdata)
425 				goto fmt_broken;
426 			chardata = true;
427 			break;
428 		case 'e':
429 		case 'E':
430 		case 'f':
431 		case 'F':
432 		case 'g':
433 		case 'G':
434 			if (longdata)
435 				goto fmt_broken;
436 			/* No cast needed for printing in putdata() */
437 			break;
438 		default:
439 fmt_broken:
440 			errx(1, "illegal or unsupported format '%.*s'",
441 			    (int)(p + 1 - fmt), fmt);
442 		}
443 
444 		while ((p = strchr(p, '%')) != NULL && p[1] == '%')
445 			p += 2;
446 
447 		if (p != NULL) {
448 			if (p[1] != '\0')
449 				errx(1, "too many conversions");
450 			/* cannot end in single '%' */
451 			if (asprintf(&format, "%s%%", format) == -1)
452 				err(1, NULL);
453 		}
454 	}
455 }
456