writeValue method

void writeValue (WriteBuffer buffer, dynamic value)

Writes value to buffer by first writing a type discriminator byte, then the value itself.

This method may be called recursively to serialize container values.

Type discriminators 0 through 127 inclusive are reserved for use by the base class.

The codec can be extended by overriding this method, calling super for values that the extension does not handle. Type discriminators used by extensions must be greater than or equal to 128 in order to avoid clashes with any later extensions to the base class.

Implementation

void writeValue(WriteBuffer buffer, dynamic value) {
  if (value == null) {
    buffer.putUint8(_valueNull);
  } else if (value is bool) {
    buffer.putUint8(value ? _valueTrue : _valueFalse);
  } else if (value is int) {
    if (-0x7fffffff - 1 <= value && value <= 0x7fffffff) {
      buffer.putUint8(_valueInt32);
      buffer.putInt32(value);
    } else {
      buffer.putUint8(_valueInt64);
      buffer.putInt64(value);
    }
  } else if (value is double) {
    buffer.putUint8(_valueFloat64);
    buffer.putFloat64(value);
  } else if (value is String) {
    buffer.putUint8(_valueString);
    final List<int> bytes = utf8.encoder.convert(value);
    writeSize(buffer, bytes.length);
    buffer.putUint8List(bytes);
  } else if (value is Uint8List) {
    buffer.putUint8(_valueUint8List);
    writeSize(buffer, value.length);
    buffer.putUint8List(value);
  } else if (value is Int32List) {
    buffer.putUint8(_valueInt32List);
    writeSize(buffer, value.length);
    buffer.putInt32List(value);
  } else if (value is Int64List) {
    buffer.putUint8(_valueInt64List);
    writeSize(buffer, value.length);
    buffer.putInt64List(value);
  } else if (value is Float64List) {
    buffer.putUint8(_valueFloat64List);
    writeSize(buffer, value.length);
    buffer.putFloat64List(value);
  } else if (value is List) {
    buffer.putUint8(_valueList);
    writeSize(buffer, value.length);
    for (final dynamic item in value) {
      writeValue(buffer, item);
    }
  } else if (value is Map) {
    buffer.putUint8(_valueMap);
    writeSize(buffer, value.length);
    value.forEach((dynamic key, dynamic value) {
      writeValue(buffer, key);
      writeValue(buffer, value);
    });
  } else {
    throw ArgumentError.value(value);
  }
}