Files
tasks/common/util/strings.go
David ReissandGitHub 3f24c833ef Fix truncation of Failures (#6113)
## What changed?
Truncate could split strings in the middle of utf-8 codepoints.
Also, not all strings in the failure were truncated and depth of
failures (at least structure) was not limited.

## Why?
Avoid invalid utf-8 in strings.

## How did you test it?
unit tests

## Potential risks
This could drop more information from Failures than before.
2024-06-13 17:12:50 -07:00

44 lines
1.6 KiB
Go

// The MIT License
//
// Copyright (c) 2020 Temporal Technologies Inc. All rights reserved.
//
// Copyright (c) 2020 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package util
import "unicode/utf8"
// TruncateUTF8 truncates s to no more than n _bytes_, and returns a valid utf-8 string as long
// as the input is a valid utf-8 string.
// Note that truncation pays attention to codepoints only! This may truncate in the middle of a
// grapheme cluster.
func TruncateUTF8(s string, n int) string {
if len(s) <= n {
return s
} else if n <= 0 {
return ""
}
for n > 0 && !utf8.RuneStart(s[n]) {
n--
}
return s[:n]
}