truncateBytes is like truncateChars but counts the number of bytes, not UTF-8 characters
(s string, max int, keepExtension bool)
| 283 | |
| 284 | // truncateBytes is like truncateChars but counts the number of bytes, not UTF-8 characters |
| 285 | func truncateBytes(s string, max int, keepExtension bool) (string, error) { |
| 286 | if max <= 0 { |
| 287 | return s, nil |
| 288 | } |
| 289 | if len(s) <= max { |
| 290 | return s, nil |
| 291 | } |
| 292 | exts := "" |
| 293 | if keepExtension { |
| 294 | s, exts = splitExtension(s) |
| 295 | } |
| 296 | |
| 297 | // ensure we don't split a multi-byte UTF-8 character |
| 298 | for i := max - len(exts); i > 0; i-- { |
| 299 | b := append([]byte(s)[:i], exts...) |
| 300 | if len(b) <= max && utf8.Valid(b) { |
| 301 | return string(b), nil |
| 302 | } |
| 303 | } |
| 304 | return "", errors.New("could not truncate to valid UTF-8") |
| 305 | } |
| 306 | |
| 307 | // forbid transformations that add/remove path separators |
| 308 | func validateSegment(s string) error { |
no test coverage detected
searching dependent graphs…