xref: /openbsd/lib/libutil/fmt_scaled.c (revision 3cab2bb3)
1 /*	$OpenBSD: fmt_scaled.c,v 1.18 2019/01/14 23:52:06 bluhm Exp $	*/
2 
3 /*
4  * Copyright (c) 2001, 2002, 2003 Ian F. Darwin.  All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  * 3. The name of the author may not be used to endorse or promote products
15  *    derived from this software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  */
28 
29 /*
30  * fmt_scaled: Format numbers scaled for human comprehension
31  * scan_scaled: Scan numbers in this format.
32  *
33  * "Human-readable" output uses 4 digits max, and puts a unit suffix at
34  * the end.  Makes output compact and easy-to-read esp. on huge disks.
35  * Formatting code was originally in OpenBSD "df", converted to library routine.
36  * Scanning code written for OpenBSD libutil.
37  */
38 
39 #include <stdio.h>
40 #include <stdlib.h>
41 #include <errno.h>
42 #include <string.h>
43 #include <ctype.h>
44 #include <limits.h>
45 
46 #include "util.h"
47 
48 typedef enum {
49 	NONE = 0, KILO = 1, MEGA = 2, GIGA = 3, TERA = 4, PETA = 5, EXA = 6
50 } unit_type;
51 
52 /* These three arrays MUST be in sync!  XXX make a struct */
53 static unit_type units[] = { NONE, KILO, MEGA, GIGA, TERA, PETA, EXA };
54 static char scale_chars[] = "BKMGTPE";
55 static long long scale_factors[] = {
56 	1LL,
57 	1024LL,
58 	1024LL*1024,
59 	1024LL*1024*1024,
60 	1024LL*1024*1024*1024,
61 	1024LL*1024*1024*1024*1024,
62 	1024LL*1024*1024*1024*1024*1024,
63 };
64 #define	SCALE_LENGTH (sizeof(units)/sizeof(units[0]))
65 
66 #define MAX_DIGITS (SCALE_LENGTH * 3)	/* XXX strlen(sprintf("%lld", -1)? */
67 
68 /* Convert the given input string "scaled" into numeric in "result".
69  * Return 0 on success, -1 and errno set on error.
70  */
71 int
72 scan_scaled(char *scaled, long long *result)
73 {
74 	char *p = scaled;
75 	int sign = 0;
76 	unsigned int i, ndigits = 0, fract_digits = 0;
77 	long long scale_fact = 1, whole = 0, fpart = 0;
78 
79 	/* Skip leading whitespace */
80 	while (isascii((unsigned char)*p) && isspace((unsigned char)*p))
81 		++p;
82 
83 	/* Then at most one leading + or - */
84 	while (*p == '-' || *p == '+') {
85 		if (*p == '-') {
86 			if (sign) {
87 				errno = EINVAL;
88 				return -1;
89 			}
90 			sign = -1;
91 			++p;
92 		} else if (*p == '+') {
93 			if (sign) {
94 				errno = EINVAL;
95 				return -1;
96 			}
97 			sign = +1;
98 			++p;
99 		}
100 	}
101 
102 	/* Main loop: Scan digits, find decimal point, if present.
103 	 * We don't allow exponentials, so no scientific notation
104 	 * (but note that E for Exa might look like e to some!).
105 	 * Advance 'p' to end, to get scale factor.
106 	 */
107 	for (; isascii((unsigned char)*p) &&
108 	    (isdigit((unsigned char)*p) || *p=='.'); ++p) {
109 		if (*p == '.') {
110 			if (fract_digits > 0) {	/* oops, more than one '.' */
111 				errno = EINVAL;
112 				return -1;
113 			}
114 			fract_digits = 1;
115 			continue;
116 		}
117 
118 		i = (*p) - '0';			/* whew! finally a digit we can use */
119 		if (fract_digits > 0) {
120 			if (fract_digits >= MAX_DIGITS-1)
121 				/* ignore extra fractional digits */
122 				continue;
123 			fract_digits++;		/* for later scaling */
124 			if (fpart > LLONG_MAX / 10) {
125 				errno = ERANGE;
126 				return -1;
127 			}
128 			fpart *= 10;
129 			if (i > LLONG_MAX - fpart) {
130 				errno = ERANGE;
131 				return -1;
132 			}
133 			fpart += i;
134 		} else {				/* normal digit */
135 			if (++ndigits >= MAX_DIGITS) {
136 				errno = ERANGE;
137 				return -1;
138 			}
139 			if (whole > LLONG_MAX / 10) {
140 				errno = ERANGE;
141 				return -1;
142 			}
143 			whole *= 10;
144 			if (i > LLONG_MAX - whole) {
145 				errno = ERANGE;
146 				return -1;
147 			}
148 			whole += i;
149 		}
150 	}
151 
152 	if (sign) {
153 		whole *= sign;
154 		fpart *= sign;
155 	}
156 
157 	/* If no scale factor given, we're done. fraction is discarded. */
158 	if (!*p) {
159 		*result = whole;
160 		return 0;
161 	}
162 
163 	/* Validate scale factor, and scale whole and fraction by it. */
164 	for (i = 0; i < SCALE_LENGTH; i++) {
165 
166 		/* Are we there yet? */
167 		if (*p == scale_chars[i] ||
168 			*p == tolower((unsigned char)scale_chars[i])) {
169 
170 			/* If it ends with alphanumerics after the scale char, bad. */
171 			if (isalnum((unsigned char)*(p+1))) {
172 				errno = EINVAL;
173 				return -1;
174 			}
175 			scale_fact = scale_factors[i];
176 
177 			/* check for overflow and underflow after scaling */
178 			if (whole > LLONG_MAX / scale_fact ||
179 			    whole < LLONG_MIN / scale_fact) {
180 				errno = ERANGE;
181 				return -1;
182 			}
183 
184 			/* scale whole part */
185 			whole *= scale_fact;
186 
187 			/* truncate fpart so it does't overflow.
188 			 * then scale fractional part.
189 			 */
190 			while (fpart >= LLONG_MAX / scale_fact) {
191 				fpart /= 10;
192 				fract_digits--;
193 			}
194 			fpart *= scale_fact;
195 			if (fract_digits > 0) {
196 				for (i = 0; i < fract_digits -1; i++)
197 					fpart /= 10;
198 			}
199 			whole += fpart;
200 			*result = whole;
201 			return 0;
202 		}
203 	}
204 
205 	/* Invalid unit or character */
206 	errno = EINVAL;
207 	return -1;
208 }
209 
210 /* Format the given "number" into human-readable form in "result".
211  * Result must point to an allocated buffer of length FMT_SCALED_STRSIZE.
212  * Return 0 on success, -1 and errno set if error.
213  */
214 int
215 fmt_scaled(long long number, char *result)
216 {
217 	long long abval, fract = 0;
218 	unsigned int i;
219 	unit_type unit = NONE;
220 
221 	/* Not every negative long long has a positive representation. */
222 	if (number == LLONG_MIN) {
223 		errno = ERANGE;
224 		return -1;
225 	}
226 
227 	abval = llabs(number);
228 
229 	/* Also check for numbers that are just too darned big to format. */
230 	if (abval / 1024 >= scale_factors[SCALE_LENGTH-1]) {
231 		errno = ERANGE;
232 		return -1;
233 	}
234 
235 	/* scale whole part; get unscaled fraction */
236 	for (i = 0; i < SCALE_LENGTH; i++) {
237 		if (abval/1024 < scale_factors[i]) {
238 			unit = units[i];
239 			fract = (i == 0) ? 0 : abval % scale_factors[i];
240 			number /= scale_factors[i];
241 			if (i > 0)
242 				fract /= scale_factors[i - 1];
243 			break;
244 		}
245 	}
246 
247 	fract = (10 * fract + 512) / 1024;
248 	/* if the result would be >= 10, round main number */
249 	if (fract >= 10) {
250 		if (number >= 0)
251 			number++;
252 		else
253 			number--;
254 		fract = 0;
255 	} else if (fract < 0) {
256 		/* shouldn't happen */
257 		fract = 0;
258 	}
259 
260 	if (number == 0)
261 		strlcpy(result, "0B", FMT_SCALED_STRSIZE);
262 	else if (unit == NONE || number >= 100 || number <= -100) {
263 		if (fract >= 5) {
264 			if (number >= 0)
265 				number++;
266 			else
267 				number--;
268 		}
269 		(void)snprintf(result, FMT_SCALED_STRSIZE, "%lld%c",
270 			number, scale_chars[unit]);
271 	} else
272 		(void)snprintf(result, FMT_SCALED_STRSIZE, "%lld.%1lld%c",
273 			number, fract, scale_chars[unit]);
274 
275 	return 0;
276 }
277 
278 #ifdef	MAIN
279 /*
280  * This is the original version of the program in the man page.
281  * Copy-and-paste whatever you need from it.
282  */
283 int
284 main(int argc, char **argv)
285 {
286 	char *cinput = "1.5K", buf[FMT_SCALED_STRSIZE];
287 	long long ninput = 10483892, result;
288 
289 	if (scan_scaled(cinput, &result) == 0)
290 		printf("\"%s\" -> %lld\n", cinput, result);
291 	else
292 		perror(cinput);
293 
294 	if (fmt_scaled(ninput, buf) == 0)
295 		printf("%lld -> \"%s\"\n", ninput, buf);
296 	else
297 		fprintf(stderr, "%lld invalid (%s)\n", ninput, strerror(errno));
298 
299 	return 0;
300 }
301 #endif
302