TruncateString truncates a string to a given number of runes.
(s string, maxRunes int)
| 33 | |
| 34 | // TruncateString truncates a string to a given number of runes. |
| 35 | func TruncateString(s string, maxRunes int) string { |
| 36 | // This is a fast path (len(s) is an upper bound for RuneCountInString). |
| 37 | if len(s) <= maxRunes { |
| 38 | return s |
| 39 | } |
| 40 | n := utf8.RuneCountInString(s) |
| 41 | if n <= maxRunes { |
| 42 | return s |
| 43 | } |
| 44 | // Fast path for ASCII strings. |
| 45 | if len(s) == n { |
| 46 | return s[:maxRunes] |
| 47 | } |
| 48 | i := 0 |
| 49 | for pos := range s { |
| 50 | if i == maxRunes { |
| 51 | return s[:pos] |
| 52 | } |
| 53 | i++ |
| 54 | } |
| 55 | // This code should be unreachable. |
| 56 | return s |
| 57 | } |
no outgoing calls
no test coverage detected
searching dependent graphs…