Skip to content

Commit 0264231

Browse files
committed
fix: error string when unit is too long
1 parent f626cc8 commit 0264231

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
## Unreleased
44

5+
- Fix unit truncation in error strings.
6+
57
## 2.3.0
68

79
- Add `Unit` enum.

src/parse.rs

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -245,11 +245,24 @@ impl str::FromStr for Unit {
245245
}
246246
}
247247

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

251252
if unit.len() > MAX_UNIT_LEN {
252-
format!("{unit}...")
253+
// TODO(MSRV 1.91): use ceil_char_boundary
254+
255+
if unit.is_char_boundary(3) {
256+
format!("{}...", &unit[..3])
257+
} else if unit.is_char_boundary(4) {
258+
format!("{}...", &unit[..4])
259+
} else if unit.is_char_boundary(5) {
260+
format!("{}...", &unit[..5])
261+
} else if unit.is_char_boundary(6) {
262+
format!("{}...", &unit[..6])
263+
} else {
264+
unreachable!("char boundary will be within 4 bytes")
265+
}
253266
} else {
254267
unit.to_owned()
255268
}
@@ -274,6 +287,17 @@ mod tests {
274287

275288
use super::*;
276289

290+
#[test]
291+
fn truncating_error_strings() {
292+
assert_eq!("", to_string_truncate(""));
293+
assert_eq!("b", to_string_truncate("b"));
294+
assert_eq!("ob", to_string_truncate("ob"));
295+
assert_eq!("foo", to_string_truncate("foo"));
296+
297+
assert_eq!("foo...", to_string_truncate("foob"));
298+
assert_eq!("foo...", to_string_truncate("foobar"));
299+
}
300+
277301
#[test]
278302
fn when_ok() {
279303
// shortcut for writing test cases

0 commit comments

Comments
 (0)