cellwidth
Terminal geometry for Rust

Your columns are
lying to you.

"👨‍👩‍👧‍👦".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.

0 dependencies no_std MSRV 1.75 Unicode 17.0.0 100% line & function coverage 89 tests
01 / The instrument

Measure anything, right now

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.

cellwidth.wasm loading…

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 without breaking anything

truncate(s, n) & cell(s, n)

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.

Wrap at real break opportunities

wrap(s, n) — UAX #14

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.

02 / The problem

Three different numbers, and only one is the right one

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 cellsWhy
café554the accent is a combining mark, drawn on top
日本語936East Asian wide — two cells each
👨‍👩‍👧‍👦2572four people joined by ZWJ into one glyph
🇯🇵822two regional indicators form one flag
\e[31mred\e[0m14143colour 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.

What that looks like

// .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         │
└────────────────────┴──────────────────┘
03 / Why this exists

Four crates, and the bug lives in the glue

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.

Before

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.

After

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.

It also runs where the others can't. 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.
04 / The proof

Every number here was checked by something that isn't us

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 againstScaleResult
Unicode GraphemeBreakTest.txt (UAX #29)766 casesall pass
Unicode LineBreakTest.txt (UAX #14)19,338 casesall pass
Unicode emoji-test.txt (UTS #51)3,944 sequencesall pass
glibc wcwidth + unicode-width1,112,064 code pointsevery divergence categorised & pinned
unicode-segmentation, both cluster modes9,282,875 strings × 2exact agreement
Real terminals via CSI 6n probing4 terminals × 32 casesrecorded in-repo
libFuzzer6 targets0 crashes
Miriinterpreterclean
Eight real defects were found this way — none of them by re-reading the code. Each has a regression test naming the oracle that caught it. That is the entire argument for testing against something external: the bugs you can find by staring are not the bugs that are there.

Coverage, stated exactly

MetricValueGated in CI
Line coverage100% (1,239 / 1,239)yes — build fails below 100%
Function coverage100% (110 / 110)yes — build fails below 100%
Region coverage99.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.

Terminals genuinely disagree — so we measured instead of guessing

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👨‍👩‍👧‍👦❤ + VS16skin toneBengali কা
kitty 0.482221
WezTerm 202402032121
VTE 0.76 (GNOME Terminal)8142
Alacritty 0.178141

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.

05 / The blueprint

Ten phases, all shipped

There was a plan before there was code. This is it, with honest status.

01
Correct width tables
UCD 17.0.0 generated into a two-level deduplicated lookup — 4,352 pages collapsed to 149 distinct, 85 KB
shipped
02
Grapheme clustering
Full UAX #29 including ZWJ sequences, flags, skin tones, Hangul and Indic conjuncts
shipped
03
ANSI awareness
CSI, OSC, DCS, nF and 8-bit C1 forms parsed as sequences, not pattern-matched
shipped
04
Fitting primitives
truncate, cell, pad, center — style-preserving and allocation-free where possible
shipped
05
Differential testing
glibc, unicode-width and unicode-segmentation as external oracles; 8 real defects found
shipped
06
Continuous integration
13 jobs: three toolchains, MSRV, bare metal, Miri, fuzzing, semver, coverage gates
shipped
07
Real-terminal harness
Cursor-position probing under Xvfb across four terminal emulators
shipped
08
Line breaking & tables
UAX #14 at full conformance, plus a table builder that survives fuzzing
shipped
09
Publish
Released to crates.io, with a live WebAssembly demo on this page
shipped
10
Compat shims & benchmarks
Drop-in compat traits for unicode-width and unicode-segmentation, oracle-tested in both cluster modes, plus head-to-head timings — then 1.0.0
shipped
06 / Using it

The whole API, roughly

use 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);

Tables that line up

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.

Where this shows up

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.

Coming from unicode-width or unicode-segmentation

Same 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);

Head to head

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.

inputcellwidth::widthWidth::LEGACYunicode-widthanswers
ascii, 69 B49 ns46 ns54 ns69 / 69 / 69
cjk, 114 B413 ns118 ns85 ns76 / 76 / 76
emoji, 126 B644 ns131 ns132 ns77 / 84 / 77
ansi, 80 B129 ns129 ns62 ns42 / 42 / 80
table row, 64 B263 ns84 ns59 ns38 / 40 / 47

Grapheme iteration runs about twice as fast as unicode-segmentation on every input (233 ns vs 519 ns for the CJK string).