1 /* $OpenBSD: fmt_scaled.c,v 1.4 2004/09/16 10:56:35 otto 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 #if defined(LIBC_SCCS) && !defined(lint) 40 static const char ident[] = "$OpenBSD: fmt_scaled.c,v 1.4 2004/09/16 10:56:35 otto Exp $"; 41 #endif /* LIBC_SCCS and not lint */ 42 43 #include <stdio.h> 44 #include <stdlib.h> 45 #include <errno.h> 46 #include <string.h> 47 #include <ctype.h> 48 #include <limits.h> 49 50 #include "util.h" 51 52 typedef enum { 53 NONE = 0, KILO = 1, MEGA = 2, GIGA = 3, TERA = 4, PETA = 5, EXA = 6 54 } unit_type; 55 56 /* These three arrays MUST be in sync! XXX make a struct */ 57 static unit_type units[] = { NONE, KILO, MEGA, GIGA, TERA, PETA, EXA }; 58 static char scale_chars[] = "BKMGTPE"; 59 static long long scale_factors[] = { 60 1LL, 61 1024LL, 62 1024LL*1024, 63 1024LL*1024*1024, 64 1024LL*1024*1024*1024, 65 1024LL*1024*1024*1024*1024, 66 1024LL*1024*1024*1024*1024*1024, 67 }; 68 #define SCALE_LENGTH (sizeof(units)/sizeof(units[0])) 69 70 #define MAX_DIGITS (SCALE_LENGTH * 3) /* XXX strlen(sprintf("%lld", -1)? */ 71 72 /** Convert the given input string "scaled" into numeric in "result". 73 * Return 0 on success, -1 and errno set on error. 74 */ 75 int 76 scan_scaled(char *scaled, long long *result) 77 { 78 char *p = scaled; 79 int sign = 0; 80 unsigned int i, ndigits = 0, fract_digits = 0; 81 long long scale_fact = 1, whole = 0, fpart = 0; 82 83 if (p == NULL || result == NULL) { 84 errno = EFAULT; 85 return -1; 86 } 87 88 /* Skip leading whitespace */ 89 while (*p && isascii(*p) && isspace(*p)) 90 ++p; 91 92 /* Then at most one leading + or - */ 93 while (*p == '-' || *p == '+') { 94 if (*p == '-') { 95 if (sign) { 96 errno = EINVAL; 97 return -1; 98 } 99 sign = -1; 100 ++p; 101 } else if (*p == '+') { 102 if (sign) { 103 errno = EINVAL; 104 return -1; 105 } 106 sign = +1; 107 ++p; 108 } 109 } 110 111 /* Main loop: Scan digits, find decimal point, if present. 112 * We don't allow exponentials, so no scientific notation 113 * (but note that E for Exa might look like e to some!). 114 * Advance 'p' to end, to get scale factor. 115 */ 116 for (; *p && isascii(*p) && (isdigit(*p) || *p=='.'); ++p) { 117 if (*p == '.') { 118 if (fract_digits > 0) { /* oops, more than one '.' */ 119 errno = EINVAL; 120 return -1; 121 } 122 fract_digits = 1; 123 continue; 124 } 125 126 i = (*p) - '0'; /* whew! finally a digit we can use */ 127 if (fract_digits > 0) { 128 if (fract_digits >= MAX_DIGITS-1) 129 /* ignore extra fractional digits */ 130 continue; 131 fract_digits++; /* for later scaling */ 132 fpart *= 10; 133 fpart += i; 134 } else { /* normal digit */ 135 if (++ndigits >= MAX_DIGITS) { 136 errno = ERANGE; 137 return -1; 138 } 139 whole *= 10; 140 whole += i; 141 } 142 } 143 144 if (sign) { 145 whole *= sign; 146 fpart *= sign; 147 } 148 149 /* If no scale factor given, we're done. fraction is discarded. */ 150 if (!*p) { 151 *result = whole; 152 return 0; 153 } 154 155 /* Validate scale factor, and scale whole and fraction by it. */ 156 for (i = 0; i < SCALE_LENGTH; i++) { 157 158 /** Are we there yet? */ 159 if (*p == scale_chars[i] || 160 *p == tolower(scale_chars[i])) { 161 162 /* If it ends with alphanumerics after the scale char, bad. */ 163 if (*(p+1) != '\0' && isalnum(*(p+1))) { 164 errno = EINVAL; 165 return -1; 166 } 167 scale_fact = scale_factors[i]; 168 169 /* scale whole part */ 170 whole *= scale_fact; 171 172 /* truncate fpart so it does't overflow. 173 * then scale fractional part. 174 */ 175 while (fpart >= LLONG_MAX / scale_fact) { 176 fpart /= 10; 177 fract_digits--; 178 } 179 fpart *= scale_fact; 180 if (fract_digits > 0) { 181 for (i = 0; i < fract_digits -1; i++) 182 fpart /= 10; 183 } 184 whole += fpart; 185 *result = whole; 186 return 0; 187 } 188 } 189 errno = ERANGE; 190 return -1; 191 } 192 193 /* Format the given "number" into human-readable form in "result". 194 * Result must point to an allocated buffer of length FMT_SCALED_STRSIZE. 195 * Return 0 on success, -1 and errno set if error. 196 */ 197 int 198 fmt_scaled(long long number, char *result) 199 { 200 long long abval, fract = 0; 201 unsigned int i; 202 unit_type unit = NONE; 203 204 if (result == NULL) { 205 errno = EFAULT; 206 return -1; 207 } 208 209 abval = (number < 0LL) ? -number : number; /* no long long_abs yet */ 210 211 /* Not every negative long long has a positive representation. 212 * Also check for numbers that are just too darned big to format 213 */ 214 if (abval < 0 || abval / 1024 >= scale_factors[SCALE_LENGTH-1]) { 215 errno = ERANGE; 216 return -1; 217 } 218 219 /* scale whole part; get unscaled fraction */ 220 for (i = 0; i < SCALE_LENGTH; i++) { 221 if (abval/1024 < scale_factors[i]) { 222 unit = units[i]; 223 fract = (i == 0) ? 0 : abval % scale_factors[i]; 224 number /= scale_factors[i]; 225 break; 226 } 227 } 228 229 /* scale fraction to one digit (by rounding) - thnx pjanzen */ 230 for (i = SCALE_LENGTH-1; i > 0; i--) { 231 if (fract >= scale_factors[i]) { 232 fract /= scale_factors[i]; 233 break; 234 } 235 } 236 fract = (10 * fract + 512) / 1024; 237 /* if the result would be >= 10, round main number */ 238 if (fract == 10) { 239 if (number >= 0) 240 number++; 241 else 242 number--; 243 fract = 0; 244 } 245 246 if (number == 0) 247 strlcpy(result, "0B", FMT_SCALED_STRSIZE); 248 else if (unit == NONE || number >= 100 || number <= -100) 249 (void)snprintf(result, FMT_SCALED_STRSIZE, "%lld%c", 250 number, scale_chars[unit]); 251 else 252 (void)snprintf(result, FMT_SCALED_STRSIZE, "%lld.%1lld%c", 253 number, fract, scale_chars[unit]); 254 255 return 0; 256 } 257 258 #ifdef MAIN 259 /* 260 * This is the original version of the program in the man page. 261 * Copy-and-paste whatever you need from it. 262 */ 263 int 264 main(int argc, char **argv) 265 { 266 char *cinput = "1.5K", buf[FMT_SCALED_STRSIZE]; 267 long long ninput = 10483892, result; 268 269 if (scan_scaled(cinput, &result) == 0) 270 printf("\"%s\" -> %lld\n", cinput, result); 271 else 272 perror(cinput); 273 274 if (fmt_scaled(ninput, buf) == 0) 275 printf("%lld -> \"%s\"\n", ninput, buf); 276 else 277 fprintf(stderr, "%lld invalid (%s)\n", ninput, strerror(errno)); 278 279 return 0; 280 } 281 #endif 282