bevyengine / bevyengine/bevy

Using `TextWriter` with an invalid span index produces an inscrutable panic

Open
#16,700 3 comments 1 reaction 0 assignees View on GitHub
A-Text C-Usability D-Straightforward S-Ready-For-Implementation
Dominant language
Rust
Stars
48.2k
Forks
4.8k
Avg merge
3d 16h
Merged PRs (30d)
171

Description

## Bevy version

0.15, main

## What you did

It's really easy to goof and use `TextWriter` with an invalid span index. Here are three scenarios, two that have affected me personally, and another witnessed in Discord.

```rust
fn setup(mut commands: Commands) {
// User is just bad at counting, or goofed while refactoring
// after removing a span, or made a typo.
commands.spawn((Text::default(), A));

// User accidentally uses `Text` in place of `TextSpan`
commands
.spawn((Text::default(), B))
.with_child(Text::new("One"));

// User attempts to use `TextWriter` API with marker
// component placed on child text span
commands
.spawn(Text::default())
.with_child((TextSpan::new("One"), C));
}

fn update_text(
a_query: Query>,
b_query: Query>,
c_query: Query>,
mut writer: TextUiWriter,
) {
let entity = a_query.single();
*writer.text(entity, 1) = "Panic".to_string(); // Panics

let entity = b_query.single();
*writer.text(entity, 1) = "Panic".to_string(); // Panics

let entity = c_query.single();
*writer.text(entity, 1) = "Panic".to_string(); // Panics
}

```

## What went wrong

In each of these cases, the user is presented with a panic on an internal Bevy unwrap.

```rust
thread 'Compute Task Pool (0)' panicked at /Users/me/src/bevy/crates/bevy_text/src/text_access.rs:344:43:
called `Option::unwrap()` on a `None` value
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
```

## How can this be improved?

Some ideas:

- Add a nicer message by changing the `unwrap` to an `expect`.
- Refactor the fallible methods involved to return `Result` with a nice error.
- Pushing users to `get_text` in docs and using that in examples, even if we immediately unwrap it. At least then it would be slightly more clear that this is user error.
- Remove the panicking variants.

Contributor guide

Open the contributing guide

Research direction

Start at crates/bevy_text/src/text_access.rs around line 344 and trace the TextWriter access path for invalid span indices and misplaced components. Review the proposed alternatives in the issue, then establish which behavior is preferred; done should replace the internal unwrap panic with a clear, user-facing failure or documented non-panicking behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
frontend
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.