@@ -245,11 +245,24 @@ impl str::FromStr for Unit {
245245 }
246246}
247247
248+ /// Safely truncates
248249fn 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