Skip to content
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

Line width computation in the linter and formatter #12133

Closed
dhruvmanila opened this issue Jul 1, 2024 · 1 comment
Closed

Line width computation in the linter and formatter #12133

dhruvmanila opened this issue Jul 1, 2024 · 1 comment

Comments

@dhruvmanila
Copy link
Member

Related to #12130, it turns out that computing the line width on a char-by-char basis and as a whole str is different. From the docs of unicode-width, it's these cases where it differs specifically.

In the linter, the LineWidthBuilder determines the width by looking at each char individually. But, in some places the width is computed directly on &str which creates the panic as in #12130. These cases are:

if width.get() - last_chunk.width() <= limit.value() as usize {

.then_some(name.map(str::width).unwrap_or_default() + level as usize);

let maybe_length = settings.length_sort.then_some(name.width());

/// Returns `true` if the source code should be truncated when included in a user-facing
/// diagnostic.
fn should_truncate(source_code: &str) -> bool {
source_code.width() > 50 || source_code.contains(['\r', '\n'])
}

In the formatter,

// SAFETY: A u32 is sufficient to represent the width of a file <= 4GB
char.width().unwrap_or(0) as u32

// SAFETY: A u32 is sufficient to format files <= 4GB
#[allow(clippy::cast_possible_truncation)]
c => c.width().unwrap_or(0) as u32,

dhruvmanila added a commit that referenced this issue Jul 1, 2024
## Summary

This PR updates various references in the linter to compute the
line-width for summing the width of each `char` in a `str` instead of
computing the width of the `str` itself.

Refer to #12133 for more details.

fixes: #12130 

## Test Plan

Add a file with null (`\0`) character which is zero-width. Run this test
case on `main` to make sure it panics and switch over to this branch to
make sure it doesn't panic now.
@dhruvmanila
Copy link
Member Author

I'll close this as resolved by #12135 but this is a good reference to have for the time being.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant