-/* $OpenBSD: fmt_scaled.c,v 1.17 2018/05/14 04:39:04 djm Exp $ */
+/* $OpenBSD: fmt_scaled.c,v 1.21 2022/03/11 07:29:53 dtucker Exp $ */
/*
* Copyright (c) 2001, 2002, 2003 Ian F. Darwin. All rights reserved.
} unit_type;
/* These three arrays MUST be in sync! XXX make a struct */
-static unit_type units[] = { NONE, KILO, MEGA, GIGA, TERA, PETA, EXA };
-static char scale_chars[] = "BKMGTPE";
-static long long scale_factors[] = {
+static const unit_type units[] = { NONE, KILO, MEGA, GIGA, TERA, PETA, EXA };
+static const char scale_chars[] = "BKMGTPE";
+static const long long scale_factors[] = {
1LL,
1024LL,
1024LL*1024,
}
}
- if (sign) {
+ if (sign)
whole *= sign;
- fpart *= sign;
- }
/* If no scale factor given, we're done. fraction is discarded. */
if (!*p) {
/* truncate fpart so it doesn't overflow.
* then scale fractional part.
*/
- while (fpart >= LLONG_MAX / scale_fact) {
+ while (fpart >= LLONG_MAX / scale_fact ||
+ fpart <= LLONG_MIN / scale_fact) {
fpart /= 10;
fract_digits--;
}
for (i = 0; i < fract_digits -1; i++)
fpart /= 10;
}
- whole += fpart;
+ if (sign == -1)
+ whole -= fpart;
+ else
+ whole += fpart;
*result = whole;
return 0;
}
unsigned int i;
unit_type unit = NONE;
+ /* Not every negative long long has a positive representation. */
+ if (number == LLONG_MIN) {
+ errno = ERANGE;
+ return -1;
+ }
+
abval = llabs(number);
- /* Not every negative long long has a positive representation.
- * Also check for numbers that are just too darned big to format
- */
- if (abval < 0 || abval / 1024 >= scale_factors[SCALE_LENGTH-1]) {
+ /* Also check for numbers that are just too darned big to format. */
+ if (abval / 1024 >= scale_factors[SCALE_LENGTH-1]) {
errno = ERANGE;
return -1;
}