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