std.Progress: add optional unit to progress indicator

This commit is contained in:
mlugg 2023-07-25 13:51:22 +01:00
parent dc24835168
commit 06e50e9aa7
No known key found for this signature in database
GPG Key ID: E60D96B91E86EF9F

View File

@ -68,6 +68,7 @@ pub const Node = struct {
context: *Progress, context: *Progress,
parent: ?*Node, parent: ?*Node,
name: []const u8, name: []const u8,
unit: []const u8 = "",
/// Must be handled atomically to be thread-safe. /// Must be handled atomically to be thread-safe.
recently_updated_child: ?*Node = null, recently_updated_child: ?*Node = null,
/// Must be handled atomically to be thread-safe. 0 means 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. /// Thread-safe. 0 means unknown.
pub fn setEstimatedTotalItems(self: *Node, count: usize) void { pub fn setEstimatedTotalItems(self: *Node, count: usize) void {
@atomicStore(usize, &self.unprotected_estimated_total_items, count, .Monotonic); @atomicStore(usize, &self.unprotected_estimated_total_items, count, .Monotonic);
@ -307,11 +323,11 @@ fn refreshWithHeldLock(self: *Progress) void {
} }
if (eti > 0) { if (eti > 0) {
if (need_ellipse) self.bufWrite(&end, " ", .{}); 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; need_ellipse = false;
} else if (completed_items != 0) { } else if (completed_items != 0) {
if (need_ellipse) self.bufWrite(&end, " ", .{}); if (need_ellipse) self.bufWrite(&end, " ", .{});
self.bufWrite(&end, "[{d}] ", .{current_item}); self.bufWrite(&end, "[{d}{s}] ", .{ current_item, node.unit });
need_ellipse = false; need_ellipse = false;
} }
} }