add<T> method

void add<T>({
  1. required int subId,
  2. required Encoder<T> encoder,
  3. required Decoder<T> decoder,
  4. bool polymorphic = false,
})

Adds type T to this group with the given subId.

subId must be unique within the group. For best performance, use values between 0 and 127.

Example:

group.add<Circle>(
  subId: 1,
  encoder: (c, ctx) => ctx.pack(c.radius),
  decoder: (d, ctx) => Circle(ctx.unpack<double>(d)),
);

Implementation

void add<T>({
  required int subId,
  required Encoder<T> encoder,
  required Decoder<T> decoder,
  bool polymorphic = false,
}) {
  ExtensionRegistry._checkType<T>();

  if (_subs.containsKey(subId)) {
    throw MessagePackConfigurationException(
      'Sub-type id $subId is already registered in group $_extId.',
      'Use a different subId.',
    );
  }

  final ext = ExtensionRegistry._makeExt<T>(
    id: _extId,
    subId: subId,
    encoder: encoder,
    decoder: decoder,
  );

  _subs[subId] = ext;

  // Register the concrete type in the flat cache for O(1) encoding.
  _registry._putType(T, ext, polymorphic: polymorphic);
}