Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

## Unreleased

- Fix unit truncation in error strings.

## 2.3.0

- Add `Unit` enum.
Expand Down
26 changes: 25 additions & 1 deletion src/parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -245,11 +245,24 @@ impl str::FromStr for Unit {
}
}

/// Safely truncates
fn to_string_truncate(unit: &str) -> String {
const MAX_UNIT_LEN: usize = 3;

if unit.len() > MAX_UNIT_LEN {
format!("{unit}...")
// TODO(MSRV 1.91): use ceil_char_boundary

if unit.is_char_boundary(3) {
format!("{}...", &unit[..3])
} else if unit.is_char_boundary(4) {
format!("{}...", &unit[..4])
} else if unit.is_char_boundary(5) {
format!("{}...", &unit[..5])
} else if unit.is_char_boundary(6) {
format!("{}...", &unit[..6])
} else {
unreachable!("char boundary will be within 4 bytes")
}
} else {
unit.to_owned()
}
Expand All @@ -274,6 +287,17 @@ mod tests {

use super::*;

#[test]
fn truncating_error_strings() {
assert_eq!("", to_string_truncate(""));
assert_eq!("b", to_string_truncate("b"));
assert_eq!("ob", to_string_truncate("ob"));
assert_eq!("foo", to_string_truncate("foo"));

assert_eq!("foo...", to_string_truncate("foob"));
assert_eq!("foo...", to_string_truncate("foobar"));
}

#[test]
fn when_ok() {
// shortcut for writing test cases
Expand Down