marshalMapField function

List<int> marshalMapField(
  1. List<int> buffer,
  2. int fieldNumber,
  3. Map<Object?, Object?> mapValue,
  4. String keyType,
  5. String valueType, {
  6. List<Map<String, Object?>>? valueDescriptor,
})

Marshals a map field as repeated key-value pair messages.

In protobuf, map<K, V> is encoded on the wire as:

repeated MapEntry { K key = 1; V value = 2; }

Each entry is a length-delimited submessage containing field 1 (key) and field 2 (value).

mapValue is the Dart map to encode. Keys may be native-typed (as binary unmarshal produces — int/bool/String) or string-typed (as the JSON codec produces); keyType determines how each key is interpreted on the wire (e.g. TYPE_STRING, TYPE_INT32, etc.) and _coerceMapKey accepts either representation.

Returns buffer with the map entry fields appended.

Implementation

List<int> marshalMapField(
  List<int> buffer,
  int fieldNumber,
  Map<Object?, Object?> mapValue,
  String keyType,
  String valueType, {
  List<Map<String, Object?>>? valueDescriptor,
}) {
  if (mapValue.isEmpty) return buffer;

  for (final entry in mapValue.entries) {
    final entryBuffer = <int>[];

    // Encode key as field 1.
    final key = _coerceMapKey(entry.key, keyType);
    marshalField(entryBuffer, 1, keyType, key, repeated: true);

    // Encode value as field 2 (a message value re-marshals via its descriptor).
    if (entry.value != null) {
      marshalField(
        entryBuffer,
        2,
        valueType,
        entry.value,
        repeated: true,
        messageDescriptor: valueDescriptor,
      );
    }

    // Write the entry as a length-delimited submessage at [fieldNumber].
    encodeMessageField(buffer, fieldNumber, entryBuffer);
  }

  return buffer;
}