mpb

package module
v0.1.9 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 19, 2026 License: MIT Imports: 16 Imported by: 0

README

mpb

quant1x/mpb 把 Rust 进度条库 indicatif 作为唯一规范, 用五套语言实现同一套进度条语义。

角色 内容
规范 Rust indicatif 0.18.6(commit 3adb05c),任何行为以它为准
移植 Go / Python / C++ / Zig 四个独立实现,逐模块对照上游
封装 Rust 侧同名 mpb crate,只有 pub use indicatif::*;,不做二次实现

五个入口共享同一套能力:模板与 ANSI 样式、宽度与换行度量、20Hz 节流与令牌桶、15 秒双指数 平滑估算器、单/多进度条、树形嵌套、println / clear / suspend、u64 边界、 Drop/僵尸行(zombie)算法、内存终端。

上游与版本

项 值
上游仓库 https://github.com/console-rs/indicatif
上游版本 0.18.6
上游 commit 3adb05c80429415743d8142503c24fa8ee639453(短号 3adb05c,2026-10-06)
上游本地副本 <UPSTREAM_DIR>,例如 d:/projects/rust/indicatif

仓库不随附上游的 .rs / examples/ / tests/ / Cargo.toml,移植时直接读 <UPSTREAM_DIR>。 对比两个上游版本:

git -C <UPSTREAM_DIR> --no-pager diff <OLD_COMMIT> HEAD -- src/

<OLD_COMMIT> 取 3adb05c 的前一次提交,即可看到 0.18.6 这一批改动。

语言矩阵

语言 入口 构建 测试 示例 版本来源
Go doc.go go build ./... go test ./... go run ./examples <name> —(无版本清单)
Python __init__.py pip install -e . python -m pytest python -m examples <name> setuptools-scm
C++ mpb.h cmake + cmake --build ctest --test-dir build mpb_examples <name> git describe(git_tag_info.cmake)
Zig mpb.zig zig build zig build test zig build run -- <name> build.zig.zon
Rust lib.rs cargo build cargo test cargo run --example examples -- <name> Cargo.toml

版本号由 quant1x/auto-changelog 在发版时统一写入 Cargo.toml、build.zig.zon 等清单文件,不手工维护。

目录结构

五种语言的源文件同目录并排(与 mopr 的组织方式一致):

mpb/
├── *.go                     go.mod
├── *.py                     pyproject.toml
├── *.h / *.cpp              CMakeLists.txt、git_tag_info.cmake
├── *.zig                    build.zig、build.zig.zon、unicode_width.zig
├── Cargo.toml               lib.rs
├── examples/
│   ├── main.{go,py,cpp,zig,rs}      每种语言一个入口,按名字分派
│   └── <name>.{go,py,cpp,zig,rs}    17 个示例,同名同语义
├── scripts/generate.{ps1,sh}        重录 screenshots/
└── screenshots/                     16 条 VHS 录屏

模块对照

Rust(上游) Go Python C++ Zig 内容
style.rs style.go style.py style.h / style.cpp style.zig 模板解析、ANSI 样式、宽度度量
state.rs state.go state.py state.h / state.cpp state.zig BarState / ProgressState、出帧、Estimator
draw_target.rs draw_target.go draw_target.py draw_target.h / draw_target.cpp draw_target.zig 绘制目标、限速、行数调整
multi.rs multi.go multi.py multi.h / multi.cpp multi.zig MultiProgress / MultiState、orphan 行、僵尸行
progress_bar.rs progress_bar.go progress_bar.py progress_bar.h / progress_bar.cpp progress_bar.zig ProgressBar 门面
iter.rs / rayon.rs iter.go / rayon.go iter.py iter.h —(未移植) 迭代器包装
format.rs format.go format.py format.h / format.cpp format.zig HumanBytes / HumanDuration / HumanCount 等
in_memory.rs / term_like.rs in_memory.go / term_like.go in_memory.py / term_like.py in_memory.h / in_memory.cpp、term_like.h / term_like.cpp term_like.zig 内存终端与终端抽象
lib.rs doc.go __init__.py mpb.h mpb.zig 包入口与导出

说明:

  • Rust 列即上游规范;Rust 侧的同名 mpb crate 直接 re-export,因此没有独立的模块文件。
  • C++ 另有 types.h(共享枚举/时间类型)、utf8.h(UTF-8 编解码)、unicode_width_tables.h (由 Rust unicode-width 0.2.2 生成的宽度区间表)。
  • Zig 另有 width.zig + unicode_width.zig:宽度算法与同一份 unicode-width 0.2.2 区间表。
  • Rust 的 Drop for BarState 在四个移植里的对应实现: Go weakref.go + finalizer、Python weakref + BarState.__del__、 C++ std::weak_ptr + 析构函数、Zig 引用计数 + ProgressBar.deinit()。

快速开始

Go
package main

import "github.com/quant1x/mpb"

func main() {
    pb := mpb.New(1024)
    for i := 0; i < 1024; i++ {
        pb.Inc(1)
    }
    pb.FinishWithMessage("done")
}
go build ./...
go test ./...
Python
pip install -e .
from mpb import ProgressBar, ProgressStyle

pb = ProgressBar(1024)
pb.set_style(ProgressStyle("{wide_bar} {pos}/{len}"))
for _ in range(1024):
    pb.inc(1)
pb.finish_with_message("done")
python -m pytest
C++
#include "mpb.h"

int main() {
    auto pb = mpb::ProgressBar::make(1024);
    pb->set_style(mpb::progress_style_with_template("{wide_bar} {pos}/{len}"));
    for (int i = 0; i < 1024; ++i) {
        pb->inc();
    }
    pb->finish_with_message("done");
}
# Linux / macOS(GCC / Clang)
cmake -S . -B build -DCMAKE_BUILD_TYPE=Release
cmake --build build -j
ctest --test-dir build --output-on-failure
# Windows(MSVC)
cmake -S . -B build-msvc -G "Visual Studio 17 2022" -A x64
cmake --build build-msvc --config Release -j
ctest --test-dir build-msvc -C Release --output-on-failure

非 git 源码树用 -DMPB_VERSION_OVERRIDE=x.y.z 显式指定版本;-DMPB_BUILD_EXAMPLES=OFF 可以只构建库。

Zig
const mpb = @import("mpb");

var pb = mpb.ProgressBar.new(1024);
defer pb.deinit();
for (0..1024) |_| pb.inc(1);
pb.finishWithMessage("done");
zig build test      # 单元测试
zig build           # 构建 mpb_examples
Rust
[dependencies]
# 发布后:mpb = "0.1";仓库内开发时也可以直接用 path 依赖
mpb = { path = "../mpb" }
use mpb::{ProgressBar, ProgressStyle};

let pb = ProgressBar::new(1024);
pb.set_style(ProgressStyle::with_template("{wide_bar} {pos}/{len}").unwrap());
for _ in 0..1024 {
    pb.inc(1);
}
pb.finish_with_message("done");
cargo test
cargo build --example examples

mpb 没有自己的 feature:in_memory / improved_unicode / futures / rayon / tokio 全部默认打开。mpb::ProgressBar 就是 indicatif::ProgressBar,不是包装类型。

示例

17 个示例与上游 examples/ 同名,统一入口按名字分派。名字使用上游的连字符写法 (multi-tree),五个入口同时接受下划线写法(multi_tree)。

示例 演示内容 录屏
single 单条进度条,1024 步 × 5ms gif
fastbar 百万次极快更新下的 20Hz 出帧与耗时统计 gif
finebars 5 条不同粒度/颜色的条并发推进 gif
log println 打日志不破坏进度条画面 gif
morebars 一条总条 + 多条子条的嵌套推进 gif
multi 三条并发进度条 + println + insert_after —
multi-tree 树形嵌套:元素按缩进逐级加入 gif
multi-tree-ext 树形增删 + --bottom-alignment gif
cargo 模拟 cargo 编译:4 个 worker 抢 crate 队列 gif
cargowrap 把 cargo build --release 的 stderr 喂给 spinner gif
download {bytes}/{total_bytes} + 自定义 eta key gif
download-continued 断点续传:非零起点 + reset_eta() gif
download-speed 在 download 基础上加 {bytes_per_sec} gif
iterator progress() / progress_count() / progress_with() gif
long-spinner steady tick + 自定义 spinner 帧 gif
tokio 定时器驱动:每 5ms 一个 tick gif
yarnish 四段式安装输出,最后用 HumanDuration 报耗时 gif

single

五种语言的运行方式:

go run ./examples multi-tree
python -m examples multi-tree
./build/mpb_examples multi-tree          # MSVC 多配置生成器在 build/Release/ 下
zig build run -- multi-tree
cargo run --example examples -- multi-tree

带参数的示例(Zig/Cargo 需要 -- 分隔自己的参数):

go run ./examples multi-tree-ext --bottom-alignment
python -m examples multi-tree-ext --bottom-alignment
./build/mpb_examples multi-tree-ext --bottom-alignment
zig build run -- multi-tree-ext -- --bottom-alignment
cargo run --example examples -- multi-tree-ext -- --bottom-alignment

重新录制 screenshots/(脚本会自己切到仓库根目录,PowerShell 与 bash 行为一致):

./scripts/generate.ps1              # 全部 16 条
./scripts/generate.ps1 single log   # 只重录指定几条
./scripts/generate.sh               # 全部 16 条
./scripts/generate.sh single log    # 只重录指定几条

核心语义

模板 key
类别 key
进度条 bar、wide_bar、percent、percent_precise
位置/长度 pos、len、human_pos、human_len
字节 bytes、total_bytes、decimal_bytes、decimal_total_bytes、binary_bytes、binary_total_bytes
速率 per_sec、bytes_per_sec、decimal_bytes_per_sec、binary_bytes_per_sec
时间 elapsed、elapsed_precise、eta、eta_precise、duration、duration_precise
文本 msg、wide_msg、prefix、spinner
自定义 with_key(name, fn)(Rust/Go/Python/C++/Zig 均支持)

模板语法与上游一致:{key:对齐宽度.样式/替代样式}、{key!} 截断、{{ / }} 转义。 bar 的示例:{bar:40.cyan/blue}、{wide_bar:.red}。

节流与估算
  • 终端出帧默认 20Hz(RateLimiter,MAX_BURST = 20,允许短时突发);
  • 位置更新另有一层 1ms 令牌桶(AtomicPosition,MAX_BURST = 10),避免高频 inc 打爆状态;
  • ETA/速率用 15 秒半衰期的双指数平滑估算器;
  • 非 TTY(管道、重定向、CI)时整条进度条隐藏,与上游一致。
多进度条与僵尸行

MultiState 用 members + free_set + ordering 维护槽位与屏幕顺序:

  • orphan 行:println 的消息先入队列,下一帧出现在所有进度条上方;
  • 僵尸行:ProgressBar 被释放后,它最后一次绘制的行保留到下一次重绘,然后回收;
  • 对齐:Top(默认)/ Bottom,删除中间条时决定整体上移还是下移;
  • clear / suspend / println 都会正确擦除僵尸行。
索引的两套语义
API Rust Go 含义
Index() index() -> Option<MultiStateIndex> (uint, bool) 不透明槽位下标,会被 free_set 复用,与屏幕顺序无关
VisualIndex() visual_index() -> Option<usize> (uint, bool) 屏幕位置(第几行)
Insert / InsertFromBack insert(index, ..) index uint 插入位置

需要“第几条 bar”时用 VisualIndex(),不要用 Index()。

语言层差异

运行时机制
维度 Go Python C++ Zig Rust
时间类型 time.Duration float 秒 std::chrono::nanoseconds i96 纳秒 std::time::Duration
迭代器 iter.go(切片) 任意可迭代对象 iter.h 未移植 ProgressIterator
宽度表 go-runewidth unicodedata + 手写规则 Rust unicode-width 表 Rust unicode-width 表 unicode-width
生命周期 finalizer + weak registry weakref + __del__ weak_ptr + 析构 引用计数 + deinit() Drop
跨平台时序 标准库 标准库 标准库 自带高精度 sleep / 控制台处理 标准库 + console
Python 与 Go 的差异

下面这些来自语言/运行时,不是 Rust 语义偏差:

  • 错误处理:Python 用异常(TemplateError、ValueError),Go 用 (value, error); MultiProgress.println() / clear() 在 Python 返回 None。
  • 迭代器:Python 支持任意可迭代对象/生成器;Go 只包装切片。
  • 格式化 API:Go 的 HumanBytes 等是实现 String/Format 的类型,Python 是普通函数,输出逐字一致。
  • 样式拷贝:Python 的 set_style() / style() / with_* 按值克隆,避免浅拷贝共享。
  • 整数边界:位置/长度按 u64 语义处理;Python 在边界处显式取模/钳位,负数抛 ValueError。
  • 锁:Python 用 RLock,suspend 回调内可重入;Go 的 Mutex 非重入。
  • 回收时机:Go/Python 依赖运行时,不保证在确定时刻触发;语义与 Rust 的 Drop 一致。
Zig 的平台处理
  • 短休眠:Windows 用 CREATE_WAITABLE_TIMER_HIGH_RESOLUTION 可等待定时器(约 0.5ms), 绕开默认 15.6ms 粒度;macOS/POSIX 用 nanosleep;
  • 自旋提示:x86 pause、arm64 isb(与 Rust core::hint::spin_loop 一致); 不使用 arm64 yield,避免 Apple Silicon 的线程节流形成 convoy;
  • 控制台:Windows 通过 WriteConsoleW 写 UTF-16,并打开 ENABLE_VIRTUAL_TERMINAL_PROCESSING,否则 █░ / emoji 会按 OEM 代码页乱码、清行失效。
与上游的有意差异
  • 宽度开关命名:Rust Width::set_default_cjk(bool);Go DefaultWidth.SetDefaultCJK(bool); Python mpb.DEFAULT_WIDTH.set_default_cjk(bool);C++ mpb::Width::set_default_cjk(bool); Zig mpb.setDefaultCjk(bool)。
  • MultiProgress 状态导出:Go 的 State 字段对应 Rust 0.18.6 的 pub state, 访问前需自行加 MultiState 的锁。

已知限制

  • Zig:iter / rayon 尚未移植;示例里的随机数用固定种子的 LCG 替代 rand, cargowrap 回放构建输出而不是递归构建,tokio 示例用等价的 5ms 循环; InMemoryTerm 是 VT100 子集(覆盖 mpb 自身产生的序列)。
  • Rust 示例:同样用确定性 LCG 替代 rand;cargowrap 会真的执行 cargo build --release(因此需要 cargo 且在 Rust 工程目录内运行)。
  • 宽度表:Python 用 unicodedata、Go 用 go-runewidth,与 Rust unicode-width 0.2.2 在 ASCII/Latin/CJK/emoji/方块/盲文等常用区间一致;约 4k 个生僻/未分配码点 (组合记号、Unicode 版本差异)可能有 0/1/2 列差异。C++ 与 Zig 直接使用 Rust 的表。
  • C++:极少数阿拉伯/希伯来/印度文字连字仍按字符合成,未复刻 unicode-width 的完整连字状态机。

许可证

MIT。

Documentation

Overview

Package mpb 是 Rust 进度条库 indicatif 的 Go 移植。

来源

上游仓库 github.com/console-rs/indicatif,对齐的版本是 0.18.6 (commit 3adb05c80429415743d8142503c24fa8ee639453)。 移植的原则是**逐语义对齐**而不是逐语法翻译:同样的模板语法、同样的宽度与 换行度量、同样的僵尸行(zombie)算法、同样的绘制限速。Rust 的枚举与 trait 在 Go 里落成接口与结构体字段,但行为保持一致。

模块

style.go        模板与样式({bar:40.red/blue}、on_* 背景色、256 色、真彩色、宽度度量)
state.go        进度条状态、绘制状态与出帧
draw_target.go  绘制目标(终端 / term-like / multi / hidden)、限速、行数调整
multi.go        MultiProgress / MultiState、成员排序、orphan 行、僵尸行
progress_bar.go ProgressBar 门面
iter.go         迭代器包装(rayon.go 提供并行版)
format.go       HumanBytes / HumanDuration / HumanFloatCount 等格式化
in_memory.go    内存终端,测试用
term_like.go    终端抽象

用法

单条进度条:

pb := mpb.New(100)
pb.SetStyle(mpb.DefaultProgressStyleBar())
for i := 0; i < 100; i++ {
	pb.Inc(1)
	time.Sleep(10 * time.Millisecond)
}
pb.Finish()

多条进度条:

mp := mpb.NewMultiProgress()
pb1 := mp.Add(mpb.New(100))
pb2 := mp.Add(mpb.New(200))

两个容易踩的点

  1. 绘制目标默认是 stderr。按上游语义,stderr 不是真终端(重定向到文件或 管道)时整条进度条会隐藏 —— 见 ProgressDrawTarget.IsHidden。测试里要拿 渲染结果请用 NewInMemoryTerm 配 NewInMemoryDrawTarget。
  2. ProgressBar.Index 返回的是 MultiState 里**不透明**的槽位下标(会被复用), 要「屏幕上是第几行」请用 ProgressBar.VisualIndex。

Index

Constants

View Source
const DEFAULT_TAB_WIDTH = 8

Variables

View Source
var (
	SECOND = time.Second
	MINUTE = time.Minute
	HOUR   = time.Hour
	DAY    = 24 * HOUR
	WEEK   = 7 * DAY
	YEAR   = 365 * DAY
)

时间单位常量

View Source
var DefaultWidth = Width{}

DefaultWidth 对应 Rust 的 `pub(crate) static WIDTH: Width = Width::new()`。

Functions

func MapParallel

func MapParallel[T any, U any](p *ProgressBarIter[T], workers int, fn func(T) U) []U

MapParallel 对应 Rust 里对包装后的并行迭代器做 `map(...).collect()`:

  • 与 ProgressFolder::consume 一致:每消费一个元素 inc(1)(先推进再干活);
  • 与 IndexedParallelIterator 的 collect 一致:**结果按输入顺序排列** (原来的实现从 out channel 里先到先收,顺序是乱的);
  • 与 Rust 一致:消费完不收尾进度条(Folder::complete 只 complete 底层, 不调 finish;是否收尾由调用方决定);
  • 迭代器被消费掉(Rust 的 drive 取得所有权),消费后 Len() 为 0。

workers 对应 rayon 的分片并发度:Rust 那边由全局线程池决定,Go 这里显式给。

Types

type AtomicPosition

type AtomicPosition struct {
	// contains filtered or unexported fields
}

AtomicPosition 是对 Rust 中 AtomicPosition 的复现。 它包含位置计数、令牌桶(capacity)、上次允许时间(prev)和起始时间(start)。

func NewAtomicPosition

func NewAtomicPosition() *AtomicPosition

func (*AtomicPosition) Allow

func (a *AtomicPosition) Allow(now time.Time) bool

Allow 模拟 Rust 的 allow() 行为:基于时间窗为 tick 决定是否允许。

func (*AtomicPosition) Dec

func (a *AtomicPosition) Dec(delta uint64)

func (*AtomicPosition) Inc

func (a *AtomicPosition) Inc(delta uint64)

func (*AtomicPosition) Pos

func (a *AtomicPosition) Pos() uint64

func (*AtomicPosition) Reset

func (a *AtomicPosition) Reset(now time.Time)

func (*AtomicPosition) Set

func (a *AtomicPosition) Set(v uint64)

type BarState

type BarState struct {
	// contains filtered or unexported fields
}

BarState 对应 Rust 的 BarState

func NewBarState

func NewBarState(len *uint64, drawTarget ProgressDrawTarget, pos *AtomicPosition) *BarState

NewBarState 创建 BarState,接受 pos(AtomicPosition)以与 Rust 保持一致

func (*BarState) DecLength

func (b *BarState) DecLength(now time.Time, delta uint64)

func (*BarState) FinishUsingStyle

func (b *BarState) FinishUsingStyle(now time.Time, finish ProgressFinish)

FinishUsingStyle 完成时应用样式行为

func (*BarState) IncLength

func (b *BarState) IncLength(now time.Time, delta uint64)

func (*BarState) Index

func (b *BarState) Index() (uint, bool)

Index 返回进度条在 MultiProgress 中的索引(如果存在)。

对应 Rust 的 `ProgressBar::index() -> Option<MultiStateIndex>`:不透明下标,类型是 usize(Go 侧即 uint),与屏幕位置无关 —— 要看第几行用 VisualIndex()。

func (*BarState) Println

func (b *BarState) Println(now time.Time, msg string)

func (*BarState) Reset

func (b *BarState) Reset(now time.Time, mode ResetMode)

func (*BarState) SetLength

func (b *BarState) SetLength(now time.Time, l uint64)

func (*BarState) SetStyle

func (b *BarState) SetStyle(style ProgressStyle)

func (*BarState) SetTabWidth

func (b *BarState) SetTabWidth(tabWidth int)

func (*BarState) Suspend

func (b *BarState) Suspend(now time.Time, f func() interface{}) interface{}

func (*BarState) Tick

func (b *BarState) Tick(now time.Time)

func (*BarState) UnsetLength

func (b *BarState) UnsetLength(now time.Time)

func (*BarState) Update

func (b *BarState) Update(now time.Time, f func(*ProgressState), tick bool)

Update 更新内部 ProgressState 并在需要时 tick

func (*BarState) UpdateEstimateAndDraw

func (b *BarState) UpdateEstimateAndDraw(now time.Time)

type BinaryBytes

type BinaryBytes uint64

BinaryBytes: 使用二进制前缀显示 (KiB, MiB)

func (BinaryBytes) String

func (b BinaryBytes) String() string

type DecimalBytes

type DecimalBytes uint64

DecimalBytes: 使用十进制 SI 前缀 (kB, MB)

func (DecimalBytes) String

func (b DecimalBytes) String() string

type DrawState

type DrawState struct {
	// contains filtered or unexported fields
}

draw target 的具体实现位于 draw_target.go(增量翻译)。 DrawState mirrors Rust's DrawState: it holds the lines to print, the move_cursor flag and the alignment for multi progress.

type DrawStateStub

type DrawStateStub = DrawState

Keep DrawStateStub as an alias for compatibility where referenced.

type DrawStateWrapper

type DrawStateWrapper struct {
	StatePtr *DrawStateStub
	// contains filtered or unexported fields
}

DrawStateWrapper is a RAII-style wrapper around DrawStateStub used to emulate Rust's DrawStateWrapper behavior: when Close() is called and an orphanLines slice was provided, non-bar lines are moved into orphanLines.

func DrawStateWrapperForMulti

func DrawStateWrapperForMulti(s *DrawStateStub, orphan *[]string) *DrawStateWrapper

func DrawStateWrapperForTerm

func DrawStateWrapperForTerm(s *DrawStateStub) *DrawStateWrapper

func (*DrawStateWrapper) Close

func (w *DrawStateWrapper) Close()

Close 对应 Rust 的 `impl Drop for DrawStateWrapper`: 只有 orphan_lines 为 Some(即 multi 路径)时才把 Text/Empty 行移出去; term 路径下这些行要留在 state 里照常绘制 —— 否则 Println 的消息会被整段丢掉。

func (*DrawStateWrapper) Reset

func (w *DrawStateWrapper) Reset()

type Drawable

type Drawable interface {
	State() *DrawStateWrapper
	Draw() error
	Clear() error
	Width() *uint16
}

type DrawableStub

type DrawableStub interface {
	State() *DrawStateStub
	Draw() error
	Clear() error
}

type Estimator

type Estimator struct {
	// contains filtered or unexported fields
}

func NewEstimator

func NewEstimator(now time.Time) Estimator

func (*Estimator) Record

func (e *Estimator) Record(newSteps uint64, now time.Time)

func (*Estimator) Reset

func (e *Estimator) Reset(now time.Time)

func (*Estimator) StepsPerSecond

func (e *Estimator) StepsPerSecond(now time.Time) float64

type FinishKind

type FinishKind int

ProgressFinish 表示完成时的行为(对应 Rust 的 enum)

const (
	FinishAndLeave FinishKind = iota
	FinishWithMessage
	FinishAndClear
	FinishAbandon
	FinishAbandonWithMessage
)

type FormattedDuration

type FormattedDuration time.Duration

FormattedDuration: 包装 time.Duration 用于基本人类可读格式化

func (FormattedDuration) String

func (d FormattedDuration) String() string

type HumanBytes

type HumanBytes uint64

HumanBytes: 把字节数格式化为人类可读(使用二进制前缀,KiB 等)

func (HumanBytes) String

func (b HumanBytes) String() string

type HumanCount

type HumanCount uint64

HumanCount: 使用千位分隔符格式化整数

func (HumanCount) String

func (h HumanCount) String() string

type HumanDuration

type HumanDuration time.Duration

HumanDuration: 包装 time.Duration 用于更直观的人类可读显示

func (HumanDuration) Format

func (d HumanDuration) Format(s fmt.State, verb rune)

为 fmt.Formatter 的兼容性提供支持(便于处理 %#v 等)

func (HumanDuration) String

func (d HumanDuration) String() string

type HumanFloatCount

type HumanFloatCount float64

HumanFloatCount: 支持带小数和千位分隔符的浮点数,尊重格式化精度

func (HumanFloatCount) Format

func (h HumanFloatCount) Format(s fmt.State, verb rune)

实现 fmt.Formatter 以便读取精度信息

type InMemoryTerm

type InMemoryTerm struct {
	// contains filtered or unexported fields
}

InMemoryTerm 是一个轻量的内存终端实现(对应 src/in_memory.rs)。

Rust 那边是 `Arc<Mutex<InMemoryTermState>>`("so it can be freely cloned"), Go 里 state 是指针,*InMemoryTerm 之间天然共享同一份 state,语义等价。

func NewInMemoryTerm

func NewInMemoryTerm(rows uint16, cols uint16) *InMemoryTerm

NewInMemoryTerm 使用指定的行数和列数创建一个新的内存终端(Rust 里 rows/cols 必须 > 0)。

func (*InMemoryTerm) ClearLine

func (t *InMemoryTerm) ClearLine() error

func (*InMemoryTerm) Contents

func (t *InMemoryTerm) Contents() string

Contents 返回当前屏幕的文本内容(去掉行尾空白,并去掉尾部空行)。

对应 Rust 的 contents():rev().skip_while(空).map(trim_end).rev().join("\n")。 注意顺序:Rust 那边 vt100 的 `screen().rows(..)` 返回的行本身就不带尾部空格,所以「判空」和 「trim」孰先孰后都一样;Go 的 buf 是空格填充的,必须先 trim 再判空,否则尾部空行会被当成非空。

func (*InMemoryTerm) ContentsFormatted

func (t *InMemoryTerm) ContentsFormatted() []byte

ContentsFormatted 返回每行后面附加重置 ANSI 序列的字节表示。 与 Rust 一致:先去掉尾部空行,再给每行拼 "\x1b[m" + '\n',最后砍掉末尾那个 '\n' (保留末尾的 reset)。

func (*InMemoryTerm) Flush

func (t *InMemoryTerm) Flush() error

func (*InMemoryTerm) Height

func (t *InMemoryTerm) Height() uint16

func (*InMemoryTerm) MoveCursorDown

func (t *InMemoryTerm) MoveCursorDown(n int) error

func (*InMemoryTerm) MoveCursorLeft

func (t *InMemoryTerm) MoveCursorLeft(n int) error

func (*InMemoryTerm) MoveCursorRight

func (t *InMemoryTerm) MoveCursorRight(n int) error

func (*InMemoryTerm) MoveCursorUp

func (t *InMemoryTerm) MoveCursorUp(n int) error

func (*InMemoryTerm) MovesSinceLastCheck

func (t *InMemoryTerm) MovesSinceLastCheck() string

MovesSinceLastCheck 返回自上次检查以来的移动历史(并清空历史)。 与 Rust 一致:对每条 Move 用 `writeln!(s, "{line:?}")` 打印,即 Debug 格式。

func (*InMemoryTerm) Reset

func (t *InMemoryTerm) Reset()

Reset 重置终端内容为初始状态。 对应 Rust 的 `*state = InMemoryTermState::new(..)`:改的是共享的 state 本体, 所以所有共享该 state 的 InMemoryTerm 都能看到重置(不是只换自己那根指针)。

func (*InMemoryTerm) Width

func (t *InMemoryTerm) Width() uint16

func (*InMemoryTerm) WriteLine

func (t *InMemoryTerm) WriteLine(s string) error

func (*InMemoryTerm) WriteStr

func (t *InMemoryTerm) WriteStr(s string) error

type InsertLocation

type InsertLocation int
const (
	InsertLocationEnd InsertLocation = iota
	InsertLocationIndex
	InsertLocationIndexFromBack
	InsertLocationAfter
	InsertLocationBefore
)

type LineAdjust

type LineAdjust struct {
	Kind  LineAdjustKind
	Count VisualLines
}

type LineAdjustKind

type LineAdjustKind int
const (
	LineAdjustClear LineAdjustKind = iota
	LineAdjustKeep
)

type LineType

type LineType int
const (
	LineText LineType = iota
	LineBar
	LineEmpty
)

func LineEmptyVal

func LineEmptyVal() LineType

func LineTextVal

func LineTextVal(s string) LineType

type MultiProgress

type MultiProgress struct {
	State *MultiState
}

MultiProgress 对应 Rust 的 `pub struct MultiProgress { state: Arc<RwLock<MultiState>> }`。

Rust 0.18.6 把 `state` 从 `pub(crate)` 改成了 `pub`(同时 `MultiState` 也 pub 了), 便于外部直接读写 multi 的状态(成员、orphan 行、对齐方式等)。Go 这边照做:字段导出。 注意 MultiState 自带 RWMutex,访问前要像 Rust 的 `read()/write()` 那样先加锁。

func DefaultMultiProgress

func DefaultMultiProgress() *MultiProgress

func NewMultiProgress

func NewMultiProgress() *MultiProgress

func WithDrawTarget

func WithDrawTarget(dt ProgressDrawTarget) *MultiProgress

func (*MultiProgress) Add

func (mp *MultiProgress) Add(pb *ProgressBar) *ProgressBar

func (*MultiProgress) Clear

func (mp *MultiProgress) Clear() error

Clear 对应 Rust 的 MultiProgress::clear:返回底层 io 错误(之前恒返回 nil,错误被吞)。

func (*MultiProgress) Insert

func (mp *MultiProgress) Insert(index uint, pb *ProgressBar) *ProgressBar

Insert / InsertFromBack 的 index 是 uint,对应 Rust 的 `insert(index: usize, ..)`。

func (*MultiProgress) InsertAfter

func (mp *MultiProgress) InsertAfter(after *ProgressBar, pb *ProgressBar) *ProgressBar

func (*MultiProgress) InsertBefore

func (mp *MultiProgress) InsertBefore(before *ProgressBar, pb *ProgressBar) *ProgressBar

func (*MultiProgress) InsertFromBack

func (mp *MultiProgress) InsertFromBack(index uint, pb *ProgressBar) *ProgressBar

func (*MultiProgress) IsHidden

func (mp *MultiProgress) IsHidden() bool

func (*MultiProgress) New

func (mp *MultiProgress) New() *MultiProgress

func (*MultiProgress) Println

func (mp *MultiProgress) Println(msg string) error

Println 对应 Rust 的 MultiProgress::println:返回底层 io 错误(之前恒返回 nil,错误被吞)。

func (*MultiProgress) Remove

func (mp *MultiProgress) Remove(pb *ProgressBar)

Remove 对应 Rust 的 MultiProgress::remove:

  1. 只移除「确实插在本 MultiProgress 上」的进度条(Rust 是 `assert!(Arc::ptr_eq(..))`, Go 里没有 Arc,退化成比 Remote() 拿到的 MultiState 是否同一个);
  2. 先把这条 bar 的绘制目标置成 hidden,再回收槽位 —— 不置的话,旧 ProgressBar 仍指向 该槽位,槽位被后来的 bar 复用后它会画到别人的行上。

func (*MultiProgress) SetAlignment

func (mp *MultiProgress) SetAlignment(alignment MultiProgressAlignment)

func (*MultiProgress) SetDrawTarget

func (mp *MultiProgress) SetDrawTarget(target ProgressDrawTarget)

SetDrawTarget 对应 Rust 的 MultiProgress::set_draw_target:

state.draw_target.disconnect(Instant::now());   // 先断开旧的
state.draw_target = target;                     // 再换新的

Go 这边 MultiState 持有的是 multiDrawTarget 包装层,所以断开的是包装层里的旧目标, 换上去的也重新包一层(包装层负责聚合出帧,不能直接丢)。

func (*MultiProgress) SetMoveCursor

func (mp *MultiProgress) SetMoveCursor(moveCursor bool)

func (*MultiProgress) Suspend

func (mp *MultiProgress) Suspend(f func() interface{}) interface{}

func (*MultiProgress) WithDrawTarget

func (mp *MultiProgress) WithDrawTarget(dt ProgressDrawTarget) *MultiProgress

type MultiProgressAlignment

type MultiProgressAlignment int
const (
	MultiProgressAlignmentTop MultiProgressAlignment = iota
	MultiProgressAlignmentBottom
)

type MultiState

type MultiState struct {
	// contains filtered or unexported fields
}

--- MultiState and helpers ---

func NewMultiState

func NewMultiState(dt ProgressDrawTarget) *MultiState

type MultiStateMember

type MultiStateMember struct {
	// contains filtered or unexported fields
}

MultiStateMember 对应 Rust 的 `struct MultiStateMember`:

draw_state: Option<DrawState>  —— 成员上一次绘制留下的行
is_zombie: bool                —— 对应的 ProgressBar(准确说是 BarState)是否已"死亡"

type MultiStateStub

type MultiStateStub struct {
	// contains filtered or unexported fields
}

MultiStateStub with reference to actual MultiState to expose Suspend

func (*MultiStateStub) Suspend

func (m *MultiStateStub) Suspend(f func() interface{}, now time.Time) interface{}

type ProgressBar

type ProgressBar struct {
	// contains filtered or unexported fields
}

ProgressBar 是对 Rust `ProgressBar` 的 Go 移植,尽量保持 1:1 的逻辑。

设计说明: - 内部状态由 `BarState` 表示(在 state.go 中实现)。 - 使用原子变量记录位置,支持并发更新。 - 支持后台稳定 ticker(EnableSteadyTick/DisableSteadyTick)。 - 提供与 Rust 接口相似的方法名(小写导出以匹配包内部使用时可见性要求)。

func Hidden

func Hidden() *ProgressBar

Hidden 创建一个隐藏的进度条(不渲染)。

func New

func New(length uint64) *ProgressBar

New 创建一个指定长度的进度条。

func NewSpinner

func NewSpinner() *ProgressBar

NewSpinner 创建一个 spinner 风格的进度条(对应 Rust 的 ProgressStyle::default_spinner())。

func NewWithDrawTarget

func NewWithDrawTarget(length *uint64, dt ProgressDrawTarget) *ProgressBar

NewWithDrawTarget 使用指定长度和绘制目标创建进度条。

func NoLength

func NoLength() *ProgressBar

NoLength 创建一个未知长度的进度条。

func (*ProgressBar) Abandon

func (p *ProgressBar) Abandon()

Abandon 标记完成但保留当前进度显示。

func (*ProgressBar) AbandonWithMessage

func (p *ProgressBar) AbandonWithMessage(msg string)

AbandonWithMessage 标记完成但保留当前进度显示,并设置消息。

func (*ProgressBar) Clone

func (p *ProgressBar) Clone() *ProgressBar

Clone 返回一个对相同内部状态与位置的浅拷贝,语义类似 Rust 的 Arc::clone。

func (*ProgressBar) Dec

func (p *ProgressBar) Dec(delta uint64)

Dec 减少位置。

func (*ProgressBar) DecLength

func (p *ProgressBar) DecLength(delta uint64)

DecLength 减少长度。

func (*ProgressBar) DisableSteadyTick

func (p *ProgressBar) DisableSteadyTick()

DisableSteadyTick 停止后台定时器。

func (*ProgressBar) Downgrade

func (p *ProgressBar) Downgrade() WeakProgressBar

func (*ProgressBar) Duration

func (p *ProgressBar) Duration() time.Duration

Duration 返回预计总时长(已用时间 + ETA)

func (*ProgressBar) Elapsed

func (p *ProgressBar) Elapsed() time.Duration

Elapsed 返回已用时间

func (*ProgressBar) EnableSteadyTick

func (p *ProgressBar) EnableSteadyTick(interval time.Duration)

EnableSteadyTick 启动后台定时器以周期性 tick。

func (*ProgressBar) Eta

func (p *ProgressBar) Eta() time.Duration

Eta 返回 ETA

func (*ProgressBar) Finish

func (p *ProgressBar) Finish()

Finish 标记完成并保留当前消息。 与 Rust 一致:不停 ticker,ticker 线程自己会在下一轮检测到 is_finished 后退出。

func (*ProgressBar) FinishAndClear

func (p *ProgressBar) FinishAndClear()

FinishAndClear 完成并清除输出。

func (*ProgressBar) FinishUsingStyle

func (p *ProgressBar) FinishUsingStyle()

FinishUsingStyle 使用当前存储的样式完成进度条(与 Rust 行为一致)。

func (*ProgressBar) FinishWithMessage

func (p *ProgressBar) FinishWithMessage(msg string)

FinishWithMessage 完成并设置消息。

func (*ProgressBar) ForceDraw

func (p *ProgressBar) ForceDraw()

ForceDraw 强制重绘。

func (*ProgressBar) Inc

func (p *ProgressBar) Inc(delta uint64)

Inc 增加位置。

对应 Rust:

self.pos.inc(delta);
let now = Instant::now();
if self.pos.allow(now) {
    self.tick_inner(now);   // ← now 是**同一个**时刻,不会重取
}

func (*ProgressBar) IncLength

func (p *ProgressBar) IncLength(delta uint64)

IncLength 增加长度。

func (*ProgressBar) Index

func (p *ProgressBar) Index() (uint, bool)

Index 返回在 MultiProgress 中的索引(如果存在)

对应 Rust 的 `ProgressBar::index()`:返回的是 `MultiState::members` 的**不透明下标** (槽位会被 free_set 复用,所以它与屏幕上的先后无关)。要看屏幕位置用 VisualIndex。

func (*ProgressBar) IsFinished

func (p *ProgressBar) IsFinished() bool

IsFinished 判断是否完成。

func (*ProgressBar) IsHidden

func (p *ProgressBar) IsHidden() bool

IsHidden 判断是否隐藏。

func (*ProgressBar) Length

func (p *ProgressBar) Length() *uint64

Length 返回可选长度

func (*ProgressBar) Message

func (p *ProgressBar) Message() string

Message 返回当前消息。

func (*ProgressBar) PerSec

func (p *ProgressBar) PerSec() float64

PerSec 返回速率

func (*ProgressBar) Position

func (p *ProgressBar) Position() uint64

Position 返回当前位置

func (*ProgressBar) Prefix

func (p *ProgressBar) Prefix() string

Prefix 返回当前前缀。

func (*ProgressBar) Println

func (p *ProgressBar) Println(msg string)

Println 打印一行到进度条上方。

func (*ProgressBar) Reset

func (p *ProgressBar) Reset()

Reset 重置估算与开始时间

func (*ProgressBar) ResetElapsed

func (p *ProgressBar) ResetElapsed()

ResetElapsed 重置已用时间

func (*ProgressBar) ResetEta

func (p *ProgressBar) ResetEta()

ResetEta 重置 ETA 估算

func (*ProgressBar) SetDrawTarget

func (p *ProgressBar) SetDrawTarget(dt ProgressDrawTarget)

SetDrawTarget 切换绘制目标(会断开先前目标)。

func (*ProgressBar) SetElapsed

func (p *ProgressBar) SetElapsed(elapsed time.Duration)

SetElapsed 设置已用时间(对应 Rust 的 set_elapsed:把起始时间往前推 elapsed)。

func (*ProgressBar) SetLength

func (p *ProgressBar) SetLength(l uint64)

SetLength 设置长度。

func (*ProgressBar) SetMessage

func (p *ProgressBar) SetMessage(msg string)

SetMessage 设置消息(对应 Rust 的 set_message,设置后立即更新估算并重绘)。

func (*ProgressBar) SetPosition

func (p *ProgressBar) SetPosition(pos uint64)

SetPosition 设置绝对位置。

func (*ProgressBar) SetPrefix

func (p *ProgressBar) SetPrefix(prefix string)

SetPrefix 设置前缀(对应 Rust 的 set_prefix,设置后立即更新估算并重绘)。

func (*ProgressBar) SetStyle

func (p *ProgressBar) SetStyle(style ProgressStyle)

SetStyle 设置样式。

func (*ProgressBar) SetTabWidth

func (p *ProgressBar) SetTabWidth(w int)

SetTabWidth 设置制表符宽度(默认 8),与 Rust 一致:设置后强制重绘一次。

func (*ProgressBar) Style

func (p *ProgressBar) Style() ProgressStyle

Style 返回当前样式的拷贝。

func (*ProgressBar) Suspend

func (p *ProgressBar) Suspend(f func() interface{}) interface{}

Suspend 隐藏进度条,执行 f,再重绘,并返回 f 的结果。 对应 Rust 的 `suspend<F: FnOnce() -> R, R>(f) -> R`;Go 的方法不支持类型参数,故 R 退化为 any。

func (*ProgressBar) TabWidth

func (p *ProgressBar) TabWidth() int

TabWidth 返回当前的制表符宽度

func (*ProgressBar) UnsetLength

func (p *ProgressBar) UnsetLength()

UnsetLength 取消长度。

func (*ProgressBar) Update

func (p *ProgressBar) Update(f func(*ProgressState))

Update 在内部 ProgressState 上执行 f,对应 Rust 的 `update(f: impl FnOnce(&mut ProgressState))`: 闭包拿到的是可变状态;随后仅当没有安装 steady ticker 时才 tick(Rust 的 `self.ticker.lock().unwrap().is_none()`)。

func (*ProgressBar) VisualIndex

func (p *ProgressBar) VisualIndex() (uint, bool)

VisualIndex 返回在 MultiProgress 中的**屏幕位置**(第几行),不在任何 MultiProgress 里时返回 false。

对应 Rust 0.18.6 新增的 `ProgressBar::visual_index()`:

self.state().draw_target.remote().map(|(remote, idx)| remote.read().unwrap().visual_index(idx))

func (*ProgressBar) WithElapsed

func (p *ProgressBar) WithElapsed(d time.Duration) *ProgressBar

WithElapsed 链式设置已用时间(简化实现)。

func (*ProgressBar) WithFinish

func (p *ProgressBar) WithFinish(f ProgressFinish) *ProgressBar

WithFinish 链式设置完成行为。

func (*ProgressBar) WithMessage

func (p *ProgressBar) WithMessage(msg string) *ProgressBar

WithMessage 链式设置消息。

func (*ProgressBar) WithPosition

func (p *ProgressBar) WithPosition(pos uint64) *ProgressBar

WithPosition 链式设置位置。

func (*ProgressBar) WithPrefix

func (p *ProgressBar) WithPrefix(prefix string) *ProgressBar

WithPrefix 链式设置前缀。

func (*ProgressBar) WithStyle

func (p *ProgressBar) WithStyle(style ProgressStyle) *ProgressBar

WithStyle 链式设置样式并返回自身。

func (*ProgressBar) WithTabWidth

func (p *ProgressBar) WithTabWidth(w int) *ProgressBar

WithTabWidth 链式设置制表符宽度(与 Rust 一致,链式设置不触发重绘)。

func (*ProgressBar) WrapRead

func (p *ProgressBar) WrapRead(r io.Reader) io.Reader

WrapRead 包装 io.Reader,对应 Rust 的 wrap_read:返回的是带进度推进的 Read 包装器 (Rust 里就是同一个 ProgressBarIter<R>,走 seek_max + set_position,见 iter.go)。

func (*ProgressBar) WrapWrite

func (p *ProgressBar) WrapWrite(w io.Writer) io.Writer

WrapWrite 包装 io.Writer,对应 Rust 的 wrap_write(同上,见 iter.go)。

type ProgressBarIter

type ProgressBarIter[T any] struct {
	// contains filtered or unexported fields
}

ProgressBarIter 对应 Rust 的 ProgressBarIter<T>:包装一个迭代器(Go 里是切片), 每产出一个元素就把进度条往前推一格。

func NewProgressBarIterFromSlice

func NewProgressBarIterFromSlice[T any](slice []T, pb *ProgressBar) *ProgressBarIter[T]

func Progress

func Progress[T any](slice []T) *ProgressBarIter[T]

Progress 对应 `progress()`:用切片长度作为元素个数。

func ProgressCount

func ProgressCount[T any](slice []T, count uint64) *ProgressBarIter[T]

ProgressCount 对应 `progress_count(len)`:显式给定元素个数。

func ProgressWithSlice

func ProgressWithSlice[T any](slice []T, pb *ProgressBar) *ProgressBarIter[T]

ProgressWithSlice 对应 `progress_with(progress)`:用已有的进度条包装。

func ProgressWithStyle

func ProgressWithStyle[T any](slice []T, style ProgressStyle) *ProgressBarIter[T]

ProgressWithStyle 对应 `progress_with_style(style)`。

func TryProgress

func TryProgress[T any](slice []T) (*ProgressBarIter[T], bool)

TryProgress 对应 `try_progress()`:Rust 里只有 size_hint 的上界已知才返回 Some, Go 的切片长度恒已知,所以这里恒返回 true。

func WrapSlice

func WrapSlice[T any](p *ProgressBar, slice []T) *ProgressBarIter[T]

WrapSlice 为切片创建一个 ProgressBarIter(Go 中的替代 wrap_iter)。

func (*ProgressBarIter[T]) Len

func (p *ProgressBarIter[T]) Len() int

Len 对应 Rust 的 ExactSizeIterator::len:返回剩余元素个数。

func (*ProgressBarIter[T]) Next

func (p *ProgressBarIter[T]) Next() (T, bool)

Next 对应 Rust 的 Iterator::next: 取到元素就 inc(1);取完了且进度条未结束,则 finish_using_style()(用样式里存的完成行为, 默认是 AndClear,不是 Finish() 的 AndLeave)。

func (*ProgressBarIter[T]) NextBack

func (p *ProgressBarIter[T]) NextBack() (T, bool)

NextBack 对应 Rust 的 DoubleEndedIterator::next_back,推进逻辑与 next 相同。

func (*ProgressBarIter[T]) WithElapsed

func (p *ProgressBarIter[T]) WithElapsed(elapsed time.Duration) *ProgressBarIter[T]

func (*ProgressBarIter[T]) WithFinish

func (p *ProgressBarIter[T]) WithFinish(f ProgressFinish) *ProgressBarIter[T]

WithFinish 对应 Rust 的 with_finish(finish: ProgressFinish),整个 ProgressFinish(含 Msg)透传。

func (*ProgressBarIter[T]) WithMessage

func (p *ProgressBarIter[T]) WithMessage(msg string) *ProgressBarIter[T]

func (*ProgressBarIter[T]) WithPosition

func (p *ProgressBarIter[T]) WithPosition(pos uint64) *ProgressBarIter[T]

func (*ProgressBarIter[T]) WithPrefix

func (p *ProgressBarIter[T]) WithPrefix(prefix string) *ProgressBarIter[T]

func (*ProgressBarIter[T]) WithStyle

func (p *ProgressBarIter[T]) WithStyle(style ProgressStyle) *ProgressBarIter[T]

type ProgressDrawTarget

type ProgressDrawTarget interface {
	IsHidden() bool
	IsStderr() bool
	Drawable(force bool) Drawable
	DrawableWithNow(force bool, now time.Time) Drawable
	Width() *uint16
	// 返回 (remoteState, idx, ok);idx 对应 Rust 的 `MultiStateIndex(usize)`
	Remote() (*RemoteStub, uint, bool)
	Disconnect(now time.Time)
	AdjustLastLineCount(adjust LineAdjust)
	// MarkZombie 对应 Rust 的 ProgressDrawTarget::mark_zombie:只有 Remote 变体(挂在
	// MultiProgress 上的那条 bar)会真做事 —— 通知 MultiState 这条 bar 已"死亡"。
	MarkZombie()
}

ProgressDrawTarget 接口:抽象出绘制目标的必要方法(逐步完善) ProgressDrawTarget 接口:抽象出绘制目标的必要方法(逐步完善)

Rust 侧的入口是 `drawable(force_draw, now)`,now 一路透传给速率限制器, 所以 Go 这边以 DrawableWithNow 为准,Drawable(force) 只是「取当前时刻」的便捷包装。

func NewHiddenDrawTarget

func NewHiddenDrawTarget() ProgressDrawTarget

NewHiddenDrawTarget 对应 Rust 的 `hidden()`:完全不渲染。

func NewInMemoryDrawTarget

func NewInMemoryDrawTarget(t *InMemoryTerm) ProgressDrawTarget

NewInMemoryDrawTarget 创建一个使用 InMemoryTerm 的 draw target(用于测试)。 对应 Rust 里 `ProgressDrawTarget::term_like(Box::new(InMemoryTerm::new(..)))` 的用法:不限速。

func NewRemoteDrawTarget

func NewRemoteDrawTarget(ms *MultiState, idx uint) ProgressDrawTarget

func NewStderrDrawTarget

func NewStderrDrawTarget() ProgressDrawTarget

NewStderrDrawTarget 对应 Rust 的 `stderr()`:buffered stderr,每秒最多 20 次。 这是进度条的默认绘制目标(New / NoLength / NewSpinner 都用它)。

func NewStderrDrawTargetWithHz

func NewStderrDrawTargetWithHz(refreshRate uint8) ProgressDrawTarget

NewStderrDrawTargetWithHz 对应 Rust 的 `stderr_with_hz(refresh_rate)`。

func NewStdoutDrawTarget

func NewStdoutDrawTarget() ProgressDrawTarget

NewStdoutDrawTarget 对应 Rust 的 `stdout()`:buffered stdout,每秒最多 20 次。

func NewStdoutDrawTargetWithHz

func NewStdoutDrawTargetWithHz(refreshRate uint8) ProgressDrawTarget

NewStdoutDrawTargetWithHz 对应 Rust 的 `stdout_with_hz(refresh_rate)`。

func NewTermDrawTarget

func NewTermDrawTarget(term TermLike, refreshRate uint8) ProgressDrawTarget

NewTermDrawTarget 对应 Rust 的 `term(term, refresh_rate)`。

func NewTermLikeDrawTarget

func NewTermLikeDrawTarget(termLike TermLike) ProgressDrawTarget

NewTermLikeDrawTarget 对应 Rust 的 `term_like(term_like)`: 注意它没有默认刷新率(不限速),需要限速请用 NewTermLikeDrawTargetWithHz。

func NewTermLikeDrawTargetWithHz

func NewTermLikeDrawTargetWithHz(termLike TermLike, refreshRate uint8) ProgressDrawTarget

NewTermLikeDrawTargetWithHz 对应 Rust 的 `term_like_with_hz(term_like, refresh_rate)`。

type ProgressFinish

type ProgressFinish struct {
	Kind FinishKind
	Msg  string
}

func DefaultProgressFinish

func DefaultProgressFinish() ProgressFinish

type ProgressReaderIter

type ProgressReaderIter struct {
	// contains filtered or unexported fields
}

func NewProgressReaderIter

func NewProgressReaderIter(r io.Reader, pb *ProgressBar) *ProgressReaderIter

func (*ProgressReaderIter) Read

func (pr *ProgressReaderIter) Read(b []byte) (int, error)

type ProgressState

type ProgressState struct {
	// contains filtered or unexported fields
}

func NewProgressState

func NewProgressState(len *uint64, pos *AtomicPosition) ProgressState

func (*ProgressState) Duration

func (ps *ProgressState) Duration() time.Duration

Duration 返回预计总时长,对应 Rust 的 ProgressState::duration():

  • 完成态(DoneVisible/DoneHidden):返回落库的时长;
  • 进行中且已知长度:已用时间 + ETA(Rust 的 saturating_add);
  • 进行中且未知长度:0。

func (*ProgressState) Elapsed

func (ps *ProgressState) Elapsed() time.Duration

func (*ProgressState) Eta

func (ps *ProgressState) Eta() time.Duration

func (*ProgressState) Fraction

func (ps *ProgressState) Fraction() float32

func (*ProgressState) IsFinished

func (ps *ProgressState) IsFinished() bool

func (*ProgressState) Len

func (ps *ProgressState) Len() *uint64

func (*ProgressState) PerSec

func (ps *ProgressState) PerSec() float64

PerSec 对应 Rust 的 per_sec:进行中用估算器的平滑速率; 已完成则用「总步数 / 总耗时」这个真实平均速率(Rust 明确分了两支)。

func (*ProgressState) Pos

func (ps *ProgressState) Pos() uint64

func (*ProgressState) SetLen

func (ps *ProgressState) SetLen(v uint64)

func (*ProgressState) SetPos

func (ps *ProgressState) SetPos(v uint64)

type ProgressStyle

type ProgressStyle struct {
	// contains filtered or unexported fields
}

func DefaultProgressStyleBar

func DefaultProgressStyleBar() ProgressStyle

func DefaultProgressStyleSpinner

func DefaultProgressStyleSpinner() ProgressStyle

func NewProgressStyle

func NewProgressStyle(tpl Template) ProgressStyle

NewProgressStyle constructs a ProgressStyle using the provided template and initializes other defaults (tick strings, progress chars, char width, tab width). This mirrors Rust's `Self::new(template)` constructor so callers doing `ProgressStyle::with_template(template)` will get the same initialization order.

func ProgressStyleWithTemplate

func ProgressStyleWithTemplate(template string) (ProgressStyle, error)

ProgressStyleWithTemplate creates a ProgressStyle based on the default bar but replaces the template with the provided template string. This mirrors the Rust API `ProgressStyle::with_template("...")` used in tests.

func (*ProgressStyle) FormatState

func (ps *ProgressStyle) FormatState(state *ProgressState, targetWidth int, forStderr bool) ([]LineType, []string)

FormatState 将 ProgressState 格式化为若干行及对应文本内容(返回 line types 与 contents)。 这是一个简化实现,支持常见占位符替换并返回渲染文本,便于 DrawStateStub.contents 填充。

func (ProgressStyle) ProgressChars

func (ps ProgressStyle) ProgressChars(s string) ProgressStyle

Builder-style methods to mirror Rust's chaining API (consume-and-return Self) ProgressChars mirrors Rust's `progress_chars` and returns an updated copy.

func (*ProgressStyle) SetForStderr

func (ps *ProgressStyle) SetForStderr()

SetForStderr updates placeholder-level styles to their stderr variants.

func (*ProgressStyle) SetProgressChars

func (ps *ProgressStyle) SetProgressChars(s string)

SetProgressChars sets the progress characters sequence like "##-". Each rune becomes a cluster in progressChars; updates charWidth accordingly.

func (*ProgressStyle) SetTabWidth

func (ps *ProgressStyle) SetTabWidth(w int)

func (ProgressStyle) Template

func (ps ProgressStyle) Template(s string) (ProgressStyle, error)

Template mirrors Rust's `template(mut self, s: &str) -> Result<Self, TemplateError>` It parses the template and returns the updated ProgressStyle or an error.

func (ProgressStyle) TickChars

func (ps ProgressStyle) TickChars(s string) ProgressStyle

TickChars mirrors Rust's `tick_chars` which accepts a string of grapheme clusters.

func (ProgressStyle) TickStrings

func (ps ProgressStyle) TickStrings(ss []string) ProgressStyle

TickStrings mirrors Rust's `tick_strings` which accepts a slice of strings.

func (*ProgressStyle) WithKey

func (ps *ProgressStyle) WithKey(key string, f func(*ProgressState) string)

WithKey registers a custom formatter for a template key.

func (*ProgressStyle) WithKeyStyle

func (ps *ProgressStyle) WithKeyStyle(key string, f func(*ProgressState, bool) (string, *Style))

WithKeyStyle registers a custom formatter that may also return a *Style to apply to the rendered text. Formatter-provided styles take precedence over placeholder-level style/alt-style.

func (*ProgressStyle) WithTracker

func (ps *ProgressStyle) WithTracker(key string, t ProgressTracker)

WithTracker registers a ProgressTracker directly (closest to Rust API).

type ProgressTracker

type ProgressTracker interface {
	Clone() ProgressTracker
	Tick(state *ProgressState, now time.Time)
	Reset(state *ProgressState, now time.Time)
	Write(state *ProgressState, w *tabWriter)
}

ProgressTracker mirrors Rust's trait: it can be stateful, tick/reset, and write its representation into a writer.

type ProgressWriterIter

type ProgressWriterIter struct {
	// contains filtered or unexported fields
}

func NewProgressWriterIter

func NewProgressWriterIter(w io.Writer, pb *ProgressBar) *ProgressWriterIter

func (*ProgressWriterIter) Flush

func (pw *ProgressWriterIter) Flush() error

Flush 对应 Rust 的 io::Write::flush:直接透传给底层 writer。

func (*ProgressWriterIter) Write

func (pw *ProgressWriterIter) Write(b []byte) (int, error)

type RateLimiter

type RateLimiter struct {
	// contains filtered or unexported fields
}

RateLimiter mirrors the Rust implementation: interval in milliseconds, a capacity allowing occasional bursts, and a timestamp of the previous allowance calculation.

type RemoteStub

type RemoteStub struct {
	// contains filtered or unexported fields
}

RemoteStub references a MultiState for remote operations

func (*RemoteStub) StateWrite

func (r *RemoteStub) StateWrite() *MultiStateStub

type ResetMode

type ResetMode int

ResetMode 与 Rust 的 Reset

const (
	ResetEta ResetMode = iota
	ResetElapsed
	ResetAll
)

type SafeBarState

type SafeBarState struct {
	// contains filtered or unexported fields
}

SafeBarState 是对 BarState 的线程安全包装,模拟 Rust 中的 Arc<Mutex<BarState>> 行为。

func NewSafeBarState

func NewSafeBarState(b *BarState) *SafeBarState

func (*SafeBarState) DecLength

func (s *SafeBarState) DecLength(now time.Time, d uint64)

func (*SafeBarState) Draw

func (s *SafeBarState) Draw(force bool) error

func (*SafeBarState) DrawWithNow

func (s *SafeBarState) DrawWithNow(force bool, now time.Time) error

func (*SafeBarState) Duration

func (s *SafeBarState) Duration() time.Duration

func (*SafeBarState) Elapsed

func (s *SafeBarState) Elapsed() time.Duration

func (*SafeBarState) Eta

func (s *SafeBarState) Eta() time.Duration

func (*SafeBarState) FinishUsingStyle

func (s *SafeBarState) FinishUsingStyle(now time.Time, f ProgressFinish)

func (*SafeBarState) FormatForWidth

func (s *SafeBarState) FormatForWidth(width int) ([]LineType, []string)

FormatForWidth returns the formatted lines and contents for the bar under the SafeBarState lock.

func (*SafeBarState) GetOnFinish

func (s *SafeBarState) GetOnFinish() ProgressFinish

func (*SafeBarState) IncLength

func (s *SafeBarState) IncLength(now time.Time, d uint64)

func (*SafeBarState) Index

func (s *SafeBarState) Index() (uint, bool)

Index 对应 Rust 的 `ProgressBar::index() -> Option<MultiStateIndex>`(usize → uint)。

func (*SafeBarState) IsFinished

func (s *SafeBarState) IsFinished() bool

Accessors for inner ProgressState values

func (*SafeBarState) IsHidden

func (s *SafeBarState) IsHidden() bool

func (*SafeBarState) Len

func (s *SafeBarState) Len() *uint64

func (*SafeBarState) Message

func (s *SafeBarState) Message() string

func (*SafeBarState) PerSec

func (s *SafeBarState) PerSec() float64

func (*SafeBarState) Pos

func (s *SafeBarState) Pos() uint64

func (*SafeBarState) Position

func (s *SafeBarState) Position() uint64

func (*SafeBarState) Prefix

func (s *SafeBarState) Prefix() string

func (*SafeBarState) Println

func (s *SafeBarState) Println(now time.Time, msg string)

func (*SafeBarState) Reset

func (s *SafeBarState) Reset(now time.Time, mode ResetMode)

func (*SafeBarState) SetDrawTarget

func (s *SafeBarState) SetDrawTarget(dt ProgressDrawTarget)

func (*SafeBarState) SetElapsed

func (s *SafeBarState) SetElapsed(d time.Duration)

SetElapsed sets the progress start time so that elapsed time equals d.

func (*SafeBarState) SetLength

func (s *SafeBarState) SetLength(now time.Time, l uint64)

func (*SafeBarState) SetMessage

func (s *SafeBarState) SetMessage(msg string)

func (*SafeBarState) SetOnFinish

func (s *SafeBarState) SetOnFinish(f ProgressFinish)

func (*SafeBarState) SetPos

func (s *SafeBarState) SetPos(v uint64)

func (*SafeBarState) SetPrefix

func (s *SafeBarState) SetPrefix(prefix string)

func (*SafeBarState) SetStyle

func (s *SafeBarState) SetStyle(style ProgressStyle)

func (*SafeBarState) SetTabWidth

func (s *SafeBarState) SetTabWidth(w int)

func (*SafeBarState) Style

func (s *SafeBarState) Style() ProgressStyle

func (*SafeBarState) Suspend

func (s *SafeBarState) Suspend(now time.Time, f func() interface{}) interface{}

func (*SafeBarState) TabWidth

func (s *SafeBarState) TabWidth() int

func (*SafeBarState) Tick

func (s *SafeBarState) Tick(now time.Time)

func (*SafeBarState) UnsetLength

func (s *SafeBarState) UnsetLength(now time.Time)

func (*SafeBarState) Update

func (s *SafeBarState) Update(now time.Time, f func(*ProgressState), tick bool)

func (*SafeBarState) VisualIndex

func (s *SafeBarState) VisualIndex() (uint, bool)

VisualIndex 对应 Rust 的 `ProgressBar::visual_index()`: 取所属 MultiProgress 里的**屏幕位置**(ordering 中的下标)。

type SeekMax

type SeekMax struct {
	// contains filtered or unexported fields
}

SeekMax 记住最近 HISTORY 次位置里最大的那个,用来把抖动的 seek 摊平成单调的位置显示。 与 Rust 一致:缓冲只在发生过 seek 之后才启用(Rust 里是 Option), 连续 RESET 次顺序读写之后丢弃历史回到「直通」模式。

func NewSeekMax

func NewSeekMax() *SeekMax

func (*SeekMax) UpdateSeek

func (s *SeekMax) UpdateSeek(newpos uint64) uint64

UpdateSeek 对应 Rust 的 update_seek:一旦 seek 过就启用缓冲并清掉顺序计数。

func (*SeekMax) UpdateSeq

func (s *SeekMax) UpdateSeq(prev uint64, delta uint64) uint64

UpdateSeq 对应 Rust 的 update_seq。

type Status

type Status struct {
	// contains filtered or unexported fields
}

func StatusDoneHidden

func StatusDoneHidden(d time.Duration) Status

func StatusDoneVisible

func StatusDoneVisible(d time.Duration) Status

func StatusInProgress

func StatusInProgress() Status

func (Status) Duration

func (s Status) Duration() time.Duration

Duration 返回完成态落库的时长;进行中返回 0。

func (Status) Kind

func (s Status) Kind() StatusKind

Kind 返回状态类别。

type StatusKind

type StatusKind int

Status 对应 Rust 的 `enum Status { InProgress, DoneVisible(Duration), DoneHidden(Duration) }`。 完成态必须携带落库时长(Rust 由 enum 的字段承载),ProgressState.Duration() 依赖它。

const (
	StatusKindInProgress StatusKind = iota
	StatusKindDoneVisible
	StatusKindDoneHidden
)

type StdTerm

type StdTerm struct {
	// contains filtered or unexported fields
}

StdTerm 是一个简单的终端实现,向指定的 io.Writer 写入,并通过 ANSI 控制序列移动光标。

func NewStdTerm

func NewStdTerm() *StdTerm

NewStdTerm 使用 stdout 创建默认终端,对应 Rust 的 `Term::buffered_stdout()` (`ProgressDrawTarget::stdout()` 用的就是这个,带缓冲)。

func NewStdTermWithWriter

func NewStdTermWithWriter(w io.Writer) *StdTerm

NewStdTermWithWriter creates a StdTerm that writes to the provided writer.

注意:这个便捷构造**不带缓冲**(写什么立刻进 writer)。上游没有直接对应的构造, 带缓冲的那两个是 `buffered_stdout()` / `buffered_stderr()` —— 要走缓冲语义请用 NewStdTerm / NewStderrTerm。

func NewStderrTerm

func NewStderrTerm() *StdTerm

NewStderrTerm 使用 stderr 创建终端,对应 Rust 的 `Term::buffered_stderr()`。 进度条的默认绘制目标是 stderr,所以 `ProgressDrawTarget::stderr()` 走的是这个。

func (*StdTerm) ClearLine

func (t *StdTerm) ClearLine() error

ClearLine 使用 ANSI 序列清除当前行并回到行首。

func (*StdTerm) Flush

func (t *StdTerm) Flush() error

Flush 对应 Rust 的 `Term::flush()`:

if let Some(ref buffer) = self.inner.buffer {
    let mut buffer = buffer.lock().unwrap();
    if !buffer.is_empty() {
        self.write_through(&buffer[..])?;   // 一次性落盘
        buffer.clear();
    }
}

一帧只 flush 一次(indicatif 在 draw_to_term 末尾调),所以终端每帧只重绘一次 —— 这就是"丝滑"与"闪"的分界:带缓冲时清屏与重画合成一次写,不带缓冲时终端会看到 中间的清屏状态。不带缓冲时退化成原来"底层 writer 有 Flush 就调"的行为。

func (*StdTerm) Height

func (t *StdTerm) Height() uint16

Height 同 Width:每次现问(Rust 的 `Term::height()` → `size().0`)。

func (*StdTerm) IsTerm

func (t *StdTerm) IsTerm() bool

IsTerm 对应 Rust 的 `console::Term::is_term()`:是不是真实终端(而非文件/管道)。

func (*StdTerm) MoveCursorDown

func (t *StdTerm) MoveCursorDown(n int) error

func (*StdTerm) MoveCursorLeft

func (t *StdTerm) MoveCursorLeft(n int) error

func (*StdTerm) MoveCursorRight

func (t *StdTerm) MoveCursorRight(n int) error

func (*StdTerm) MoveCursorUp

func (t *StdTerm) MoveCursorUp(n int) error

func (*StdTerm) Width

func (t *StdTerm) Width() uint16

Width 对应 Rust 的 `console::Term::width()`:

let (_, w) = term.size(); // size() = size_checked().unwrap_or((24, DEFAULT_WIDTH))

终端窗口是可缩放的,进度条每帧都要按**当前**宽度重排;构造时量一次就存死的话, 缩放之后要么超宽折行、要么只画一截补不满整行。

func (*StdTerm) WriteLine

func (t *StdTerm) WriteLine(s string) error

func (*StdTerm) WriteStr

func (t *StdTerm) WriteStr(s string) error

WriteStr 对应 Rust 的 `Term::write_str()`:

match self.inner.buffer {
    Some(ref buffer) => buffer.lock().unwrap().write_all(s.as_bytes()),
    None => self.write_through(s.as_bytes()),
}

type Style

type Style struct {
	Spec    string
	SpecErr string // optional alternate spec for stderr
}

Style represents a simple style descriptor (wraps the style spec string) that can be applied to text to produce ANSI-wrapped output.

func (*Style) ApplyFor

func (s *Style) ApplyFor(text string, forStderr bool) string

type TabExpandedString

type TabExpandedString struct {
	// contains filtered or unexported fields
}

--- TabExpandedString ---

func NewTabExpandedString

func NewTabExpandedString(s string, tabWidth int) TabExpandedString

func (*TabExpandedString) Expanded

func (t *TabExpandedString) Expanded() string

func (*TabExpandedString) SetTabWidth

func (t *TabExpandedString) SetTabWidth(w int)

type Template

type Template struct {
	Parts []TemplatePart
	// contains filtered or unexported fields
}

func Template_from_str

func Template_from_str(s string) (Template, error)

Template_from_str mirrors Rust's Template::from_str(s)

func Template_from_str_with_tab_width

func Template_from_str_with_tab_width(s string, tab_width int) (Template, error)

Template_from_str_with_tab_width 是 Rust 的 Template::from_str_with_tab_width 的直译: 同一个状态机、同一套分支,包括

  • `{{` → 字面量 `{`、`}}` → 字面量 `}`(Rust 的 MaybeOpen/DoubleClose 两支)
  • 键名位置遇到 ASCII 空白 → 回退成字面量 "{...}"(Rust 的 backtrack)
  • `{key!}` / `{key:>10!}` 的截断位
  • 无法匹配的状态+字符 → 返回 TemplateError(Rust 是 Err,Go 之前恒返回 nil)

func (*Template) SetTabWidth

func (t *Template) SetTabWidth(newTabWidth int)

type TemplateError

type TemplateError struct {
	State templateState
	Next  rune
}

TemplateError 对应 Rust 的 `pub struct TemplateError { state, next }` (Rust 的 Display:`TemplateError: unexpected character {:?} in state {:?}`)。

func (*TemplateError) Error

func (e *TemplateError) Error() string

type TemplatePart

type TemplatePart struct {
	IsPlaceholder bool
	Text          string
	Key           string
	Align         rune // '<' '^' '>' or 0
	Width         int  // 0 means none
	Truncate      bool
	Style         *Style
	AltStyle      *Style
}

Template -----------------------------------------------------------------

type TermLike

type TermLike interface {
	Width() uint16
	Height() uint16
	MoveCursorUp(n int) error
	MoveCursorDown(n int) error
	MoveCursorRight(n int) error
	MoveCursorLeft(n int) error
	WriteLine(s string) error
	WriteStr(s string) error
	ClearLine() error
	Flush() error
}

TermLike 表示最小的终端行为抽象(源自 src/term_like.rs),中文注释对应 Rust 注释。

type TickerHandle

type TickerHandle struct {
	// contains filtered or unexported fields
}

TickerHandle 是一个简单 ticker 控制句柄,供 EnableSteadyTick 使用。

func NewTickerHandle

func NewTickerHandle(interval time.Duration, pb *ProgressBar) *TickerHandle

NewTickerHandle 启动后台 ticker,语义对应 Rust 的 `Ticker::new` + `TickerControl::run`: 循环体是「先判完成 → tick → 等一个 interval」,进度条一完成就自行退出,不需要调用方显式停。 另一条退出路径(进度条被回收)由 SafeBarState 上的 finalizer 兜住,等价于 Rust 的 `Weak::upgrade()` 失败。

func (*TickerHandle) Stop

func (th *TickerHandle) Stop()

type VisualLines

type VisualLines int

VisualLines represents a count of visual lines (wrap-aware).

func VisualLinesFromInt

func VisualLinesFromInt(i int) VisualLines

func (VisualLines) AsInt

func (v VisualLines) AsInt() int

func (VisualLines) SaturatingAdd

func (v VisualLines) SaturatingAdd(o VisualLines) VisualLines

func (VisualLines) SaturatingSub

func (v VisualLines) SaturatingSub(o VisualLines) VisualLines

type WeakProgressBar

type WeakProgressBar struct {
	// contains filtered or unexported fields
}

弱引用类型

func NewWeakProgressBar

func NewWeakProgressBar() WeakProgressBar

func (WeakProgressBar) Upgrade

func (w WeakProgressBar) Upgrade() *ProgressBar

type Width

type Width struct{}

padAndTruncate returns a string that when measured occupies exactly width columns according to measureTextWidth. If truncate is true, content is truncated to fit. Width 对应 Rust 的 `pub struct Width`:宽度的计算入口,带一个全局的 「歧义宽度(CJK)」开关。

Rust 里宽度计算分散在 `measure_text_width` / `UnicodeWidthChar::width` 两处, 0.18.6 把它们收进了这个结构,并允许切换 CJK 口径:

WIDTH.char('█')     // 默认 1,set_default_cjk(true) 后 2
WIDTH.str(s)        // 纯文本宽度
WIDTH.ansi_str(s)   // 跳过 ANSI 段后的可见宽度

func (Width) SetDefaultCJK

func (Width) SetDefaultCJK(isCJK bool)

SetDefaultCJK 对应 Rust 的 `Width::set_default_cjk(is_cjk)`。

打开后,"歧义宽度"字符(如 █、○、± 等 East Asian Ambiguous)按 2 列计算, 适合终端**真的**把方块字符渲染成双宽的 CJK 环境(Rust 侧是 `UnicodeWidthChar::width_cjk` / `UnicodeWidthStr::width_cjk`)。 只影响本包,不去改 go-runewidth 的全局 DefaultCondition。

Directories

Path Synopsis
对应上游 examples/cargo.rs:模仿 cargo 编译时的输出(并不真的调用 cargo)。
对应上游 examples/cargo.rs:模仿 cargo 编译时的输出(并不真的调用 cargo)。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL