fitToLimit static method

String fitToLimit(
  1. String text,
  2. int limit, {
  3. bool truncated = false,
})

Cuts text so its JSON-escaped length is at most limit and appends truncatedSuffix when anything was left out.

Implementation

static String fitToLimit(String text, int limit, {bool truncated = false}) {
  var cost = 0;
  var end = 0;
  while (end < text.length) {
    final next = cost + _escapedCost(text.codeUnitAt(end));
    if (next > limit) break;
    cost = next;
    end++;
  }
  if (end == text.length) {
    return truncated ? '$text$truncatedSuffix' : text;
  }
  // Never split a surrogate pair.
  if (end > 0 && _isHighSurrogate(text.codeUnitAt(end - 1))) end--;
  return '${text.substring(0, end)}$truncatedSuffix';
}