"👨👩👧👦".len() is 25. .chars().count() is 7.
A terminal draws it in 2 columns. Every CLI table, progress bar and status
line needs that third number — and nothing in the standard library will tell you it.
This is not a simulation. The panel below is the actual crate, compiled to WebAssembly and running in your browser. Same code, same Unicode tables, same answers as your terminal build.
Each box is one grapheme cluster, drawn across the terminal cells it occupies. Violet = 2 cells, grey = 1 cell, red = zero-width (a combining mark or an escape sequence — it costs nothing).
truncate borrows the longest prefix that fits — never splitting a
character or leaving half an escape sequence. cell guarantees
exactly n columns, adding an ellipsis or padding. The amber frame is the
target width; hatching is padding. Every glyph sits in a real cell, so nothing
here depends on your browser’s font metrics.
Japanese has no spaces, so naive whitespace wrapping produces one giant line.
wrap implements the Unicode line-breaking algorithm and breaks
between characters where the script allows it.
A terminal is a grid of fixed-size cells. To draw anything that lines up — a table, a border, a progress bar, a status line — you must know how many cells a string occupies. Rust gives you two numbers, and neither is that one.
| String | .len() | .chars() | Terminal cells | Why |
|---|---|---|---|---|
café | 5 | 5 | 4 | the accent is a combining mark, drawn on top |
日本語 | 9 | 3 | 6 | East Asian wide — two cells each |
👨👩👧👦 | 25 | 7 | 2 | four people joined by ZWJ into one glyph |
🇯🇵 | 8 | 2 | 2 | two regional indicators form one flag |
\e[31mred\e[0m | 14 | 14 | 3 | colour codes are instructions, not ink |
Reach for len() and your output goes ragged the first time someone has an
umlaut in their name, a Japanese hostname, or an emoji in a commit message. It stays
broken, because the failure only shows up on other people's data — never yours.
// .len() — every non-ASCII row drifts
┌────────────────────┬──────────────────┐
│ nagoya-prod-01 │ healthy │
│ 日本語ログ出力 │ healthy │
│ 👨👩👧👦 shared account │ degraded │
└────────────────────┴──────────────────┘
// cellwidth — every line is the same number of cells
┌────────────────────┬──────────────────┐
│ nagoya-prod-01 │ healthy │
│ 日本語ログ出力 │ healthy │
│ 👨👩👧👦 shared account │ degraded │
└────────────────────┴──────────────────┘
You can already solve parts of this. The problem is that the parts don't fit together, and joining them is where people get it wrong.
unicode-width // widths
unicode-segmentation // clusters
strip-ansi-escapes // colour
textwrap // wrapping
+ glue you write yourself
Width and segmentation are different questions, and those two crates do not talk to each other. Nothing stops you from measuring a string one way and cutting it another — which is exactly the bug.
cargo add cellwidth
// cargo tree
your-app v0.1.0
└── cellwidth v1.0.0
One crate. Zero dependencies, zero dev-dependencies, no build script. Every operation works in whole grapheme clusters and whole escape sequences, so a cut can never produce half a character or half a colour code.
no_std with optional
alloc, verified on a bare-metal thumbv7em-none-eabi build —
so width, truncate, graphemes and
pieces work in a serial console or an embedded shell with no allocator at all.
A library that claims to be correct about Unicode is easy to write and hard to trust. So nothing below rests on our own say-so — each figure comes from an external oracle, a published conformance file, or a real terminal.
| Checked against | Scale | Result |
|---|---|---|
Unicode GraphemeBreakTest.txt (UAX #29) | 766 cases | all pass |
Unicode LineBreakTest.txt (UAX #14) | 19,338 cases | all pass |
Unicode emoji-test.txt (UTS #51) | 3,944 sequences | all pass |
glibc wcwidth + unicode-width | 1,112,064 code points | every divergence categorised & pinned |
unicode-segmentation, both cluster modes | 9,282,875 strings × 2 | exact agreement |
Real terminals via CSI 6n probing | 4 terminals × 32 cases | recorded in-repo |
| libFuzzer | 6 targets | 0 crashes |
| Miri | interpreter | clean |
| Metric | Value | Gated in CI |
|---|---|---|
| Line coverage | 100% (1,239 / 1,239) | yes — build fails below 100% |
| Function coverage | 100% (110 / 110) | yes — build fails below 100% |
| Region coverage | 99.95% (1 of 2,088) | reported, not gated |
That last row is the honest one. A single region is reported missing, but the report's own segment data contains no uncovered segment for that file, and a library-only run shows the lines covered. It is an artifact of how per-binary reports are merged, not a hole in the suite — so it is reported and explained rather than rounded away or quietly hidden.
There is no single right answer for how wide an emoji is. Rather than pick one and hope,
probe/ prints a string into a live terminal, asks where the cursor ended up
with CSI 6n, and writes the answer down.
| Terminal | 👨👩👧👦 | ❤ + VS16 | skin tone | Bengali কা |
|---|---|---|---|---|
| kitty 0.48 | 2 | 2 | 2 | 1 |
| WezTerm 20240203 | 2 | 1 | 2 | 1 |
| VTE 0.76 (GNOME Terminal) | 8 | 1 | 4 | 2 |
| Alacritty 0.17 | 8 | 1 | 4 | 1 |
Two camps, so there are two presets. Width::DEFAULT reproduces kitty exactly
on all 32 cases. Width::LEGACY counts every code point separately, as
wcwidth does, and scores higher across the four as a group (99/128 vs 94/128).
Flip between them in the demo above and watch the numbers move.
There was a plan before there was code. This is it, with honest status.
compat traits for unicode-width and unicode-segmentation, oracle-tested in both cluster modes, plus head-to-head timings — then 1.0.0use cellwidth::{width, cell, truncate, wrap, Table};
assert_eq!(width("café"), 4); // combining accents are free
assert_eq!(width("日本語"), 6); // CJK is double-width
assert_eq!(width("👨👩👧👦"), 2); // one glyph, not seven
assert_eq!(width("\x1b[31mred\x1b[0m"), 3); // colour costs nothing
// exactly 10 columns, always — truncated with an ellipsis or padded
assert_eq!(width(&cell("🇯🇵 Tōkyō 東京", 10)), 10);
let out = Table::new()
.column("host")
.column_with("label", Align::Left, Sizing::Max(22))
.column_aligned("rps", Align::Right)
.row(["tokyo-cdn", "🇯🇵 Tōkyō 東京 edge", "17,900"])
.row(["crew-alpha", "👨👩👧👦 shared account", "3"])
.border(Border::Ascii)
.render(Some(60));
+------------+--------------------+--------+
| host | label | rps |
+------------+--------------------+--------+
| tokyo-cdn | 🇯🇵 Tōkyō 東京 edge | 17,900 |
| crew-alpha | 👨👩👧👦 shared account | 3 |
+------------+--------------------+--------+
A flag, a ZWJ family, CJK and a macron in one column — and all six lines measure 44 cells exactly. That invariant is what the fuzzer asserts, whatever the cells hold.
Anything that draws a fixed grid into a terminal: CLI tables and reports, TUI list and
column views, progress bars and spinners, log formatters, box-drawn banners, help and
error text wrapped to $COLUMNS, and text inputs where the cursor should move
by characters rather than bytes.
unicode-width or unicode-segmentationSame trait names, same method signatures, cellwidth's answers. The figures are measured by the oracle tests, not quoted.
// use unicode_width::UnicodeWidthStr;
use cellwidth::compat::{UnicodeSegmentation, UnicodeWidthStr};
assert_eq!("\x1b[31mred\x1b[0m".width(), 3); // unicode-width 0.2.2: 12
assert_eq!("क्षि".width(), 1); // unicode-width 0.2.2: 3
assert_eq!("a👍🏽🇯🇵".graphemes(true).count(), 3);
Best of seven rounds of 100,000 calls. Read the answers before the timings: unicode-width neither segments clusters nor parses escapes, so on those inputs it does less work and returns a number the terminal will not honour. Width::LEGACY is the like-for-like model.
| input | cellwidth::width | Width::LEGACY | unicode-width | answers |
|---|---|---|---|---|
| ascii, 69 B | 49 ns | 46 ns | 54 ns | 69 / 69 / 69 |
| cjk, 114 B | 413 ns | 118 ns | 85 ns | 76 / 76 / 76 |
| emoji, 126 B | 644 ns | 131 ns | 132 ns | 77 / 84 / 77 |
| ansi, 80 B | 129 ns | 129 ns | 62 ns | 42 / 42 / 80 |
| table row, 64 B | 263 ns | 84 ns | 59 ns | 38 / 40 / 47 |
Grapheme iteration runs about twice as fast as unicode-segmentation on every input (233 ns vs 519 ns for the CJK string).