truncateUtf8 function

String truncateUtf8(
  1. String text,
  2. int maxBytes
)

按 UTF-8 字节截断,不截断多字节字符。

Implementation

String truncateUtf8(String text, int maxBytes) {
  if (utf8Length(text) <= maxBytes) return text;
  var bytes = 0;
  final out = StringBuffer();
  for (final rune in text.runes) {
    final ch = String.fromCharCode(rune);
    final size = utf8Length(ch);
    if (bytes + size > maxBytes) break;
    bytes += size;
    out.write(ch);
  }
  return out.toString();
}