Skip to content

Implement measure_text_width with no allocation #246

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 14, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ test:
@cargo test
@cargo test --all-features
@cargo test --no-default-features
@cargo test --no-default-features --features ansi-parsing
@cargo test --no-default-features --features unicode-width

check-minver:
@echo "MINVER CHECK"
Expand Down
39 changes: 30 additions & 9 deletions src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,7 @@ use once_cell::sync::Lazy;
use crate::term::{wants_emoji, Term};

#[cfg(feature = "ansi-parsing")]
use crate::ansi::{strip_ansi_codes, AnsiCodeIterator};

#[cfg(not(feature = "ansi-parsing"))]
fn strip_ansi_codes(s: &str) -> &str {
s
}
use crate::ansi::AnsiCodeIterator;

fn default_colors_enabled(out: &Term) -> bool {
(out.features().colors_supported()
Expand Down Expand Up @@ -71,7 +66,19 @@ pub fn set_colors_enabled_stderr(val: bool) {

/// Measure the width of a string in terminal characters.
pub fn measure_text_width(s: &str) -> usize {
str_width(&strip_ansi_codes(s))
#[cfg(feature = "ansi-parsing")]
{
AnsiCodeIterator::new(s)
.filter_map(|(s, is_ansi)| match is_ansi {
false => Some(str_width(s)),
true => None,
})
.sum()
}
#[cfg(not(feature = "ansi-parsing"))]
{
str_width(s)
}
}

/// A terminal color.
Expand Down Expand Up @@ -937,16 +944,30 @@ fn test_text_width() {
.bold()
.force_styling(true)
.to_string();

assert_eq!(
measure_text_width(&s),
if cfg!(feature = "ansi-parsing") {
3
} else if cfg!(feature = "unicode-width") {
17
} else {
21
}
);

let s = style("🐶 <3").red().force_styling(true).to_string();

assert_eq!(
measure_text_width(&s),
match (
cfg!(feature = "ansi-parsing"),
cfg!(feature = "unicode-width")
) {
(true, true) => 5, // "🐶 <3"
(true, false) => 4, // "🐶 <3", no unicode-aware width
(false, true) => 14, // full string
(false, false) => 13, // full string, no unicode-aware width
}
);
}

#[test]
Expand Down
Loading