Skip to content

truncate panics for max_len values below 3 #68

Description

@tusharhqq

I ran this command.

I reproduced this by adding a small regression test next to the existing test_truncate test in src/cmd/submissions.rs:

#[test]
fn test_truncate_handles_zero_max_len() {
    assert_eq!(truncate("0", 0).len(), 0);
}

Then I ran:

cargo test test_truncate_handles_zero_max_len

I expected this to happen.

truncate should handle very small max_len values without panicking. If max_len is 0, the returned string should fit in length 0. More generally, the returned string should not be longer than max_len.

This happened instead.

The test panicked inside truncate. The function currently appends ... when the input is too long, but it computes the prefix length as max_len - 3:

fn truncate(s: &str, max_len: usize) -> String {
    if s.len() <= max_len {
        s.to_string()
    } else {
        format!("{}...", &s[..max_len - 3])
    }
}

When max_len is 0, 1, or 2, max_len - 3 underflows because max_len is a usize.

Here is the exact error or log.

thread 'cmd::submissions::tests::test_truncate_handles_zero_max_len' panicked at src/cmd/submissions.rs:164:31:\nattempt to subtract with overflow\n```

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions