1 /* $OpenBSD: fmt_scaled.c,v 1.2 2003/12/27 19:49:51 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.2 2003/12/27 19:49:51 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 continue; /* ignore extra fractional digits */ 130 fract_digits++; /* for later scaling */ 131 fpart *= 10; 132 fpart += i; 133 } else { /* normal digit */ 134 if (++ndigits >= MAX_DIGITS) { 135 errno = ERANGE; 136 return -1; 137 } 138 whole *= 10; 139 whole += i; 140 } 141 } 142 143 if (sign) { 144 whole *= sign; 145 fpart *= sign; 146 } 147 148 /* If no scale factor given, we're done. fraction is discarded. */ 149 if (!*p) { 150 *result = whole; 151 return 0; 152 } 153 154 /* Validate scale factor, and scale whole and fraction by it. */ 155 for (i = 0; i < SCALE_LENGTH; i++) { 156 157 /** Are we there yet? */ 158 if (*p == scale_chars[i] || 159 *p == tolower(scale_chars[i])) { 160 161 /* If it ends with alphanumerics after the scale char, bad. */ 162 if (*(p+1) != '\0' && isalnum(*(p+1))) { 163 errno = EINVAL; 164 return -1; 165 } 166 scale_fact = scale_factors[i]; 167 168 /* scale whole part */ 169 whole *= scale_fact; 170 171 /* truncate fpart so it does't overflow. 172 * then scale fractional part. 173 */ 174 while (fpart >= LLONG_MAX / scale_fact) { 175 fpart /= 10; 176 fract_digits--; 177 } 178 fpart *= scale_fact; 179 if (fract_digits > 0) { 180 for (i = 0; i < fract_digits -1; i++) 181 fpart /= 10; 182 } 183 whole += fpart; 184 *result = whole; 185 return 0; 186 } 187 } 188 errno = ERANGE; 189 return -1; 190 } 191 192 /* Format the given "number" into human-readable form in "result". 193 * Result must point to an allocated buffer of length FMT_SCALED_STRSIZE. 194 * Return 0 on success, -1 and errno set if error. 195 */ 196 int 197 fmt_scaled(long long number, char *result) 198 { 199 long long abval, fract = 0; 200 unsigned int i; 201 unit_type unit = NONE; 202 203 if (result == NULL) { 204 errno = EFAULT; 205 return -1; 206 } 207 208 abval = (number < 0LL) ? -number : number; /* no long long_abs yet */ 209 210 /* Not every negative long long has a positive representation. 211 * Also check for numbers that are just too darned big to format 212 */ 213 if (abval < 0 || abval / 1024 >= scale_factors[SCALE_LENGTH-1]) { 214 errno = ERANGE; 215 return -1; 216 } 217 218 /* scale whole part; get unscaled fraction */ 219 for (i = 0; i < SCALE_LENGTH; i++) { 220 if (abval/1024 < scale_factors[i]) { 221 unit = units[i]; 222 fract = (i == 0) ? 0 : abval % scale_factors[i]; 223 number /= scale_factors[i]; 224 break; 225 } 226 } 227 228 /* scale fraction to one digit (by rounding) - thnx pjanzen */ 229 for (i = SCALE_LENGTH-1; i > 0; i--) { 230 if (fract > scale_factors[i]) { 231 fract /= scale_factors[i]; 232 break; 233 } 234 } 235 fract = (10 * fract + 512) / 1024; 236 /* if the result would be >= 10, round main number */ 237 if (fract == 10) { 238 if (number >= 0) 239 number++; 240 else 241 number--; 242 fract = 0; 243 } 244 245 if (number == 0) 246 strlcpy(result, "0B", FMT_SCALED_STRSIZE); 247 else if (unit == NONE || number >= 100 || number <= -100) 248 (void)snprintf(result, FMT_SCALED_STRSIZE, "%lld%c", 249 number, scale_chars[unit]); 250 else 251 (void)snprintf(result, FMT_SCALED_STRSIZE, "%lld.%1lld%c", 252 number, fract, scale_chars[unit]); 253 254 return 0; 255 } 256 257 #ifdef MAIN 258 /* 259 * This is the original version of the program in the man page. 260 * Copy-and-paste whatever you need from it. 261 */ 262 int 263 main(int argc, char **argv) 264 { 265 char *cinput = "1.5K", buf[FMT_SCALED_STRSIZE]; 266 long long ninput = 10483892, result; 267 268 if (scan_scaled(cinput, &result) == 0) 269 printf("\"%s\" -> %lld\n", cinput, result); 270 else 271 perror(cinput); 272 273 if (fmt_scaled(ninput, buf) == 0) 274 printf("%lld -> \"%s\"\n", ninput, buf); 275 else 276 fprintf(stderr, "%lld invalid (%s)\n", ninput, strerror(errno)); 277 278 return 0; 279 } 280 #endif 281