Blob


1 /* $OpenBSD: fmt_scaled.c,v 1.19 2020/10/12 22:08:34 deraadt Exp $ */
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 */
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 */
39 #include "compat.h"
41 #include <stdio.h>
42 #include <stdlib.h>
43 #include <errno.h>
44 #include <string.h>
45 #include <ctype.h>
46 #include <limits.h>
48 typedef enum {
49 NONE = 0, KILO = 1, MEGA = 2, GIGA = 3, TERA = 4, PETA = 5, EXA = 6
50 } unit_type;
52 /* These three arrays MUST be in sync! XXX make a struct */
53 static const unit_type units[] = { NONE, KILO, MEGA, GIGA, TERA, PETA, EXA };
54 static const char scale_chars[] = "BKMGTPE";
55 static const long long scale_factors[] = {
56 1LL,
57 1024LL,
58 1024LL*1024,
59 1024LL*1024*1024,
60 1024LL*1024*1024*1024,
61 1024LL*1024*1024*1024*1024,
62 1024LL*1024*1024*1024*1024*1024,
63 };
64 #define SCALE_LENGTH (sizeof(units)/sizeof(units[0]))
66 #define MAX_DIGITS (SCALE_LENGTH * 3) /* XXX strlen(sprintf("%lld", -1)? */
68 /* Format the given "number" into human-readable form in "result".
69 * Result must point to an allocated buffer of length FMT_SCALED_STRSIZE.
70 * Return 0 on success, -1 and errno set if error.
71 */
72 int
73 fmt_scaled(long long number, char *result)
74 {
75 long long abval, fract = 0;
76 unsigned int i;
77 unit_type unit = NONE;
79 /* Not every negative long long has a positive representation. */
80 if (number == LLONG_MIN) {
81 errno = ERANGE;
82 return -1;
83 }
85 abval = llabs(number);
87 /* Also check for numbers that are just too darned big to format. */
88 if (abval / 1024 >= scale_factors[SCALE_LENGTH-1]) {
89 errno = ERANGE;
90 return -1;
91 }
93 /* scale whole part; get unscaled fraction */
94 for (i = 0; i < SCALE_LENGTH; i++) {
95 if (abval/1024 < scale_factors[i]) {
96 unit = units[i];
97 fract = (i == 0) ? 0 : abval % scale_factors[i];
98 number /= scale_factors[i];
99 if (i > 0)
100 fract /= scale_factors[i - 1];
101 break;
105 fract = (10 * fract + 512) / 1024;
106 /* if the result would be >= 10, round main number */
107 if (fract >= 10) {
108 if (number >= 0)
109 number++;
110 else
111 number--;
112 fract = 0;
113 } else if (fract < 0) {
114 /* shouldn't happen */
115 fract = 0;
118 if (number == 0)
119 strlcpy(result, "0B", FMT_SCALED_STRSIZE);
120 else if (unit == NONE || number >= 100 || number <= -100) {
121 if (fract >= 5) {
122 if (number >= 0)
123 number++;
124 else
125 number--;
127 (void)snprintf(result, FMT_SCALED_STRSIZE, "%lld%c",
128 number, scale_chars[unit]);
129 } else
130 (void)snprintf(result, FMT_SCALED_STRSIZE, "%lld.%1lld%c",
131 number, fract, scale_chars[unit]);
133 return 0;
136 #ifdef MAIN
137 /*
138 * This is the original version of the program in the man page.
139 * Copy-and-paste whatever you need from it.
140 */
141 int
142 main(int argc, char **argv)
144 char *cinput = "1.5K", buf[FMT_SCALED_STRSIZE];
145 long long ninput = 10483892, result;
147 if (scan_scaled(cinput, &result) == 0)
148 printf("\"%s\" -> %lld\n", cinput, result);
149 else
150 perror(cinput);
152 if (fmt_scaled(ninput, buf) == 0)
153 printf("%lld -> \"%s\"\n", ninput, buf);
154 else
155 fprintf(stderr, "%lld invalid (%s)\n", ninput, strerror(errno));
157 return 0;
159 #endif