Skip to content

fix(schema): truncate by rune in truncateString to avoid splitting UTF-8 - #1117

Open
feizhuzheng wants to merge 1 commit into
cloudwego:mainfrom
feizhuzheng:fix/truncate-string-runes
Open

fix(schema): truncate by rune in truncateString to avoid splitting UTF-8#1117
feizhuzheng wants to merge 1 commit into
cloudwego:mainfrom
feizhuzheng:fix/truncate-string-runes

Conversation

@feizhuzheng

Copy link
Copy Markdown

What type of PR is this?

fix

Check the PR title.

  • This PR title match the format: <type>(optional scope): <description>
  • The description of this PR title is user-oriented and clear enough for others to understand.

(Optional) More detailed description for this PR(en: English/zh: Chinese).

en:
truncateString says it "truncates a string to maxLen characters", but it uses len(s) and s[:maxLen], which count and slice by byte. For multi-byte UTF-8 input (CJK, emoji, ...) this can cut a rune in half and emit invalid UTF-8.

This counts and slices by rune instead, so maxLen really means characters and the output is always valid UTF-8. It now matches how truncateTextByChars and truncateSkillContent already handle truncation in this repo. A non-positive maxLen is also handled without panicking. Added TestTruncateString.

(Optional) Which issue(s) this PR fixes:

truncateString is documented to truncate to maxLen characters, but it used
len(s) and s[:maxLen], which count and slice by byte. For multi-byte UTF-8
input (e.g. CJK or emoji) this could cut a character in half and produce
invalid UTF-8. Count and slice by rune instead, consistent with
truncateTextByChars and truncateSkillContent in the same module. Added a test.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

1 participant