From 9c44acf3b6c4e8a7d9d30e1631703ba236afede5 Mon Sep 17 00:00:00 2001 From: Jeremy Andrews Date: Mon, 30 Oct 2023 17:33:40 +0100 Subject: [PATCH 1/2] don't panic when truncating non-utf8 --- src/util.rs | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/src/util.rs b/src/util.rs index 746321b0..403024eb 100644 --- a/src/util.rs +++ b/src/util.rs @@ -247,14 +247,15 @@ pub fn median( /// // All characters are returned as the string is less than 15 characters long. /// assert_eq!(util::truncate_string("shorter string", 15), "shorter string"); /// ``` -pub fn truncate_string(str_to_truncate: &str, max_length: u64) -> String { - let mut string_to_truncate = str_to_truncate.to_string(); - if string_to_truncate.len() as u64 > max_length { - let truncated_length = max_length - 2; - string_to_truncate.truncate(truncated_length as usize); - string_to_truncate += ".."; +pub fn truncate_string(str_to_truncate: &str, max_length: usize) -> String { + if str_to_truncate.char_indices().count() > max_length { + match str_to_truncate.char_indices().nth(max_length - 2) { + None => str_to_truncate.to_string(), + Some((idx, _)) => format!("{}..", &str_to_truncate[..idx]), + } + } else { + str_to_truncate.to_string() } - string_to_truncate } /// Determine if a timer expired, with second granularity. @@ -561,6 +562,8 @@ mod tests { assert_eq!(truncate_string("abcde", 4), "ab.."); assert_eq!(truncate_string("abcde", 3), "a.."); assert_eq!(truncate_string("abcde", 2), ".."); + assert_eq!(truncate_string("これはテストだ", 10), "これはテストだ"); + assert_eq!(truncate_string("これはテストだ", 3), "こ.."); } #[tokio::test] From aee01751603b09a5ad5fddda66049b7088e9aebb Mon Sep 17 00:00:00 2001 From: Jeremy Andrews Date: Wed, 1 Nov 2023 10:22:02 +0100 Subject: [PATCH 2/2] document; add Chinese and Korean characters to tests --- CHANGELOG.md | 1 + src/util.rs | 7 +++++++ 2 files changed, 8 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index e4846560..3778f944 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## 0.17.3-dev - [#565](https://github.com/tag1consulting/goose/pull/565) add `--accept-invalid-certs` to skip validation of https certificates + - [#568](https://github.com/tag1consulting/goose/pull/568) don't panic when truncating non utf-8 string ## 0.17.2 August 28, 2023 - [#557](https://github.com/tag1consulting/goose/pull/557) speed up user initialization on Linux diff --git a/src/util.rs b/src/util.rs index 403024eb..ff33bd38 100644 --- a/src/util.rs +++ b/src/util.rs @@ -564,6 +564,13 @@ mod tests { assert_eq!(truncate_string("abcde", 2), ".."); assert_eq!(truncate_string("これはテストだ", 10), "これはテストだ"); assert_eq!(truncate_string("これはテストだ", 3), "こ.."); + assert_eq!(truncate_string("这是一个测试。", 10), "这是一个测试。"); + assert_eq!(truncate_string("这是一个测试。", 3), "这.."); + assert_eq!( + truncate_string("이것은 테스트입니다.", 15), + "이것은 테스트입니다." + ); + assert_eq!(truncate_string("이것은 테스트입니다.", 3), "이.."); } #[tokio::test]