convert method

List<int> convert (String string, [ int start = 0, int end ])

Converts string to its UTF-8 code units (a list of unsigned 8-bit integers).

If start and end are provided, only the substring string.substring(start, end) is converted.

Implementation

List<int> convert(String string, [int start = 0, int end]) {
  int stringLength = string.length;
  RangeError.checkValidRange(start, end, stringLength);
  if (end == null) end = stringLength;
  int length = end - start;
  if (length == 0) return new Uint8List(0);
  // Create a new encoder with a length that is guaranteed to be big enough.
  // A single code unit uses at most 3 bytes, a surrogate pair at most 4.
  _Utf8Encoder encoder = new _Utf8Encoder.withBufferSize(length * 3);
  int endPosition = encoder._fillBuffer(string, start, end);
  assert(endPosition >= end - 1);
  if (endPosition != end) {
    // Encoding skipped the last code unit.
    // That can only happen if the last code unit is a leadsurrogate.
    // Force encoding of the lead surrogate by itself.
    int lastCodeUnit = string.codeUnitAt(end - 1);
    assert(_isLeadSurrogate(lastCodeUnit));
    // We use a non-surrogate as `nextUnit` so that _writeSurrogate just
    // writes the lead-surrogate.
    bool wasCombined = encoder._writeSurrogate(lastCodeUnit, 0);
    assert(!wasCombined);
  }
  return encoder._buffer.sublist(0, encoder._bufferIndex);
}