#ansi-colors #terminal-colors #color #ansi-term #terminal #rgb #escaping

ansistream

将快速、无需分配内存的 ANSI 转义码写入缓冲区,并将它们全部刷新到任何输出

6 个版本

0.2.0 2024 年 1 月 21 日
0.1.6 2024 年 1 月 11 日

开发工具 中排名第 559

Download history 1/week @ 2024-03-09

每月下载量 73

MIT 许可证

210KB
527 行 代码

AnsiStream

Crates.io Crates.io Downloads Rust Stable License GitHub Actions Workflow Status

将快速、无需分配内存的 ANSI 转义码写入缓冲区,并将它们全部刷新到任何输出流。支持 8/16 种颜色,256 种颜色,RGB 颜色渲染输出。

终端图形 ANSI 转义码

ANSI 转义码标准,正式作为 ISO/IEC 6429 采纳,定义了一系列控制序列。每个控制序列以一个 控制序列引入符 (CSI) 开头,定义为转义字符后紧跟一个括号: ESC[. 特别地,一个 CSI 后跟一定数量的 "参数字节" (ASCII 0-9:; <>?),然后是字母 m,形成一个称为 选择图形表示 (SGR) 的控制序列。如果没有显式给出参数字节,则默认为 0。SGR 参数可以用分号 ; 作为 分隔符 连在一起。

以下是一些常见的 SGR 参数。

参数 效果
0 重置所有 SGR 效果到默认值
1 加粗或增强亮度
2 淡出或降低亮度
4 单行下划线
5 慢闪
30-37 前景色(3/4 位)
38;5;x 前景色(256 种颜色,非标准)
38;2;r;g;b 前景色(RGB,非标准)
40-47 背景色(8 种颜色)
48;5;x 背景色(256 种颜色,非标准)
48;2;r;g;b 背景色(RGB,非标准)
90-97 亮前景色(非标准)
100-107 亮背景色(非标准)
  • 以下示例将打印红色下划线文本。

sgi

用法

  • AnsiStream 包添加到您的 Cargo.toml
$ cargo add ansistream
  • 初始化一个缓冲区并在其中写入一个简单的字符串
// initialize a ansi stream
let output = Cursor::new(Vec::<u8>::new());
let mut astream = ansistream::AnsiScapeStream::new(output);
// write a simple string in buffer
astream.write_string("the quick brown fox jumps over the lazy dog")?;
// data will be flushed when astream drop or gets flushed
  • 将流写入 stdout
let stdout = io::stdout().lock();

let mut astream = ansistream::AnsiScapeStream::new(stdout);
astream.write_string("simple text")?;

astream.flush()?;
  • 将绿色前景文本写入流
let mut astream = AnsiEscapeStream::new(writer);
astream.write_text_fc_fmt(FCGREEN, format_args!("123")).unwrap();
// asserts that fcgreen was writed and also reseted with fcdefault
assert_eq!(
    &[0x1b, 0x5b, 0x33, 0x32, 0x6d, 0x31, 0x32, 0x33, 0x1b, 0x5b, 0x33, 0x39, 0x6d],
    astream.buffer()
);
  • 写入格式化颜色输出
let mut astream = AnsiEscapeStream::new(writer);

  for i in 100..=107 {
      astream.write_text_color_fmt(FC_LIGHT_GRAY, i, format_args!("{i:>5} "))?;
  }

示例

  • 16色示例

256color

$ hyperfine --warmup 100 '16color'
Benchmark 1: 16color
  Time (mean ± σ):      10.9 ms ±   0.4 ms    [User: 5.7 ms, System: 9.3 ms]
  Range (min … max):    10.3 ms …  12.2 ms    133 runs
  • 256色示例

256color

$ hyperfine --warmup 100 '256color'
Benchmark 1: 256color
  Time (mean ± σ):      11.3 ms ±   0.4 ms    [User: 4.9 ms, System: 9.3 ms]
  Range (min … max):    10.7 ms …  12.7 ms    130 runs
  • 真彩色示例

truecolor

$ hyperfine --warmup 100 'truecolor'
Benchmark 1: truecolor
  Time (mean ± σ):      11.2 ms ±   0.5 ms    [User: 5.4 ms, System: 9.2 ms]
  Range (min … max):    10.4 ms …  13.0 ms    131 runs

状态

可用的转义码

完成 类型
x 颜色和样式转义码
屏幕和光标转义码

参考

ANSI 转义码

无运行时依赖