1180750Sdes/*	$OpenBSD: fmt_scaled.c,v 1.9 2007/03/20 03:42:52 tedu Exp $	*/
2180750Sdes
3180750Sdes/*
4180750Sdes * Copyright (c) 2001, 2002, 2003 Ian F. Darwin.  All rights reserved.
5180750Sdes *
6180750Sdes * Redistribution and use in source and binary forms, with or without
7180750Sdes * modification, are permitted provided that the following conditions
8180750Sdes * are met:
9180750Sdes * 1. Redistributions of source code must retain the above copyright
10180750Sdes *    notice, this list of conditions and the following disclaimer.
11180750Sdes * 2. Redistributions in binary form must reproduce the above copyright
12180750Sdes *    notice, this list of conditions and the following disclaimer in the
13180750Sdes *    documentation and/or other materials provided with the distribution.
14180750Sdes * 3. The name of the author may not be used to endorse or promote products
15180750Sdes *    derived from this software without specific prior written permission.
16180750Sdes *
17180750Sdes * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18180750Sdes * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19180750Sdes * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20180750Sdes * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21180750Sdes * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22180750Sdes * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23180750Sdes * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24180750Sdes * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25180750Sdes * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26180750Sdes * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27180750Sdes */
28180750Sdes
29180750Sdes/* OPENBSD ORIGINAL: lib/libutil/fmt_scaled.c */
30180750Sdes
31180750Sdes/*
32180750Sdes * fmt_scaled: Format numbers scaled for human comprehension
33180750Sdes * scan_scaled: Scan numbers in this format.
34180750Sdes *
35180750Sdes * "Human-readable" output uses 4 digits max, and puts a unit suffix at
36180750Sdes * the end.  Makes output compact and easy-to-read esp. on huge disks.
37180750Sdes * Formatting code was originally in OpenBSD "df", converted to library routine.
38180750Sdes * Scanning code written for OpenBSD libutil.
39180750Sdes */
40180750Sdes
41180750Sdes#include "includes.h"
42180750Sdes
43180750Sdes#ifndef HAVE_FMT_SCALED
44180750Sdes
45180750Sdes#include <stdio.h>
46180750Sdes#include <stdlib.h>
47180750Sdes#include <errno.h>
48180750Sdes#include <string.h>
49180750Sdes#include <ctype.h>
50180750Sdes#include <limits.h>
51180750Sdes
52180750Sdestypedef enum {
53180750Sdes	NONE = 0, KILO = 1, MEGA = 2, GIGA = 3, TERA = 4, PETA = 5, EXA = 6
54180750Sdes} unit_type;
55180750Sdes
56180750Sdes/* These three arrays MUST be in sync!  XXX make a struct */
57180750Sdesstatic unit_type units[] = { NONE, KILO, MEGA, GIGA, TERA, PETA, EXA };
58180750Sdesstatic char scale_chars[] = "BKMGTPE";
59180750Sdesstatic long long scale_factors[] = {
60180750Sdes	1LL,
61180750Sdes	1024LL,
62180750Sdes	1024LL*1024,
63180750Sdes	1024LL*1024*1024,
64180750Sdes	1024LL*1024*1024*1024,
65180750Sdes	1024LL*1024*1024*1024*1024,
66180750Sdes	1024LL*1024*1024*1024*1024*1024,
67180750Sdes};
68180750Sdes#define	SCALE_LENGTH (sizeof(units)/sizeof(units[0]))
69180750Sdes
70180750Sdes#define MAX_DIGITS (SCALE_LENGTH * 3)	/* XXX strlen(sprintf("%lld", -1)? */
71180750Sdes
72180750Sdes/** Convert the given input string "scaled" into numeric in "result".
73180750Sdes * Return 0 on success, -1 and errno set on error.
74180750Sdes */
75180750Sdesint
76180750Sdesscan_scaled(char *scaled, long long *result)
77180750Sdes{
78180750Sdes	char *p = scaled;
79180750Sdes	int sign = 0;
80180750Sdes	unsigned int i, ndigits = 0, fract_digits = 0;
81180750Sdes	long long scale_fact = 1, whole = 0, fpart = 0;
82180750Sdes
83180750Sdes	/* Skip leading whitespace */
84180750Sdes	while (isascii(*p) && isspace(*p))
85180750Sdes		++p;
86180750Sdes
87180750Sdes	/* Then at most one leading + or - */
88180750Sdes	while (*p == '-' || *p == '+') {
89180750Sdes		if (*p == '-') {
90180750Sdes			if (sign) {
91180750Sdes				errno = EINVAL;
92180750Sdes				return -1;
93180750Sdes			}
94180750Sdes			sign = -1;
95180750Sdes			++p;
96180750Sdes		} else if (*p == '+') {
97180750Sdes			if (sign) {
98180750Sdes				errno = EINVAL;
99180750Sdes				return -1;
100180750Sdes			}
101180750Sdes			sign = +1;
102180750Sdes			++p;
103180750Sdes		}
104180750Sdes	}
105180750Sdes
106180750Sdes	/* Main loop: Scan digits, find decimal point, if present.
107180750Sdes	 * We don't allow exponentials, so no scientific notation
108180750Sdes	 * (but note that E for Exa might look like e to some!).
109180750Sdes	 * Advance 'p' to end, to get scale factor.
110180750Sdes	 */
111180750Sdes	for (; isascii(*p) && (isdigit(*p) || *p=='.'); ++p) {
112180750Sdes		if (*p == '.') {
113180750Sdes			if (fract_digits > 0) {	/* oops, more than one '.' */
114180750Sdes				errno = EINVAL;
115180750Sdes				return -1;
116180750Sdes			}
117180750Sdes			fract_digits = 1;
118180750Sdes			continue;
119180750Sdes		}
120180750Sdes
121180750Sdes		i = (*p) - '0';			/* whew! finally a digit we can use */
122180750Sdes		if (fract_digits > 0) {
123180750Sdes			if (fract_digits >= MAX_DIGITS-1)
124180750Sdes				/* ignore extra fractional digits */
125180750Sdes				continue;
126180750Sdes			fract_digits++;		/* for later scaling */
127180750Sdes			fpart *= 10;
128180750Sdes			fpart += i;
129180750Sdes		} else {				/* normal digit */
130180750Sdes			if (++ndigits >= MAX_DIGITS) {
131180750Sdes				errno = ERANGE;
132180750Sdes				return -1;
133180750Sdes			}
134180750Sdes			whole *= 10;
135180750Sdes			whole += i;
136180750Sdes		}
137180750Sdes	}
138180750Sdes
139180750Sdes	if (sign) {
140180750Sdes		whole *= sign;
141180750Sdes		fpart *= sign;
142180750Sdes	}
143180750Sdes
144180750Sdes	/* If no scale factor given, we're done. fraction is discarded. */
145180750Sdes	if (!*p) {
146180750Sdes		*result = whole;
147180750Sdes		return 0;
148180750Sdes	}
149180750Sdes
150180750Sdes	/* Validate scale factor, and scale whole and fraction by it. */
151180750Sdes	for (i = 0; i < SCALE_LENGTH; i++) {
152180750Sdes
153180750Sdes		/** Are we there yet? */
154180750Sdes		if (*p == scale_chars[i] ||
155180750Sdes			*p == tolower(scale_chars[i])) {
156180750Sdes
157180750Sdes			/* If it ends with alphanumerics after the scale char, bad. */
158180750Sdes			if (isalnum(*(p+1))) {
159180750Sdes				errno = EINVAL;
160180750Sdes				return -1;
161180750Sdes			}
162180750Sdes			scale_fact = scale_factors[i];
163180750Sdes
164180750Sdes			/* scale whole part */
165180750Sdes			whole *= scale_fact;
166180750Sdes
167180750Sdes			/* truncate fpart so it does't overflow.
168180750Sdes			 * then scale fractional part.
169180750Sdes			 */
170180750Sdes			while (fpart >= LLONG_MAX / scale_fact) {
171180750Sdes				fpart /= 10;
172180750Sdes				fract_digits--;
173180750Sdes			}
174180750Sdes			fpart *= scale_fact;
175180750Sdes			if (fract_digits > 0) {
176180750Sdes				for (i = 0; i < fract_digits -1; i++)
177180750Sdes					fpart /= 10;
178180750Sdes			}
179180750Sdes			whole += fpart;
180180750Sdes			*result = whole;
181180750Sdes			return 0;
182180750Sdes		}
183180750Sdes	}
184180750Sdes	errno = ERANGE;
185180750Sdes	return -1;
186180750Sdes}
187180750Sdes
188180750Sdes/* Format the given "number" into human-readable form in "result".
189180750Sdes * Result must point to an allocated buffer of length FMT_SCALED_STRSIZE.
190180750Sdes * Return 0 on success, -1 and errno set if error.
191180750Sdes */
192180750Sdesint
193180750Sdesfmt_scaled(long long number, char *result)
194180750Sdes{
195180750Sdes	long long abval, fract = 0;
196180750Sdes	unsigned int i;
197180750Sdes	unit_type unit = NONE;
198180750Sdes
199180750Sdes	abval = (number < 0LL) ? -number : number;	/* no long long_abs yet */
200180750Sdes
201180750Sdes	/* Not every negative long long has a positive representation.
202180750Sdes	 * Also check for numbers that are just too darned big to format
203180750Sdes	 */
204180750Sdes	if (abval < 0 || abval / 1024 >= scale_factors[SCALE_LENGTH-1]) {
205180750Sdes		errno = ERANGE;
206180750Sdes		return -1;
207180750Sdes	}
208180750Sdes
209180750Sdes	/* scale whole part; get unscaled fraction */
210180750Sdes	for (i = 0; i < SCALE_LENGTH; i++) {
211180750Sdes		if (abval/1024 < scale_factors[i]) {
212180750Sdes			unit = units[i];
213180750Sdes			fract = (i == 0) ? 0 : abval % scale_factors[i];
214180750Sdes			number /= scale_factors[i];
215180750Sdes			if (i > 0)
216180750Sdes				fract /= scale_factors[i - 1];
217180750Sdes			break;
218180750Sdes		}
219180750Sdes	}
220180750Sdes
221180750Sdes	fract = (10 * fract + 512) / 1024;
222180750Sdes	/* if the result would be >= 10, round main number */
223180750Sdes	if (fract == 10) {
224180750Sdes		if (number >= 0)
225180750Sdes			number++;
226180750Sdes		else
227180750Sdes			number--;
228180750Sdes		fract = 0;
229180750Sdes	}
230180750Sdes
231180750Sdes	if (number == 0)
232180750Sdes		strlcpy(result, "0B", FMT_SCALED_STRSIZE);
233180750Sdes	else if (unit == NONE || number >= 100 || number <= -100) {
234180750Sdes		if (fract >= 5) {
235180750Sdes			if (number >= 0)
236180750Sdes				number++;
237180750Sdes			else
238180750Sdes				number--;
239180750Sdes		}
240180750Sdes		(void)snprintf(result, FMT_SCALED_STRSIZE, "%lld%c",
241180750Sdes			number, scale_chars[unit]);
242180750Sdes	} else
243180750Sdes		(void)snprintf(result, FMT_SCALED_STRSIZE, "%lld.%1lld%c",
244180750Sdes			number, fract, scale_chars[unit]);
245180750Sdes
246180750Sdes	return 0;
247180750Sdes}
248180750Sdes
249180750Sdes#ifdef	MAIN
250180750Sdes/*
251180750Sdes * This is the original version of the program in the man page.
252180750Sdes * Copy-and-paste whatever you need from it.
253180750Sdes */
254180750Sdesint
255180750Sdesmain(int argc, char **argv)
256180750Sdes{
257180750Sdes	char *cinput = "1.5K", buf[FMT_SCALED_STRSIZE];
258180750Sdes	long long ninput = 10483892, result;
259180750Sdes
260180750Sdes	if (scan_scaled(cinput, &result) == 0)
261180750Sdes		printf("\"%s\" -> %lld\n", cinput, result);
262180750Sdes	else
263180750Sdes		perror(cinput);
264180750Sdes
265180750Sdes	if (fmt_scaled(ninput, buf) == 0)
266180750Sdes		printf("%lld -> \"%s\"\n", ninput, buf);
267180750Sdes	else
268180750Sdes		fprintf(stderr, "%lld invalid (%s)\n", ninput, strerror(errno));
269180750Sdes
270180750Sdes	return 0;
271180750Sdes}
272180750Sdes#endif
273180750Sdes
274180750Sdes#endif /* HAVE_FMT_SCALED */
275