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