encode static method

Uint8List encode(
  1. Uint8List messageBytes, {
  2. bool compressed = false,
})

Prefixes messageBytes with the 5-byte gRPC frame header.

One allocation, no intermediate copy. It reserves room in front for a channel frame header, so a channel transport does not copy it again.

Implementation

static Uint8List encode(Uint8List messageBytes, {bool compressed = false}) {
  final length = messageBytes.length;
  final result = allocateWithHeadroom(
    RpcConstants.messagePrefixSize + length,
  );

  result[RpcConstants.compressionFlagIndex] = compressed
      ? RpcConstants.compressed
      : RpcConstants.noCompression;

  result[RpcConstants.messageLengthIndex] = (length >> 24) & 0xFF;
  result[RpcConstants.messageLengthIndex + 1] = (length >> 16) & 0xFF;
  result[RpcConstants.messageLengthIndex + 2] = (length >> 8) & 0xFF;
  result[RpcConstants.messageLengthIndex + 3] = length & 0xFF;

  result.setRange(
    RpcConstants.messagePrefixSize,
    result.length,
    messageBytes,
  );

  return result;
}