colored-rs / colored

(Rust) Coloring terminal so simple you already know how to do it !
Mozilla Public License 2.0
1.74k stars 84 forks source link

Incorrect value of `len()` when using colored within `format!` #172

Closed YiNNx closed 5 months ago

YiNNx commented 5 months ago

Description

The len() function applied to a string colored using colored::Colorize returns unexpected results when used within format!.

Code Example

use colored::Colorize;

fn main() {
    let exact_len = "test".green().len();
    let format_len = format!("{}", "test".green()).len();
    let format_len_without_colored = format!("{}", "test").len();

    println!("exact_len: {exact_len}");
    println!("format_len: {format_len}");
    println!("format_len_without_colored: {format_len_without_colored}");
}

Output

exact_len: 4
format_len: 13
format_len_without_colored: 4

Expected Behavior

format_len should be the same as the other lengths.

Environment

YiNNx commented 5 months ago

I figured out that the .to_string() conversion is causing the result length to change:The string "test" was converted to "\u{1b}[32mtest\u{1b}[0m", resulting in a change in length. This is likely expected behavior, so I'm going to close this issue.