chunk static method

List<String> chunk(
  1. String s,
  2. int maxBytes
)

Split s into pieces of at most maxBytes UTF-8 bytes without cutting a surrogate pair. A non-positive maxBytes returns s whole.

Implementation

static List<String> chunk(String s, int maxBytes) {
  if (maxBytes <= 0 || s.isEmpty) return <String>[s];
  final out = <String>[];
  var start = 0;
  var bytes = 0;
  var i = 0;
  while (i < s.length) {
    final cu = s.codeUnitAt(i);
    int width;
    var step = 1;
    if (cu < 0x80) {
      width = 1;
    } else if (cu < 0x800) {
      width = 2;
    } else if (cu >= 0xD800 && cu <= 0xDBFF && i + 1 < s.length) {
      width = 4;
      step = 2;
    } else {
      width = 3;
    }
    if (bytes + width > maxBytes && i > start) {
      out.add(s.substring(start, i));
      start = i;
      bytes = 0;
    }
    bytes += width;
    i += step;
  }
  out.add(s.substring(start));
  return out;
}