Commit 06e50e9aa7

mlugg <mlugg@mlugg.co.uk>
2023-07-25 14:51:22
std.Progress: add optional unit to progress indicator
1 parent dc24835
Changed files (1)
lib
lib/std/Progress.zig
@@ -68,6 +68,7 @@ pub const Node = struct {
     context: *Progress,
     parent: ?*Node,
     name: []const u8,
+    unit: []const u8 = "",
     /// Must be handled atomically to be thread-safe.
     recently_updated_child: ?*Node = null,
     /// Must be handled atomically to be thread-safe. 0 means null.
@@ -141,6 +142,21 @@ pub const Node = struct {
         }
     }
 
+    /// Thread-safe.
+    pub fn setUnit(self: *Node, unit: []const u8) void {
+        const progress = self.context;
+        progress.update_mutex.lock();
+        defer progress.update_mutex.unlock();
+        self.unit = unit;
+        if (self.parent) |parent| {
+            @atomicStore(?*Node, &parent.recently_updated_child, self, .Release);
+            if (parent.parent) |grand_parent| {
+                @atomicStore(?*Node, &grand_parent.recently_updated_child, parent, .Release);
+            }
+            if (progress.timer) |*timer| progress.maybeRefreshWithHeldLock(timer);
+        }
+    }
+
     /// Thread-safe. 0 means unknown.
     pub fn setEstimatedTotalItems(self: *Node, count: usize) void {
         @atomicStore(usize, &self.unprotected_estimated_total_items, count, .Monotonic);
@@ -307,11 +323,11 @@ fn refreshWithHeldLock(self: *Progress) void {
                 }
                 if (eti > 0) {
                     if (need_ellipse) self.bufWrite(&end, " ", .{});
-                    self.bufWrite(&end, "[{d}/{d}] ", .{ current_item, eti });
+                    self.bufWrite(&end, "[{d}/{d}{s}] ", .{ current_item, eti, node.unit });
                     need_ellipse = false;
                 } else if (completed_items != 0) {
                     if (need_ellipse) self.bufWrite(&end, " ", .{});
-                    self.bufWrite(&end, "[{d}] ", .{current_item});
+                    self.bufWrite(&end, "[{d}{s}] ", .{ current_item, node.unit });
                     need_ellipse = false;
                 }
             }