mpb

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Oct 10, 2026 License: MIT Imports: 17 Imported by: 0

README

mpb

github.com/quant1x/mpb 是 Rust 进度条库 indicatif 的 Go 移植, 按模块逐一对照实现(style / state / draw_target / multi / progress_bar / iter / format / in_memory / term_like), 目标是与 Rust 侧逐语义对齐:同样的模板语法、同样的宽度与换行度量、同样的僵尸行(zombie)算法。

来源

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

本仓库不再随附 Rust 源码:上游的 .rs、examples/、tests/、Cargo.toml 等已全部移除, 改 Go 时直接看上游本地副本(d:\projects\rust\indicatif)。要对比两个版本的差异:

git -C d:/projects/rust/indicatif --no-pager diff <旧commit> HEAD -- src/

模块对照

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

(左侧是上游文件名,本仓库只有右列的 Go 文件;上游源码见上面的本地副本路径。)

索引的两套语义(与 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) (底层是 go-runewidth 的 EastAsianWidth 条件)。
  • MultiProgress 的 State 字段已导出(对应 Rust 0.18.6 的 pub state);访问前要先加 MultiState 自带的 RWMutex(等价于 Rust 的 read() / write())。

构建与验证

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

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 增加位置。

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 创建默认终端(宽度 80,高度 20,可在需要时扩展)。

func NewStdTermWithWriter

func NewStdTermWithWriter(w io.Writer) *StdTerm

NewStdTermWithWriter creates a StdTerm that writes to the provided writer.

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 如果底层 writer 实现了 Flusher 接口则调用 Flush。

func (*StdTerm) Height

func (t *StdTerm) Height() uint16

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

func (*StdTerm) WriteLine

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

func (*StdTerm) WriteStr

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

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 环境。底层落到 go-runewidth 的 EastAsianWidth 条件上(Rust 侧是 `UnicodeWidthChar::width_cjk` / `UnicodeWidthStr::width_cjk`)。

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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