mpb

package module
v0.1.6 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

github.com/quant1x/mpb 是 Rust 进度条库 indicatif 的 Go / Python / C++ 三语言移植。三个实现都按模块逐一对照上游(style / state / draw_target / multi / progress_bar / iter / format / in_memory / term_like), 目标是与 Rust 0.18.6 逐语义对齐:同样的模板语法、同样的宽度与换行度量、 同样的节流刷新、多进度条/树形嵌套、清除与僵尸行(zombie)算法。 Python 与 C++ 版本均已完成对齐;Python 代码与 Go 并排放在仓库根目录(组织方式同 mopr), C++ 代码以 .h / .cpp 与它们同目录并排,pyproject.toml / CMakeLists.txt 也在根目录。

来源

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

本文档用尖括号表示需要自行替换的变量:

  • <UPSTREAM_DIR> —— 本地克隆 indicatif 的目录,例如 d:/projects/rust/indicatif
  • <OLD_COMMIT> —— 要对比的上游提交

源码树里不再随附 Rust 源码:上游的 .rs、examples/、tests/、Cargo.toml 等已全部移除, 改 Go/Python 时直接看 <UPSTREAM_DIR>。要对比两个版本的差异:

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

已知同步点:<OLD_COMMIT> 取 3adb05c 之前的那次提交,即可看到 0.18.6 这一批改动。

模块对照

Rust(上游) Go Python C++ 内容
style.rs style.go style.py style.h / style.cpp 模板解析({bar:40.red/blue})、样式(on_* 背景、256 色、真彩色)、宽度度量
state.rs state.go state.py state.h / state.cpp BarState / ProgressState、绘制状态与出帧、Estimator
draw_target.rs draw_target.go draw_target.py draw_target.h / draw_target.cpp 绘制目标(终端 / term-like / multi / hidden)、限速、行数调整
multi.rs multi.go multi.py multi.h / multi.cpp MultiProgress / MultiState、成员排序、orphan 行、僵尸行
progress_bar.rs progress_bar.go progress_bar.py progress_bar.h / progress_bar.cpp ProgressBar 门面
iter.rs / rayon.rs iter.go / rayon.go iter.py iter.h 迭代器包装
format.rs format.go format.py format.h / format.cpp HumanBytes / HumanDuration / HumanFloatCount 等格式化
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 内存终端(测试用)与终端抽象
lib.rs doc.go __init__.py mpb.h 包文档与入口

C++ 另有 types.h(共享枚举/时间类型)、utf8.h(UTF-8 编解码)、 unicode_width_tables.h(Unicode 宽度区间表);构建入口是根目录 CMakeLists.txt, 版本号由 git_tag_info.cmake 从 git tag 获取(与 mopr 的做法一致)。

Rust 的 Drop for BarState 由 Go 的 weakref.go、Python 的 WeakProgressBar + BarState.__del__、C++ 的 std::weak_ptr + BarState 析构函数对应实现。

表中的 Go / Python / C++ 三列同目录并排存放:style.go、style.py、style.h、 style.cpp 是同级文件,examples/<name>.go、<name>.py、<name>.cpp 也是同级文件。 上游源码见上面的本地副本路径。

示例与效果

16 个录屏示例与上游 examples/ 一一对应,动画用 VHS 录制, tape 文件与 GIF 同名,都在 screenshots/:

批量重录用 scripts/ 下的两个脚本(PowerShell 与 bash 各一份,行为一致;脚本自己会切到 仓库根目录,所以从任何地方调用都行 —— tape 里的 Output 路径相对 cwd 解析):

./scripts/generate.ps1              # 全部 16 条
./scripts/generate.ps1 single log   # 只重录指定的几条(基名,不带扩展名)

$env:VHS = 'c:\runtime\work\bin\vhs.exe'   # vhs 不在 PATH 里时这么指定
./scripts/generate.ps1
./scripts/generate.sh              # 全部 16 条
./scripts/generate.sh single log   # 只重录指定的几条

VHS=/path/to/vhs ./scripts/generate.sh

两条脚本都会跳过 _ 开头的探针 tape,逐条打印产物大小与耗时,失败时列出失败的 tape 并以 退出码 1 结束。

cargo

模拟 cargo 编译时的输出(并不真的调用 cargo):4 个 worker 并发从 crate 列表取任务, 主线程负责画进度条并打 Compiling 行。

go run ./examples cargo

cargo

cargowrap

把 cargo build --release 的 stderr 逐行喂给一个 spinner(对应上游 cargowrap.rs)。 本机需装 cargo,且要在 Rust 工程目录里跑 —— 录屏里先编成 exe,再到 %TEMP% 现建一个带依赖的 空 crate 来跑(见 screenshots/cargowrap.tape)。

go run ./examples cargowrap

cargowrap

download

模拟下载进度,演示 {bytes}/{total_bytes} 与自定义 eta key(Rust 的 with_key)。

go run ./examples download

download

download-continued

断点续传:起始位置不为 0,并调用 ResetEta() 让 ETA 从当前位置重新估算。

go run ./examples download-continued

download-continued

download-speed

在 download 的基础上多了 {bytes_per_sec}。

go run ./examples download-speed

download-speed

fastbar

极大量、每次更新都极快的场景,用来看限速(默认 20Hz)下的出帧率与 Elapsed() 的耗时统计。

go run ./examples fastbar

fastbar

finebars

同一个 MultiProgress 里 5 条不同粒度、不同颜色的条各自独立推进 (Rust 用 thread::spawn,Go 用 goroutine)。

go run ./examples finebars

finebars

iterator

三种迭代器包装:

  1. Progress(slice) —— 用切片长度当总数(Rust 的 size_hint)
  2. ProgressCount(slice, n) —— 显式指定元素个数
  3. ProgressWithSlice(slice, pb) —— 用自定义样式的进度条

取完元素时迭代器会按样式里的完成行为收尾(默认 FinishUsingStyle)。

go run ./examples iterator

iterator

log

边推进边用 Println 打日志:日志行走 MultiState 的 orphan 行通道,不会把进度条画面冲乱。

go run ./examples log

log

long-spinner

steady tick + 自定义 spinner 帧(更多帧见 cli-spinners)。

go run ./examples long-spinner

long-spinner

morebars

MultiProgress 里一条总进度条统着多条子进度条。

go run ./examples morebars

morebars

multi-tree

树形排列的进度条:元素按缩进逐级加入 MultiProgress,各自推进到满;整棵树填满后收尾, 最后把树按缩进打印出来做对照。

go run ./examples multi-tree

multi-tree

multi-tree-ext

multi-tree 的扩展版:除了「加进度条 / 推进进度条」,还能从树里摘掉进度条 (要摘的都是 temp_*),并演示 MultiProgress 的垂直对齐 —— 加 --bottom-alignment 改成底部对齐。

go run ./examples multi-tree-ext              # 录屏用的是这个
go run ./examples multi-tree-ext --bottom-alignment

multi-tree-ext

single

最基础的单个进度条(1024 步 × 5ms,默认模板 {wide_bar} {pos}/{len})。

go run ./examples single

single

tokio

定时器驱动进度条:Rust 用 tokio 的 interval + block_on,Go 用 time.Ticker,语义等价 (每 5ms 一个 tick,共 1024 步)。

go run ./examples tokio

tokio

yarnish

模拟 yarn 安装时的四段式输出(解析 → 拉取 → 链接 → 构建),最后用 HumanDuration 报总耗时。

go run ./examples yarnish

yarnish

索引的两套语义(与 Rust 一致)

API Rust Go 含义
Index() index() -> Option<MultiStateIndex>(usize) (uint, bool) 不透明槽位下标,会被 free_set 复用,与屏幕先后无关
VisualIndex() visual_index() -> Option<usize> (uint, bool) 屏幕位置(第几行)
Insert(idx, pb) / InsertFromBack(idx, pb) insert(index: usize, ..) index uint 插入位置

要"第几条 bar"用 VisualIndex(),不要用 Index()。

与上游的有意差异

  • 宽度开关: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)。
  • MultiProgress 的 State 字段已导出(对应 Rust 0.18.6 的 pub state);访问前要先加 MultiState 自带的 RWMutex(等价于 Rust 的 read() / write())。

Go 构建与验证

go build ./...
go test ./...
go run ./examples multi -capture   # 渲染到内存终端,输出落在 examples/multi_capture.out

C++ 版本

C++ 实现与 Go/Python 同目录并排:style.h / style.cpp 与 style.go / style.py 同级,入口头文件是 mpb.h,构建入口是根目录 CMakeLists.txt。运行时不依赖第三方库, 要求 C++20;版本号由 git_tag_info.cmake 从 git tag 读取(与 mopr 的做法一致)。

C++ 版本已实现与 Rust indicatif 0.18.6 的语义对齐,覆盖模板/样式/ANSI、宽度与换行 度量、20Hz 节流与令牌桶、估算器、单/多进度条、树形嵌套、println / clear / suspend、 u64 边界、Drop/僵尸行与内存终端。宽度表由 Rust unicode-width 0.2.2(indicatif 使用的 同一版本)生成,包含 width / width_cjk 以及 emoji ZWJ、VS16、keycap 等序列规则; 极少数阿拉伯/希伯来/印度文字连字仍按字符合成(未复刻该 crate 的完整连字状态机)。

#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=0.1.5 显式指定版本号。

17 个示例都同时有 examples/<name>.go、<name>.py、<name>.cpp。所有 examples/*.cpp 编译进一个 mpb_examples 入口(参数是示例名),例如:

cmake --build build --target mpb_examples
./build/mpb_examples single
./build/mpb_examples multi --capture   # 输出 examples/multi_capture.out

不需要示例时用 -DMPB_BUILD_EXAMPLES=OFF。

本地验证:GCC 15(MinGW)、Clang 23、MSVC 19.44 均构建通过,mpb_tests 全部通过 (格式、模板/ANSI、宽条、MultiProgress、Drop/僵尸、迭代器、节流器、内存终端);17 个 C++ 示例也在三套编译器下构建通过。

C++ API 使用 snake_case 方法(inc / set_style / finish_with_message), 时间参数与返回值使用 std::chrono::nanoseconds,Bar 共享状态用 std::shared_ptr, MultiState 成员用 std::weak_ptr 恢复 Rust 的 Drop/僵尸语义。

Python 版本

Python 实现与 Go/C++ 实现同目录并排存放(与 mopr 的组织方式一致):仓库根目录的 *.py 与同名 *.go / *.h / *.cpp 一一对应,pyproject.toml 也在根目录,包名即 mpb。 无第三方运行时依赖(Python ≥ 3.10)。

Python 版本已实现与 Rust indicatif 0.18.6(commit 3adb05c)的语义对齐,覆盖 模板/样式/ANSI、宽度与换行度量、20Hz 节流与令牌桶、估算器、单/多进度条、树形嵌套、 println / clear / suspend、u64 边界、Drop/僵尸行与内存终端。Go 与 Python 使用 同一组输入逐项比对:53 个模板解析、36,928 个 format_bar 组合、16 个渲染场景、 31 个 ANSI 样式用例以及 MultiProgress 场景,结果一致。

模块对应关系见上文「模块对照」。

安装与使用(在仓库根目录执行):

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")

多条进度条:

from mpb import MultiProgress, ProgressBar

mp = MultiProgress()
one = mp.add(ProgressBar(100))
two = mp.add(ProgressBar(200))
mp.println("start")

公开 API 使用 Python 的 snake_case(inc / set_style / finish_with_message), 渲染与状态语义与 Rust/Go 一致:同样的模板语法、限速、僵尸行算法与终端宽度度量。 默认绘制目标仍是 stderr,重定向到文件/管道时整条进度条隐藏;要在测试里拿渲染结果请用 InMemoryTerm + in_memory_draw_target。

Python 与 Go 的语言层差异

下面这些差异来自语言/运行时,不是 Rust 语义偏差;Rust 的模板、限速、多进度条、 清除与 Drop/僵尸行语义均已完成对齐:

  • 时间单位:Python 的 eta() / elapsed() / duration() / set_elapsed() / enable_steady_tick() / human_duration() / formatted_duration() 使用秒(float), Go 使用 time.Duration;数值等价。
  • 错误处理:Python 用异常(TemplateError、ValueError),Go 用 (value, error); MultiProgress.println() / clear() 在 Python 返回 None。
  • 迭代器:Python 的 progress() 支持任意可迭代对象/生成器(未知长度时 bar 无总长), next_back() 需要可索引序列;Go 只包装切片。map_parallel() 用线程池保持输入顺序 (GIL 下 CPU 密集不会真正并行,I/O 密集可用)。
  • 格式化 API:Go 的 HumanBytes / HumanDuration / HumanFloatCount 等是实现了 String/Format 的类型,Python 是对应函数;输出逐字一致。
  • 样式拷贝:Python 的 set_style() / style() / with_* 按值语义克隆 ProgressStyle (template、tracker map 一并复制),避免 Go 结构体浅拷贝导致的共享;渲染结果一致。
  • 整数边界:位置/长度按 Rust/Go 的 u64 语义处理(位置回绕、长度与增量饱和); Python 内部是任意精度整数,因此在边界处显式取模/钳位,负数位置/增量直接抛 ValueError (Go 由 uint64 类型在编译期拒绝)。
  • 宽度表:Python 用 unicodedata + 手写规则,Rust 用 unicode-width 0.2.2, Go 用 go-runewidth,C++ 直接由 Rust unicode-width 0.2.2 生成 (width / width_cjk + emoji 序列规则)。Python/Go 与 Rust 在 ASCII/Latin/CJK/emoji/方块/盲文等常用区间一致;约 4k 个生僻/未分配码点 (主要是组合记号与 Unicode 版本差异)可能有 0/1/2 列差异。
  • 内存终端:Python 的 InMemoryTerm 是 VT100 子集(CSI A/B/C/D/H/f/K/J、SGR 忽略), Go 用 go-vte;mpb 自身产生的序列两边一致。
  • 标准终端:Python StdTerm 接收文本流(str),Go io.Writer 接收字节; 重定向/非 TTY 时两者都隐藏进度条。
  • 锁:Python 使用 RLock,suspend 回调内重入同一 bar/multi 不会死锁;Go/Rust 的 Mutex 非重入,这是 Python 侧更宽松的行为。
  • 回收机制:两版 MultiStateMember 都只保存 BarState 的弱引用,最后一个 ProgressBar 被回收时按 on_finish 收尾并 mark_zombie(与 Rust 的 Drop 一致)。 Go 用 runtime.SetFinalizer + weak registry,Python 用 weakref + BarState.__del__; 具体回收时机由运行时决定,不保证在确定时刻发生。

Python 示例从包入口 examples/__main__.py 调用:使用 python -m examples <name>, 不需要直接执行 examples/main.py(它只是内部 dispatcher)。

测试与示例(Python 测试沿用 *_test.py 命名,与 mopr 一致,用 pytest 收集):

python -m pytest                       # 65 个测试
python -m examples single         # 17 个示例,与 Go/C++ 示例一一对应
python -m examples multi-tree

每个示例在 examples/ 下都有 <name>.go、<name>.py 与 <name>.cpp,例如 cargo、cargowrap、download、download-continued、download-speed、 fastbar、finebars、iterator、log、long-spinner、morebars、multi、 multi-tree、multi-tree-ext、single、tokio、yarnish。

宽度口径与上游一致:█、░ 等歧义宽度字符按 1 列,调用 mpb.DEFAULT_WIDTH.set_default_cjk(True) 后按 2 列。版本号由 setuptools-scm 写入 _version.py(源码直接运行时回退到 0.1.5)。

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