encode method

  1. @override
void encode(
  1. List<T> data,
  2. LengthTrackingByteSink buffer
)
override

Writes data into the buffer.

Implementation

@override
void encode(List<T> data, LengthTrackingByteSink buffer) {
  assert(data.length == length);

  if (encodingLength.isDynamic) {
    const lengthEncoder = UintType();

    final startPosition = buffer.length;
    var currentOffset = data.length * sizeUnitBytes;

    // first, write a bunch of zeroes were the length will be written later.
    buffer.add(Uint8List(data.length * sizeUnitBytes));

    for (var i = 0; i < length; i++) {
      // write the actual position into the slot reserved earlier
      lengthEncoder.encodeReplace(
        startPosition + i * sizeUnitBytes,
        BigInt.from(currentOffset),
        buffer,
      );

      final lengthBefore = buffer.length;
      type.encode(data[i], buffer);
      currentOffset += buffer.length - lengthBefore;
    }
  } else {
    for (final elem in data) {
      type.encode(elem, buffer);
    }
  }
}