Hey, I was looking through the command list and discovered a "count" command.
After learning what it did it reminded me of a tool called pv (Pipe viewer)
which does the exact same thing with more info that I was planning to make
a rudimentary implementation of in toybox.

I want to add a -v[erbose] option that displays info like average input/second
(size/seconds since start) and time since start, Since we are already doing 
stuff
with 'millitime()' to speed up the command, It wouldn't be that much work. But 
it seems
a bit overkill and feature-creep-y for a command that is so simple so I didn't 
include 
one in this patch. I did however add a '-h' Human readable count option.

The only memory that gets accumulated is 'buf' that can be freed easily at the 
end of the command.
I did some memory leak checking on count (calling the main function 10,000 
times and watching
in htop if any memory in being accumulated). Then some more precise checking 
with valgrind.
count now accumulates as much memory as any other (memory-leakless) command in 
toybox 
(80 bytes lost, probably infrastructure stuff but I dunno). And there doesn't 
seem to be a reason not
to MAYFORK it.

Oliver Webb <[email protected]>
From b21ec16c745ea3d6c2a6ebc2bf2ad252d7e295bc Mon Sep 17 00:00:00 2001
From: Oliver Webb <[email protected]>
Date: Sun, 15 Oct 2023 22:18:24 -0500
Subject: [PATCH] count.c: Add MAYFORK and remove memory leak, Add -h Human
 Readable Option

---
 toys/other/count.c | 17 ++++++++++++++---
 1 file changed, 14 insertions(+), 3 deletions(-)

diff --git a/toys/other/count.c b/toys/other/count.c
index 3d388e78..356d7915 100644
--- a/toys/other/count.c
+++ b/toys/other/count.c
@@ -2,17 +2,20 @@
  *
  * Copyright 2002 Rob Landley <[email protected]>
 
-USE_COUNT(NEWTOY(count, NULL, TOYFLAG_USR|TOYFLAG_BIN))
+USE_COUNT(NEWTOY(count, "h", TOYFLAG_USR|TOYFLAG_BIN|TOYFLAG_MAYFORK))
 
 config COUNT
   bool "count"
   default y
   help
-    usage: count
+    usage: count [-h]
 
     Copy stdin to stdout, displaying simple progress indicator to stderr.
+    
+    -h	Print size in human readable format
 */
 
+#define FOR_count
 #include "toys.h"
 
 void count_main(void)
@@ -31,8 +34,16 @@ void count_main(void)
       size += len;
       if ((now = millitime())-then<250) continue;
     }
-    dprintf(2, "%llu bytes\r", size);
+
+    if (FLAG(h)) {
+      human_readable(toybuf, (unsigned long long)size, 0);
+      // Giving it a buffer to eat into so characters don't overlap
+      dprintf(2, "%s    \r", toybuf);
+    }
+    else dprintf(2, "%llu bytes\r", size);
+
     if (!len) break;
   }
   dprintf(2, "\n");
+  free(buf);
 }
-- 
2.34.1

_______________________________________________
Toybox mailing list
[email protected]
http://lists.landley.net/listinfo.cgi/toybox-landley.net

Reply via email to