From 7aaf3f36f86dc2c17ec1e86c77b1790d706d41bd Mon Sep 17 00:00:00 2001 From: Rob Landley Date: Sat, 1 Jan 2022 13:32:33 -0600 Subject: [PATCH] Teach sort -h to handle decimals. (Didn't want to tangle it into the "isinf/nan" stuff with -g, but forgot to actually add the decimal part.) --- tests/sort.test | 2 ++ toys/posix/sort.c | 9 ++++++--- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/tests/sort.test b/tests/sort.test index 1d9ecc44..d3af4e61 100755 --- a/tests/sort.test +++ b/tests/sort.test @@ -119,3 +119,5 @@ testcmd '-u implies -s' '-uk2,2n' 'zero 1\nthree 2\nfour 3\n' '' \ 'zero 1\none 1\nfour 3\ntwo 1\nthree 2\nalso 1' testcmd '-h' '-h' '1bx\n1by\n1x\n1x\n1y\n1Ky\n1Ky\n1ky\n1My\n1Gx\n1Gx\n' '' \ '1bx\n1y\n1by\n1x\n1ky\n1x\n1Ky\n1Gx\n1Ky\n1Gx\n1My' +testcmd '-h2' '-h' '9\n2K\n320K\n1.000071M\n1.000073M\n2.6M\n' '' \ + '320K\n2.6M\n9\n1.000073M\n2K\n1.000071M' diff --git a/toys/posix/sort.c b/toys/posix/sort.c index 574063ea..cedf9269 100644 --- a/toys/posix/sort.c +++ b/toys/posix/sort.c @@ -231,13 +231,16 @@ static int compare_values(int flags, char *x, char *y) // Full floating point version of -n if (CFG_SORT_FLOAT) { char *xx = x, *units = "kmgtpez"; - double dxy[2]; + double dxy[2], zz = 1; int i = 0; do { dxy[i] = estrtol(xx, &xx, 0); if (flags & FLAG_h) { - if (isspace(*xx)) xx++; + if (*xx=='.') { + xx++; + while (isdigit(*xx)) dxy[i] += ((*xx++)-'0')*(zz/=10); + } if (*xx && (xx = strchr(units, tolower(*xx)))) do dxy[i] *= 1024; while (xx-->units); } @@ -245,7 +248,7 @@ static int compare_values(int flags, char *x, char *y) } while (!i++); return dxy[0]dxy[1]; - // Integer version of -n for tiny systems + // Integer version of -n for tiny systems. (qsort needs int return not long) } else return atoi(x)-atoi(y); // Ascii sort -- 2.39.2