Repository navigation
Description
Summary
mermaid-text is not multi-byte safe: byte offsets are used where character offsets are
expected. This produces two distinct failures on non-ASCII (e.g. Cyrillic, but any
multi-byte UTF-8) diagram text:
- Panic in the sequence/state parsers — a byte-index slice at a non-char boundary.
- Silent label corruption in the flowchart parser — a byte offset is returned where the
API documents a char count, so the tokenizer over-advances and mangles the next node.
Both are reproducible on mermaid-text = "0.56.0" (latest) with a few lines of input. Root
causes and suggested fixes below.
Environment: mermaid-text 0.56.0, rustc 1.96.0, Windows (platform-independent — pure
string handling).
Bug 1 — Panic: byte-index slice at non-char boundary
// panics
mermaid_text::render("sequenceDiagram\n participant Сервер\n Сервер->>Сервер: ok\n");thread 'main' panicked at src/parser/common.rs:45:16:
end byte index 8 is not a char boundary; it is inside 'о' (bytes 7..9 of string)
Other inputs that panic (all valid Mermaid):
| input line | result |
|---|---|
participant Оркестратор |
panic |
loop до готовности |
panic |
alt если готов / else иначе |
panic |
loop until ready (ASCII) |
ok |
Root cause
parser/common.rs::strip_keyword_prefix slices at the byte index keyword.len() before
checking whether the prefix matches, and without a char-boundary check:
pub(crate) fn strip_keyword_prefix<'a>(line: &'a str, keyword: &str) -> Option<&'a str> {
let len = keyword.len();
if line.len() > len
&& line[..len].eq_ignore_ascii_case(keyword) // <-- panics if `len` is not a char boundary
&& line.as_bytes()[len].is_ascii_whitespace()
{
Some(line[len..].trim())
} else {
None
}
}Any line whose byte at index keyword.len() falls inside a multi-byte character panics. The
sequence parser tries keywords of several lengths (loop=4, actor=5, activate=8,
deactivate=10, participant=11), so a non-ASCII line is very likely to hit one of them.
In loop до готовности, byte 8 lands inside о while probing the keyword activate.
Suggested fix
Guard the slice with is_char_boundary, or avoid slicing entirely:
pub(crate) fn strip_keyword_prefix<'a>(line: &'a str, keyword: &str) -> Option<&'a str> {
let rest = line.get(..keyword.len()) // None if not a char boundary
.filter(|head| head.eq_ignore_ascii_case(keyword))
.and(line.get(keyword.len()..))?;
rest.strip_prefix(|c: char| c.is_ascii_whitespace())
.map(str::trim)
}(str::get returns None rather than panicking on a non-boundary index, which also preserves
the existing ASCII-fast behaviour.)
Bug 2 — Silent corruption: byte offset returned as a char count
This one produces no error and no panic — just a wrong diagram. The only difference
between these two inputs is the edge label; node labels are ASCII in both:
mermaid_text::render("flowchart LR\n A[Start] -->|yes| B[End]\n"); // ASCII label
mermaid_text::render("flowchart LR\n A[Start] -->|да| B[End]\n"); // non-ASCII labelASCII edge label -> │ Start │──────▸│ End │ <- correct
non-ASCII edge label -> │ Start │──────▸│ [End] │ <- bracket leaked into the label
With more nodes, the damage is worse — nodes disappear entirely. Real example:
flowchart TD
A[Пользователь] --> B{Есть токен?}
B -->|Да| C[Доступ разрешён]
B -->|Нет| D[Форма входа]
renders C as [Доступ разрешён] (brackets inside the label) and drops D's label
altogether, drawing an empty node D plus a stray Форма входа].
Root cause
parser/flowchart.rs::try_consume_pipe_label documents a char count but returns a byte
offset:
/// Try to consume a `|label|` suffix. Returns `(consumed_string, char_count)`.
fn try_consume_pipe_label(s: &str) -> (String, usize) {
if let Some(inner) = s.strip_prefix('|')
&& let Some(end) = inner.find('|') // <-- BYTE offset
{
let portion = &s[..end + 2];
return (portion.to_string(), end + 2); // <-- returned as if it were a char count
}
(String::new(), 0)
}The tokenizer walks a Vec<char> and advances the char cursor by that value:
let chars: Vec<char> = /* ... */;
while i < len {
// ...
if let Some((arrow_tok, consumed)) = try_consume_arrow(&remaining) {
// ...
i += consumed; // char index advanced by a byte count
continue;
}For |да| the label is 2 chars but 4 bytes, so the cursor over-advances by 2 and eats the
B of the following B[End], leaving [End] as the node token — hence the brackets in
the label. The over-advance equals byte_len - char_len of the edge label, so any multi-byte
edge label corrupts the following node.
Suggested fix
Return an actual char count:
if let Some(inner) = s.strip_prefix('|')
&& let Some(end) = inner.find('|')
{
let portion = &s[..end + 2];
return (portion.to_string(), portion.chars().count()); // char count, matching the doc
}The same byte-offset-as-char-count pattern appears in try_consume_inline_compact_arrow
(2 + end + 3, where end comes from rest.find(".->") / rest.find("==>")), so a
non-ASCII inline label such as A -. да .-> B is likely affected in the same way.
Why this matters (context)
I evaluated mermaid-text for rendering Mermaid blocks in the message feed of a Rust/ratatui
TUI LLM chat client (Russian-language). The crate's shape is a great fit — tiny dependency
tree, Result-based API, render_ascii_with_width for legacy terminals, detect::detect for
whitelisting — and ASCII sequence diagrams look genuinely excellent.
But an LLM emitting a Russian sequence diagram would crash the app (Bug 1 panics in the
render path), and a Russian flowchart would render a plausible-but-wrong diagram (Bug 2). Of
17 real Mermaid diagrams in our own docs, 0 are pure-ASCII, so neither an ASCII-only gate
nor catch_unwind is a workable mitigation. I've shelved the feature until multi-byte input
is safe — happy to revisit and report back once it is.
Broader note
Byte-oriented string handling (as_bytes()[i], s[..n], find() offsets used as char
counts) appears across src/parser/ — common.rs, flowchart.rs, state.rs, class.rs,
er.rs, gantt.rs, git_graph.rs, journey.rs, pie.rs, sankey.rs, architecture.rs.
The two bugs above are the ones my corpus hit, but an audit of that pattern (plus a couple of
non-ASCII fixture tests per diagram type) would likely surface more.
I'm happy to submit a PR for either fix if that's useful.
Separate, unrelated to UTF-8: render_with_width(src, Some(w)) seems not to constrain output
width for several diagram types (e.g. a classDiagram rendered 203 columns wide at
Some(90); a sequence diagram rendered 69 at Some(60)). Let me know if that's expected — a
soft hint rather than a budget — and I'll file it separately if not.
Activity
style: satisfy clippy on stable 1.97 (question_mark, useless_borrows_…
docs(changelog): credit @vshylov as original author of the #29 fix (PR …
leboiko commentedon Jul 16, 2026
Fixed and released — and credit where it's due: the fix is your PR #30. I apologise that I didn't build on it directly (details and apology on #30) — I merged a parallel PR without checking for your open one. The shipped implementation is substantially yours.
Fixed
Your two reported bugs and the compact-arrow variant came straight from #30. Taking your "broader note" seriously, a full parser audit added three more sites of the same class:
common::strip_keyword_prefixloop до готовностиstr::getflowchart::try_consume_pipe_labelflowchart::try_consume_inline_compact_arrow-.да.->flowchart::try_consume_inline_quoted_arrow-. "да" .->sequence::parse_participant_declparticipant İd as …(asoffset taken from ato_lowercase()copy)gantt/timeline/journeykeyword-stripstrip_keyword_prefixmy central fix hadn't reachedgit_graphwas on the audit list too but verified clean. All six pinned by 10 regression tests (each confirmed to panic/corrupt before its fix); full write-up indocs/audit-mermaid-text-utf8-2026-07-15.md.Released
mermaid-text0.56.1 — on crates.io.markdown-reader1.34.74 — the viewer, bundling it.Your corpus should render cleanly now.
On the width question
Expected-but-not-ideal:
max_widthis currently a soft hint, not a hard budget. Sequence/pie/ER have fixed layouts and ignore it entirely; the others (class, gantt, timeline, …) receive it for truncation but can still overflow their minimum column widths. So the 203-cols-at-Some(90)classDiagram and the over-wide sequence diagram are working-as-currently-built, not a UTF-8 issue. Please do file it separately — enforcingmax_widthas a real budget is a reasonable feature request and I'd like to track it on its own.Thanks again for the report and the patch — and sorry for the process misstep.
vshylov commentedon Jul 16, 2026
Thank you very much!
fix(mermaid-text): UTF-8 safety — byte offsets used as char offsets (l…
fix(mermaid-text): route classDiagram keyword probe through the UTF-8…