Fix lint violations (#350)
diff --git a/protobuf/analysis_options.yaml b/protobuf/analysis_options.yaml
index 108d105..88748cf 100644
--- a/protobuf/analysis_options.yaml
+++ b/protobuf/analysis_options.yaml
@@ -1 +1,5 @@
include: package:pedantic/analysis_options.yaml
+
+linter:
+ rules:
+ prefer_spread_collections: false
diff --git a/protobuf/benchmarks/benchmark_js.dart b/protobuf/benchmarks/benchmark_js.dart
index 3a864f2..0d32987 100644
--- a/protobuf/benchmarks/benchmark_js.dart
+++ b/protobuf/benchmarks/benchmark_js.dart
@@ -12,13 +12,13 @@
import 'd8.dart';
final files = [
- "benchmarks/datasets/google_message1/proto3/dataset.google_message1_proto3.pb",
- "benchmarks/datasets/google_message1/proto2/dataset.google_message1_proto2.pb",
- "benchmarks/datasets/google_message2/dataset.google_message2.pb"
+ 'benchmarks/datasets/google_message1/proto3/dataset.google_message1_proto3.pb',
+ 'benchmarks/datasets/google_message1/proto2/dataset.google_message1_proto2.pb',
+ 'benchmarks/datasets/google_message2/dataset.google_message2.pb'
];
void main(List<String> arguments) {
- final List<Dataset> datasets = files
+ final datasets = files
.map((file) => Dataset.fromBinary(readAsBytesSync(file)))
.toList(growable: false);
diff --git a/protobuf/benchmarks/common.dart b/protobuf/benchmarks/common.dart
index 086746e..9259375 100644
--- a/protobuf/benchmarks/common.dart
+++ b/protobuf/benchmarks/common.dart
@@ -63,32 +63,32 @@
Dataset._(this.name, this.factories);
}
-typedef dynamic FromBufferFactory(List<int> binary);
-typedef dynamic FromJsonFactory(String json);
+typedef FromBufferFactory = dynamic Function(List<int> binary);
+typedef FromJsonFactory = dynamic Function(String json);
class Factories {
final FromBufferFactory fromBuffer;
final FromJsonFactory fromJson;
static Factories forMessage(String name) =>
- _factories[name] ?? (throw "Unsupported message: ${name}");
+ _factories[name] ?? (throw 'Unsupported message: ${name}');
/// Mapping between [BenchmarkProto.messageName] and corresponding
/// deserialization factories.
static final _factories = {
- "benchmarks.proto2.GoogleMessage1": Factories._(
+ 'benchmarks.proto2.GoogleMessage1': Factories._(
fromBuffer: (List<int> binary) => p2.GoogleMessage1.fromBuffer(binary),
fromJson: (String json) => p2.GoogleMessage1.fromJson(json)),
- "benchmarks.proto3.GoogleMessage1": Factories._(
+ 'benchmarks.proto3.GoogleMessage1': Factories._(
fromBuffer: (List<int> binary) => p3.GoogleMessage1.fromBuffer(binary),
fromJson: (String json) => p3.GoogleMessage1.fromJson(json)),
- "benchmarks.proto2.GoogleMessage2": Factories._(
+ 'benchmarks.proto2.GoogleMessage2': Factories._(
fromBuffer: (List<int> binary) => GoogleMessage2.fromBuffer(binary),
fromJson: (String json) => GoogleMessage2.fromJson(json)),
- "benchmarks.google_message3.GoogleMessage3": Factories._(
+ 'benchmarks.google_message3.GoogleMessage3': Factories._(
fromBuffer: (List<int> binary) => GoogleMessage3.fromBuffer(binary),
fromJson: (String json) => GoogleMessage3.fromJson(json)),
- "benchmarks.google_message4.GoogleMessage4": Factories._(
+ 'benchmarks.google_message4.GoogleMessage4': Factories._(
fromBuffer: (List<int> binary) => GoogleMessage4.fromBuffer(binary),
fromJson: (String json) => GoogleMessage4.fromJson(json)),
};
@@ -105,8 +105,9 @@
/// Binary deserialization benchmark.
class FromBinaryBenchmark extends _ProtobufBenchmark {
- FromBinaryBenchmark(datasets) : super(datasets, "FromBinary");
+ FromBinaryBenchmark(datasets) : super(datasets, 'FromBinary');
+ @override
void run() {
for (var i = 0; i < datasets.length; i++) {
final ds = datasets[i];
@@ -120,8 +121,9 @@
/// Binary serialization benchmark.
class ToBinaryBenchmark extends _ProtobufBenchmark {
- ToBinaryBenchmark(datasets) : super(datasets, "ToBinary");
+ ToBinaryBenchmark(datasets) : super(datasets, 'ToBinary');
+ @override
void run() {
for (var i = 0; i < datasets.length; i++) {
final ds = datasets[i];
@@ -134,8 +136,9 @@
/// JSON deserialization benchmark.
class FromJsonBenchmark extends _ProtobufBenchmark {
- FromJsonBenchmark(datasets) : super(datasets, "FromJson");
+ FromJsonBenchmark(datasets) : super(datasets, 'FromJson');
+ @override
void run() {
for (var i = 0; i < datasets.length; i++) {
final ds = datasets[i];
@@ -149,8 +152,9 @@
/// JSON serialization benchmark.
class ToJsonBenchmark extends _ProtobufBenchmark {
- ToJsonBenchmark(datasets) : super(datasets, "ToJson");
+ ToJsonBenchmark(datasets) : super(datasets, 'ToJson');
+ @override
void run() {
for (var i = 0; i < datasets.length; i++) {
final ds = datasets[i];
diff --git a/protobuf/lib/src/protobuf/builder_info.dart b/protobuf/lib/src/protobuf/builder_info.dart
index a492f96..95fa3b0 100644
--- a/protobuf/lib/src/protobuf/builder_info.dart
+++ b/protobuf/lib/src/protobuf/builder_info.dart
@@ -9,7 +9,7 @@
/// The fully qualified name of this message.
final String qualifiedMessageName;
final List<FieldInfo> byIndex = <FieldInfo>[];
- final Map<int, FieldInfo> fieldInfo = Map<int, FieldInfo>();
+ final Map<int, FieldInfo> fieldInfo = <int, FieldInfo>{};
final Map<String, FieldInfo> byTagAsString = <String, FieldInfo>{};
final Map<String, FieldInfo> byName = <String, FieldInfo>{};
// Maps a tag number to the corresponding oneof index (if any).
@@ -30,7 +30,7 @@
this.createEmptyInstance,
this.toProto3Json,
this.fromProto3Json})
- : qualifiedMessageName = "${package.prefix}$messageName";
+ : qualifiedMessageName = '${package.prefix}$messageName';
void add<T>(
int tagNumber,
@@ -90,7 +90,7 @@
// maps.
if (!fi._isDummy) {
fieldInfo[fi.tagNumber] = fi;
- byTagAsString["${fi.tagNumber}"] = fi;
+ byTagAsString['${fi.tagNumber}'] = fi;
byName[fi.name] = fi;
}
}
@@ -210,8 +210,7 @@
List<ProtobufEnum> enumValues,
PackageName packageName = const PackageName(''),
String protoName}) {
- BuilderInfo mapEntryBuilderInfo = BuilderInfo(entryClassName,
- package: packageName)
+ var mapEntryBuilderInfo = BuilderInfo(entryClassName, package: packageName)
..add(PbMap._keyFieldNumber, 'key', keyFieldType, null, null, null, null)
..add(PbMap._valueFieldNumber, 'value', valueFieldType, null,
valueCreator, valueOf, enumValues);
@@ -223,39 +222,39 @@
bool containsTagNumber(int tagNumber) => fieldInfo.containsKey(tagNumber);
- defaultValue(int tagNumber) {
- MakeDefaultFunc func = makeDefault(tagNumber);
+ dynamic defaultValue(int tagNumber) {
+ var func = makeDefault(tagNumber);
return func == null ? null : func();
}
// Returns the field name for a given tag number, for debugging purposes.
String fieldName(int tagNumber) {
- FieldInfo i = fieldInfo[tagNumber];
+ var i = fieldInfo[tagNumber];
return i != null ? i.name : null;
}
int fieldType(int tagNumber) {
- FieldInfo i = fieldInfo[tagNumber];
+ var i = fieldInfo[tagNumber];
return i != null ? i.type : null;
}
MakeDefaultFunc makeDefault(int tagNumber) {
- FieldInfo i = fieldInfo[tagNumber];
+ var i = fieldInfo[tagNumber];
return i != null ? i.makeDefault : null;
}
CreateBuilderFunc subBuilder(int tagNumber) {
- FieldInfo i = fieldInfo[tagNumber];
+ var i = fieldInfo[tagNumber];
return i != null ? i.subBuilder : null;
}
int tagNumber(String fieldName) {
- FieldInfo i = byName[fieldName];
+ var i = byName[fieldName];
return i != null ? i.tagNumber : null;
}
ValueOfFunc valueOfFunc(int tagNumber) {
- FieldInfo i = fieldInfo[tagNumber];
+ var i = fieldInfo[tagNumber];
return i != null ? i.valueOf : null;
}
@@ -279,7 +278,7 @@
GeneratedMessage _makeEmptyMessage(
int tagNumber, ExtensionRegistry extensionRegistry) {
- CreateBuilderFunc subBuilderFunc = subBuilder(tagNumber);
+ var subBuilderFunc = subBuilder(tagNumber);
if (subBuilderFunc == null && extensionRegistry != null) {
subBuilderFunc = extensionRegistry
.getExtension(qualifiedMessageName, tagNumber)
@@ -288,8 +287,9 @@
return subBuilderFunc();
}
- _decodeEnum(int tagNumber, ExtensionRegistry registry, int rawValue) {
- ValueOfFunc f = valueOfFunc(tagNumber);
+ ProtobufEnum _decodeEnum(
+ int tagNumber, ExtensionRegistry registry, int rawValue) {
+ var f = valueOfFunc(tagNumber);
if (f == null && registry != null) {
f = registry.getExtension(qualifiedMessageName, tagNumber).valueOf;
}
diff --git a/protobuf/lib/src/protobuf/coded_buffer.dart b/protobuf/lib/src/protobuf/coded_buffer.dart
index b7cd016..3709246 100644
--- a/protobuf/lib/src/protobuf/coded_buffer.dart
+++ b/protobuf/lib/src/protobuf/coded_buffer.dart
@@ -31,15 +31,13 @@
assert(registry != null);
while (true) {
- int tag = input.readTag();
+ var tag = input.readTag();
if (tag == 0) return;
- int wireType = tag & 0x7;
- int tagNumber = tag >> 3;
+ var wireType = tag & 0x7;
+ var tagNumber = tag >> 3;
- FieldInfo fi = fs._nonExtensionInfo(tagNumber);
- if (fi == null) {
- fi = registry.getExtension(fs._messageName, tagNumber);
- }
+ var fi = fs._nonExtensionInfo(tagNumber);
+ fi ??= registry.getExtension(fs._messageName, tagNumber);
if (fi == null || !_wireTypeMatches(fi.type, wireType)) {
if (!fs._ensureUnknownFields().mergeFieldFromBuffer(tag, input)) {
@@ -49,7 +47,7 @@
}
// Ignore required/optional packed/unpacked.
- int fieldType = fi.type;
+ var fieldType = fi.type;
fieldType &= ~(PbFieldType._PACKED_BIT | PbFieldType._REQUIRED_BIT);
switch (fieldType) {
case PbFieldType._OPTIONAL_BOOL:
@@ -68,7 +66,7 @@
fs._setFieldUnchecked(fi, input.readDouble());
break;
case PbFieldType._OPTIONAL_ENUM:
- int rawValue = input.readEnum();
+ var rawValue = input.readEnum();
var value = fs._meta._decodeEnum(tagNumber, registry, rawValue);
if (value == null) {
var unknown = fs._ensureUnknownFields();
@@ -78,8 +76,7 @@
}
break;
case PbFieldType._OPTIONAL_GROUP:
- GeneratedMessage subMessage =
- fs._meta._makeEmptyMessage(tagNumber, registry);
+ var subMessage = fs._meta._makeEmptyMessage(tagNumber, registry);
var oldValue = fs._getFieldOrNull(fi);
if (oldValue != null) {
subMessage.mergeFromMessage(oldValue);
@@ -118,8 +115,7 @@
fs._setFieldUnchecked(fi, input.readSfixed64());
break;
case PbFieldType._OPTIONAL_MESSAGE:
- GeneratedMessage subMessage =
- fs._meta._makeEmptyMessage(tagNumber, registry);
+ var subMessage = fs._meta._makeEmptyMessage(tagNumber, registry);
var oldValue = fs._getFieldOrNull(fi);
if (oldValue != null) {
subMessage.mergeFromMessage(oldValue);
@@ -146,8 +142,7 @@
_readPackableToListEnum(fs, input, wireType, fi, tagNumber, registry);
break;
case PbFieldType._REPEATED_GROUP:
- GeneratedMessage subMessage =
- fs._meta._makeEmptyMessage(tagNumber, registry);
+ var subMessage = fs._meta._makeEmptyMessage(tagNumber, registry);
input.readGroup(tagNumber, subMessage, registry);
fs._ensureRepeatedField(fi).add(subMessage);
break;
@@ -182,8 +177,7 @@
_readPackable(fs, input, wireType, fi, input.readSfixed64);
break;
case PbFieldType._REPEATED_MESSAGE:
- GeneratedMessage subMessage =
- fs._meta._makeEmptyMessage(tagNumber, registry);
+ var subMessage = fs._meta._makeEmptyMessage(tagNumber, registry);
input.readMessage(subMessage, registry);
fs._ensureRepeatedField(fi).add(subMessage);
break;
@@ -205,7 +199,7 @@
void _readPackableToListEnum(_FieldSet fs, CodedBufferReader input,
int wireType, FieldInfo fi, int tagNumber, ExtensionRegistry registry) {
void readToList(List list) {
- int rawValue = input.readEnum();
+ var rawValue = input.readEnum();
var value = fs._meta._decodeEnum(tagNumber, registry, rawValue);
if (value == null) {
var unknown = fs._ensureUnknownFields();
@@ -220,7 +214,7 @@
void _readPackableToList(_FieldSet fs, CodedBufferReader input, int wireType,
FieldInfo fi, Function readToList) {
- List list = fs._ensureRepeatedField(fi);
+ var list = fs._ensureRepeatedField(fi);
if (wireType == WIRETYPE_LENGTH_DELIMITED) {
// Packed.
diff --git a/protobuf/lib/src/protobuf/coded_buffer_reader.dart b/protobuf/lib/src/protobuf/coded_buffer_reader.dart
index b7e86b4..d61f977 100644
--- a/protobuf/lib/src/protobuf/coded_buffer_reader.dart
+++ b/protobuf/lib/src/protobuf/coded_buffer_reader.dart
@@ -40,7 +40,7 @@
' which claimed to have negative size.');
}
byteLimit += _bufferPos;
- int oldLimit = _currentLimit;
+ var oldLimit = _currentLimit;
if ((oldLimit != -1 && byteLimit > oldLimit) || byteLimit > _sizeLimit) {
throw InvalidProtocolBufferException.truncatedMessage();
}
@@ -73,7 +73,7 @@
throw InvalidProtocolBufferException.recursionLimitExceeded();
}
++_recursionDepth;
- UnknownFieldSet unknownFieldSet = UnknownFieldSet();
+ var unknownFieldSet = UnknownFieldSet();
unknownFieldSet.mergeFromCodedBufferReader(this);
checkLastTagWas(makeTag(fieldNumber, WIRETYPE_END_GROUP));
--_recursionDepth;
@@ -82,7 +82,7 @@
void readMessage(
GeneratedMessage message, ExtensionRegistry extensionRegistry) {
- int length = readInt32();
+ var length = readInt32();
if (_recursionDepth >= _recursionLimit) {
throw InvalidProtocolBufferException.recursionLimitExceeded();
}
@@ -92,7 +92,7 @@
' which claimed to have negative size.');
}
- int oldLimit = _currentLimit;
+ var oldLimit = _currentLimit;
_currentLimit = _bufferPos + length;
if (_currentLimit > oldLimit) {
throw InvalidProtocolBufferException.truncatedMessage();
@@ -122,7 +122,7 @@
bool readBool() => _readRawVarint32(true) != 0;
List<int> readBytes() {
- int length = readInt32();
+ var length = readInt32();
_checkLimit(length);
return Uint8List.view(
_buffer.buffer, _buffer.offsetInBytes + _bufferPos - length, length);
@@ -167,12 +167,12 @@
// Read up to 10 bytes.
// We use a local [bufferPos] variable to avoid repeatedly loading/store the
// this._bufferpos field.
- int bufferPos = _bufferPos;
- int bytes = _currentLimit - bufferPos;
+ var bufferPos = _bufferPos;
+ var bytes = _currentLimit - bufferPos;
if (bytes > 10) bytes = 10;
- int result = 0;
- for (int i = 0; i < bytes; i++) {
- int byte = _buffer[bufferPos++];
+ var result = 0;
+ for (var i = 0; i < bytes; i++) {
+ var byte = _buffer[bufferPos++];
result |= (byte & 0x7f) << (i * 7);
if ((byte & 0x80) == 0) {
result &= 0xffffffff;
@@ -185,19 +185,19 @@
}
Int64 _readRawVarint64() {
- int lo = 0;
- int hi = 0;
+ var lo = 0;
+ var hi = 0;
// Read low 28 bits.
- for (int i = 0; i < 4; i++) {
- int byte = _readRawVarintByte();
+ for (var i = 0; i < 4; i++) {
+ var byte = _readRawVarintByte();
lo |= (byte & 0x7f) << (i * 7);
if ((byte & 0x80) == 0) return Int64.fromInts(hi, lo);
}
// Read middle 7 bits: 4 low belong to low part above,
// 3 remaining belong to hi.
- int byte = _readRawVarintByte();
+ var byte = _readRawVarintByte();
lo |= (byte & 0xf) << 28;
hi = (byte >> 4) & 0x7;
if ((byte & 0x80) == 0) {
@@ -205,8 +205,8 @@
}
// Read remaining bits of hi.
- for (int i = 0; i < 5; i++) {
- int byte = _readRawVarintByte();
+ for (var i = 0; i < 5; i++) {
+ var byte = _readRawVarintByte();
hi |= (byte & 0x7f) << ((i * 7) + 3);
if ((byte & 0x80) == 0) return Int64.fromInts(hi, lo);
}
diff --git a/protobuf/lib/src/protobuf/coded_buffer_writer.dart b/protobuf/lib/src/protobuf/coded_buffer_writer.dart
index e4f6781..f19cb63 100644
--- a/protobuf/lib/src/protobuf/coded_buffer_writer.dart
+++ b/protobuf/lib/src/protobuf/coded_buffer_writer.dart
@@ -63,7 +63,7 @@
}
void writeField(int fieldNumber, int fieldType, fieldValue) {
- final int valueType = fieldType & ~0x07;
+ final valueType = fieldType & ~0x07;
if ((fieldType & PbFieldType._PACKED_BIT) != 0) {
if (!fieldValue.isEmpty) {
@@ -77,12 +77,12 @@
return;
}
- final int wireFormat = _wireTypes[_valueTypeIndex(valueType)];
+ final wireFormat = _wireTypes[_valueTypeIndex(valueType)];
if ((fieldType & PbFieldType._MAP_BIT) != 0) {
- final int keyWireFormat =
+ final keyWireFormat =
_wireTypes[_valueTypeIndex(fieldValue.keyFieldType)];
- final int valueWireFormat =
+ final valueWireFormat =
_wireTypes[_valueTypeIndex(fieldValue.valueFieldType)];
fieldValue.forEach((key, value) {
@@ -107,7 +107,7 @@
}
Uint8List toBuffer() {
- Uint8List result = Uint8List(_bytesTotal);
+ var result = Uint8List(_bytesTotal);
writeTo(result);
return result;
}
@@ -124,14 +124,14 @@
_commitChunk(false);
_commitSplice();
- int outPos = offset; // Output position in the buffer.
- int chunkIndex = 0, chunkPos = 0; // Position within _outputChunks.
- for (int i = 0; i < _splices.length; i++) {
+ var outPos = offset; // Output position in the buffer.
+ var chunkIndex = 0, chunkPos = 0; // Position within _outputChunks.
+ for (var i = 0; i < _splices.length; i++) {
final action = _splices[i];
if (action is int) {
if (action <= 0) {
// action is a positive varint to be emitted into the output buffer.
- int v = 0 - action; // Note: 0 - action to avoid -0.0 in JS.
+ var v = 0 - action; // Note: 0 - action to avoid -0.0 in JS.
while (v >= 0x80) {
buffer[outPos++] = 0x80 | (v & 0x7f);
v >>= 7;
@@ -140,7 +140,7 @@
} else {
// action is an amount of bytes to copy from _outputChunks into the
// buffer.
- int bytesToCopy = action;
+ var bytesToCopy = action;
while (bytesToCopy > 0) {
final Uint8List chunk = _outputChunks[chunkIndex];
final int bytesInChunk = _outputChunks[chunkIndex + 1];
@@ -233,7 +233,7 @@
/// of bytes written into the reserved slice space.
int _startLengthDelimited() {
_commitSplice();
- int index = _splices.length;
+ var index = _splices.length;
// Reserve a space for a splice and use it to record the current number of
// bytes written so that we can compute the length of data later in
// _endLengthDelimited.
@@ -259,7 +259,7 @@
void _writeVarint32(int value) {
_ensureBytes(5);
- int i = _bytesInChunk;
+ var i = _bytesInChunk;
while (value >= 0x80) {
_outputChunk[i++] = 0x80 | (value & 0x7f);
value >>= 7;
@@ -271,9 +271,9 @@
void _writeVarint64(Int64 value) {
_ensureBytes(10);
- int i = _bytesInChunk;
- int lo = value.toUnsigned(32).toInt();
- int hi = (value >> 32).toUnsigned(32).toInt();
+ var i = _bytesInChunk;
+ var lo = value.toUnsigned(32).toInt();
+ var hi = (value >> 32).toUnsigned(32).toInt();
while (hi > 0 || lo >= 0x80) {
_outputChunk[i++] = 0x80 | (lo & 0x7f);
lo = (lo >> 7) | ((hi & 0x7f) << 25);
@@ -297,8 +297,8 @@
}
void _writeFloat(double value) {
- const double MIN_FLOAT_DENORM = 1.401298464324817E-45;
- const double MAX_FLOAT = 3.4028234663852886E38;
+ const MIN_FLOAT_DENORM = 1.401298464324817E-45;
+ const MAX_FLOAT = 3.4028234663852886E38;
if (value.isNaN) {
_writeInt32(0x7fc00000);
} else if (value.abs() < MIN_FLOAT_DENORM) {
@@ -390,12 +390,12 @@
}
}
- _writeBytesNoTag(dynamic value) {
+ void _writeBytesNoTag(dynamic value) {
writeInt32NoTag(value.length);
_writeRawBytes(value);
}
- _writeTag(int fieldNumber, int wireFormat) {
+ void _writeTag(int fieldNumber, int wireFormat) {
writeInt32NoTag(makeTag(fieldNumber, wireFormat));
}
@@ -417,16 +417,16 @@
/// Has a specialization for Uint8List for performance.
int _copyInto(Uint8List buffer, int pos, TypedData value) {
if (value is Uint8List) {
- int len = value.length;
- for (int j = 0; j < len; j++) {
+ var len = value.length;
+ for (var j = 0; j < len; j++) {
buffer[pos++] = value[j];
}
return pos;
} else {
- int len = value.lengthInBytes;
- Uint8List u8 = Uint8List.view(
+ var len = value.lengthInBytes;
+ var u8 = Uint8List.view(
value.buffer, value.offsetInBytes, value.lengthInBytes);
- for (int j = 0; j < len; j++) {
+ for (var j = 0; j < len; j++) {
buffer[pos++] = u8[j];
}
return pos;
diff --git a/protobuf/lib/src/protobuf/exceptions.dart b/protobuf/lib/src/protobuf/exceptions.dart
index bc8d43c..0c34665 100644
--- a/protobuf/lib/src/protobuf/exceptions.dart
+++ b/protobuf/lib/src/protobuf/exceptions.dart
@@ -9,6 +9,7 @@
InvalidProtocolBufferException._(this.message);
+ @override
String toString() => 'InvalidProtocolBufferException: $message';
InvalidProtocolBufferException.invalidEndTag()
diff --git a/protobuf/lib/src/protobuf/extension.dart b/protobuf/lib/src/protobuf/extension.dart
index 2d87f79..cecc257 100644
--- a/protobuf/lib/src/protobuf/extension.dart
+++ b/protobuf/lib/src/protobuf/extension.dart
@@ -30,8 +30,10 @@
: super.repeated(name, tagNumber, null, fieldType, check, subBuilder,
valueOf: valueOf, enumValues: enumValues, protoName: protoName);
+ @override
int get hashCode => extendee.hashCode * 31 + tagNumber;
+ @override
bool operator ==(other) {
if (other is! Extension) return false;
diff --git a/protobuf/lib/src/protobuf/extension_field_set.dart b/protobuf/lib/src/protobuf/extension_field_set.dart
index fe301db..e516a9d 100644
--- a/protobuf/lib/src/protobuf/extension_field_set.dart
+++ b/protobuf/lib/src/protobuf/extension_field_set.dart
@@ -14,7 +14,7 @@
Extension _getInfoOrNull(int tagNumber) => _info[tagNumber];
- _getFieldOrDefault(Extension fi) {
+ dynamic _getFieldOrDefault(Extension fi) {
if (fi.isRepeated) return _getList(fi);
_validateInfo(fi);
// TODO(skybrian) seems unnecessary to add info?
@@ -62,7 +62,7 @@
return newList;
}
- _getFieldOrNull(Extension extension) => _values[extension.tagNumber];
+ dynamic _getFieldOrNull(Extension extension) => _values[extension.tagNumber];
void _clearFieldAndInfo(Extension fi) {
_clearField(fi);
@@ -82,7 +82,7 @@
var fi = _getInfoOrNull(tagNumber);
if (fi == null) {
throw ArgumentError(
- "tag $tagNumber not defined in $_parent._messageName");
+ 'tag $tagNumber not defined in $_parent._messageName');
}
if (fi.isRepeated) {
throw ArgumentError(_parent._setFieldFailedMessage(
@@ -136,7 +136,7 @@
Iterable<int> get _tagNumbers => _values.keys;
Iterable<Extension> get _infos => _info.values;
- get _hasValues => _values.isNotEmpty;
+ bool get _hasValues => _values.isNotEmpty;
bool _equalValues(_ExtensionFieldSet other) =>
other != null && _areMapsEqual(_values, other._values);
@@ -148,8 +148,8 @@
/// Repeated fields are copied.
/// Extensions cannot contain map fields.
void _shallowCopyValues(_ExtensionFieldSet original) {
- for (int tagNumber in original._tagNumbers) {
- Extension extension = original._getInfoOrNull(tagNumber);
+ for (var tagNumber in original._tagNumbers) {
+ var extension = original._getInfoOrNull(tagNumber);
_addInfoUnchecked(extension);
final value = original._getFieldOrNull(extension);
@@ -166,7 +166,7 @@
void _markReadOnly() {
if (_isReadOnly) return;
_isReadOnly = true;
- for (Extension field in _info.values) {
+ for (var field in _info.values) {
if (field.isRepeated) {
final entries = _values[field.tagNumber];
if (entries == null) continue;
diff --git a/protobuf/lib/src/protobuf/extension_registry.dart b/protobuf/lib/src/protobuf/extension_registry.dart
index fd04cda..9daeb1a 100644
--- a/protobuf/lib/src/protobuf/extension_registry.dart
+++ b/protobuf/lib/src/protobuf/extension_registry.dart
@@ -14,8 +14,8 @@
/// Stores an [extension] in the registry.
void add(Extension extension) {
- var map = _extensions.putIfAbsent(
- extension.extendee, () => Map<int, Extension>());
+ var map =
+ _extensions.putIfAbsent(extension.extendee, () => <int, Extension>{});
map[extension.tagNumber] = extension;
}
@@ -105,13 +105,12 @@
UnknownFieldSet ensureUnknownFields() =>
resultUnknownFields ??= ensureResult()._fieldSet._unknownFields;
- UnknownFieldSet messageUnknownFields = message._fieldSet._unknownFields;
+ var messageUnknownFields = message._fieldSet._unknownFields;
if (messageUnknownFields != null) {
- CodedBufferWriter codedBufferWriter = CodedBufferWriter();
+ var codedBufferWriter = CodedBufferWriter();
extensionRegistry._extensions[message.info_.qualifiedMessageName]
?.forEach((tagNumber, extension) {
- final UnknownFieldSetField unknownField =
- messageUnknownFields._fields[tagNumber];
+ final unknownField = messageUnknownFields._fields[tagNumber];
if (unknownField != null) {
unknownField.writeTo(tagNumber, codedBufferWriter);
ensureUnknownFields()._fields.remove(tagNumber);
@@ -137,10 +136,9 @@
final messageEntries = message._fieldSet._values[field.index];
if (messageEntries == null) return;
if (field.isGroupOrMessage) {
- for (int i = 0; i < messageEntries.length; i++) {
+ for (var i = 0; i < messageEntries.length; i++) {
final GeneratedMessage entry = messageEntries[i];
- final GeneratedMessage reparsedEntry =
- _reparseMessage(entry, extensionRegistry);
+ final reparsedEntry = _reparseMessage(entry, extensionRegistry);
if (!identical(entry, reparsedEntry)) {
ensureEntries()[i] = reparsedEntry;
}
@@ -152,8 +150,7 @@
if (_isGroupOrMessage(field.valueFieldType)) {
for (var key in messageMap.keys) {
final GeneratedMessage value = messageMap[key];
- final GeneratedMessage reparsedValue =
- _reparseMessage(value, extensionRegistry);
+ final reparsedValue = _reparseMessage(value, extensionRegistry);
if (!identical(value, reparsedValue)) {
ensureMap()[key] = reparsedValue;
}
@@ -162,8 +159,8 @@
} else if (field.isGroupOrMessage) {
final messageSubField = message._fieldSet._values[field.index];
if (messageSubField == null) return;
- final GeneratedMessage reparsedSubField =
- _reparseMessage(messageSubField, extensionRegistry);
+ final reparsedSubField =
+ _reparseMessage<GeneratedMessage>(messageSubField, extensionRegistry);
if (!identical(messageSubField, reparsedSubField)) {
ensureResult()._fieldSet._values[field.index] = reparsedSubField;
}
@@ -180,18 +177,24 @@
class _EmptyExtensionRegistry implements ExtensionRegistry {
const _EmptyExtensionRegistry();
- get _extensions => const <String, Map<int, Extension>>{};
+ @override
+ Map<String, Map<int, Extension>> get _extensions =>
+ const <String, Map<int, Extension>>{};
+ @override
void add(Extension extension) {
throw UnsupportedError('Immutable ExtensionRegistry');
}
+ @override
void addAll(Iterable<Extension> extensions) {
throw UnsupportedError('Immutable ExtensionRegistry');
}
+ @override
Extension getExtension(String messageName, int tagNumber) => null;
+ @override
T reparseMessage<T extends GeneratedMessage>(T message) =>
_reparseMessage(message, this);
}
diff --git a/protobuf/lib/src/protobuf/field_info.dart b/protobuf/lib/src/protobuf/field_info.dart
index 743a55a..1a52faf 100644
--- a/protobuf/lib/src/protobuf/field_info.dart
+++ b/protobuf/lib/src/protobuf/field_info.dart
@@ -101,7 +101,7 @@
/// Returns a read-only default value for a field.
/// (Unlike getField, doesn't create a repeated field.)
- get readonlyDefault {
+ dynamic get readonlyDefault {
if (isRepeated) {
return _emptyList ??= FrozenPbList._([]);
}
@@ -150,8 +150,8 @@
if (!list[0]._fieldSet._hasRequiredFields) return;
// Recurse on each item in the list.
- int position = 0;
- for (GeneratedMessage message in list) {
+ var position = 0;
+ for (var message in list) {
message._fieldSet
._appendInvalidFields(problems, '$prefix$name[$position].');
position++;
@@ -180,6 +180,7 @@
return fs._ensureRepeatedField<T>(this);
}
+ @override
String toString() => name;
}
diff --git a/protobuf/lib/src/protobuf/field_set.dart b/protobuf/lib/src/protobuf/field_set.dart
index cb4b376..11df0c3 100644
--- a/protobuf/lib/src/protobuf/field_set.dart
+++ b/protobuf/lib/src/protobuf/field_set.dart
@@ -4,16 +4,17 @@
part of protobuf;
-typedef void FrozenMessageErrorHandler(String messageName, [String methodName]);
+typedef FrozenMessageErrorHandler = void Function(String messageName,
+ [String methodName]);
void defaultFrozenMessageModificationHandler(String messageName,
[String methodName]) {
if (methodName != null) {
throw UnsupportedError(
- "Attempted to call $methodName on a read-only message ($messageName)");
+ 'Attempted to call $methodName on a read-only message ($messageName)');
}
throw UnsupportedError(
- "Attempted to change a read-only message ($messageName)");
+ 'Attempted to change a read-only message ($messageName)');
}
/// Invoked when an attempt is made to modify a frozen message.
@@ -96,18 +97,18 @@
final Map<int, int> _oneofCases;
_FieldSet(this._message, BuilderInfo meta, this._eventPlugin)
- : this._meta = meta,
+ : _meta = meta,
_values = _makeValueList(meta.byIndex.length),
_oneofCases = meta.oneofs.isEmpty ? null : <int, int>{};
- static _makeValueList(int length) {
+ static List _makeValueList(int length) {
if (length == 0) return _zeroList;
return List(length);
}
// Use a fixed length list and not a constant list to ensure that _values
// always has the same implementation type.
- static List _zeroList = List(0);
+ static final List _zeroList = List(0);
// Metadata about multiple fields
@@ -152,7 +153,7 @@
FieldInfo _ensureInfo(int tagNumber) {
var fi = _getFieldInfoOrNull(tagNumber);
if (fi != null) return fi;
- throw ArgumentError("tag $tagNumber not defined in $_messageName");
+ throw ArgumentError('tag $tagNumber not defined in $_messageName');
}
/// Returns the FieldInfo for a regular or extension field.
@@ -207,7 +208,7 @@
/// Works for both extended and non-extended fields.
/// Creates repeated fields (unless read-only).
/// Suitable for public API.
- _getField(int tagNumber) {
+ dynamic _getField(int tagNumber) {
var fi = _nonExtensionInfo(tagNumber);
if (fi != null) {
var value = _values[fi.index];
@@ -220,10 +221,10 @@
return _extensions._getFieldOrDefault(fi);
}
}
- throw ArgumentError("tag $tagNumber not defined in $_messageName");
+ throw ArgumentError('tag $tagNumber not defined in $_messageName');
}
- _getDefault(FieldInfo fi) {
+ dynamic _getDefault(FieldInfo fi) {
if (!fi.isRepeated) return fi.makeDefault();
if (_isReadOnly) return fi.readonlyDefault;
@@ -260,7 +261,7 @@
return value;
}
- _getFieldOrNullByTag(int tagNumber) {
+ dynamic _getFieldOrNullByTag(int tagNumber) {
var fi = _getFieldInfoOrNull(tagNumber);
if (fi == null) return null;
return _getFieldOrNull(fi);
@@ -270,7 +271,7 @@
///
/// Works for both extended and non-extend fields.
/// Works for both repeated and non-repeated fields.
- _getFieldOrNull(FieldInfo fi) {
+ dynamic _getFieldOrNull(FieldInfo fi) {
if (fi.index != null) return _values[fi.index];
if (!_hasExtensions) return null;
return _extensions._getFieldOrNull(fi);
@@ -295,7 +296,7 @@
_oneofCases.remove(_meta.oneofs[fi.tagNumber]);
}
- int oneofIndex = _meta.oneofs[fi.tagNumber];
+ var oneofIndex = _meta.oneofs[fi.tagNumber];
if (oneofIndex != null) _oneofCases[oneofIndex] = 0;
return;
}
@@ -322,7 +323,7 @@
var fi = _nonExtensionInfo(tagNumber);
if (fi == null) {
if (!_hasExtensions) {
- throw ArgumentError("tag $tagNumber not defined in $_messageName");
+ throw ArgumentError('tag $tagNumber not defined in $_messageName');
}
_extensions._setField(tagNumber, value);
return;
@@ -387,8 +388,8 @@
/// Sets a non-extended field and fires events.
void _setNonExtensionFieldUnchecked(FieldInfo fi, value) {
- int tag = fi.tagNumber;
- int oneofIndex = _meta.oneofs[tag];
+ var tag = fi.tagNumber;
+ var oneofIndex = _meta.oneofs[tag];
if (oneofIndex != null) {
_clearField(_oneofCases[oneofIndex]);
_oneofCases[oneofIndex] = tag;
@@ -511,9 +512,7 @@
/// The implementation of a generated getter for Int64 fields.
Int64 _$getI64(int index) {
var value = _values[index];
- if (value == null) {
- value = _getDefault(_nonExtensionInfoByIndex(index));
- }
+ value ??= _getDefault(_nonExtensionInfoByIndex(index));
Int64 result = value;
return result;
}
@@ -541,8 +540,8 @@
if (_hasObservers) {
_eventPlugin.beforeSetField(_nonExtensionInfoByIndex(index), value);
}
- int tag = _meta.byIndex[index].tagNumber;
- int oneofIndex = _meta.oneofs[tag];
+ var tag = _meta.byIndex[index].tagNumber;
+ var oneofIndex = _meta.oneofs[tag];
if (oneofIndex != null) {
_clearField(_oneofCases[oneofIndex]);
@@ -571,7 +570,7 @@
}
}
if (_hasExtensions) {
- for (int key in _extensions._tagNumbers) {
+ for (var key in _extensions._tagNumbers) {
var fi = _extensions._getInfoOrNull(key);
_eventPlugin.beforeClearField(fi);
}
@@ -683,7 +682,7 @@
}
// Hash with descriptor.
- int hash = _HashUtils._combine(0, _meta.hashCode);
+ var hash = _HashUtils._combine(0, _meta.hashCode);
// Hash with fields.
hash = hashEachField(hash);
// Hash with unknown fields.
@@ -757,13 +756,13 @@
// this case, we can merge the non-extension fields without field lookups or
// validation checks.
- for (FieldInfo fi in other._infosSortedByTag) {
+ for (var fi in other._infosSortedByTag) {
var value = other._values[fi.index];
if (value != null) _mergeField(fi, value, isExtension: false);
}
if (other._hasExtensions) {
var others = other._extensions;
- for (int tagNumber in others._tagNumbers) {
+ for (var tagNumber in others._tagNumbers) {
var extension = others._getInfoOrNull(tagNumber);
var value = others._getFieldOrNull(extension);
_mergeField(extension, value, isExtension: true);
@@ -776,17 +775,17 @@
}
void _mergeField(FieldInfo otherFi, fieldValue, {bool isExtension}) {
- int tagNumber = otherFi.tagNumber;
+ var tagNumber = otherFi.tagNumber;
// Determine the FieldInfo to use.
// Don't allow regular fields to be overwritten by extensions.
- FieldInfo fi = _nonExtensionInfo(tagNumber);
+ var fi = _nonExtensionInfo(tagNumber);
if (fi == null && isExtension) {
// This will overwrite any existing extension field info.
fi = otherFi;
}
- bool mustClone = _isGroupOrMessage(otherFi.type);
+ var mustClone = _isGroupOrMessage(otherFi.type);
if (fi.isMapField) {
MapFieldInfo f = fi;
@@ -807,7 +806,7 @@
// fieldValue must be a PbListBase of GeneratedMessage.
PbListBase<GeneratedMessage> pbList = fieldValue;
var repeatedFields = fi._ensureRepeatedField(this);
- for (int i = 0; i < pbList.length; ++i) {
+ for (var i = 0; i < pbList.length; ++i) {
repeatedFields.add(_cloneMessage(pbList[i]));
}
} else {
@@ -895,8 +894,8 @@
/// Map fields and repeated fields are copied.
void _shallowCopyValues(_FieldSet original) {
_values.setRange(0, original._values.length, original._values);
- for (int index = 0; index < _meta.byIndex.length; index++) {
- FieldInfo fieldInfo = _meta.byIndex[index];
+ for (var index = 0; index < _meta.byIndex.length; index++) {
+ var fieldInfo = _meta.byIndex[index];
if (fieldInfo.isMapField) {
PbMap map = _values[index];
if (map != null) {
diff --git a/protobuf/lib/src/protobuf/generated_message.dart b/protobuf/lib/src/protobuf/generated_message.dart
index 0944569..13f4dfb 100644
--- a/protobuf/lib/src/protobuf/generated_message.dart
+++ b/protobuf/lib/src/protobuf/generated_message.dart
@@ -4,9 +4,9 @@
part of protobuf;
-typedef GeneratedMessage CreateBuilderFunc();
-typedef MakeDefaultFunc();
-typedef ProtobufEnum ValueOfFunc(int value);
+typedef CreateBuilderFunc = GeneratedMessage Function();
+typedef MakeDefaultFunc = Function();
+typedef ValueOfFunc = ProtobufEnum Function(int value);
/// The base class for all protobuf message types.
///
@@ -122,6 +122,7 @@
///
/// The hash may change when any field changes (recursively).
/// Therefore, protobufs used as map keys shouldn't be changed.
+ @override
int get hashCode => _fieldSet._hashCode;
/// Returns a String representation of this message.
@@ -132,6 +133,7 @@
///
/// Note that this format is absolutely subject to change, and should only
/// ever be used for debugging.
+ @override
String toString() => toDebugString();
/// Returns a String representation of this message.
@@ -146,15 +148,15 @@
void check() {
if (!isInitialized()) {
- List<String> invalidFields = <String>[];
- _fieldSet._appendInvalidFields(invalidFields, "");
- String missingFields = (invalidFields..sort()).join(', ');
+ var invalidFields = <String>[];
+ _fieldSet._appendInvalidFields(invalidFields, '');
+ var missingFields = (invalidFields..sort()).join(', ');
throw StateError('Message missing required fields: $missingFields');
}
}
Uint8List writeToBuffer() {
- CodedBufferWriter out = CodedBufferWriter();
+ var out = CodedBufferWriter();
writeToCodedBufferWriter(out);
return out.toBuffer();
}
@@ -176,7 +178,7 @@
/// the existing sub-message.
void mergeFromBuffer(List<int> input,
[ExtensionRegistry extensionRegistry = ExtensionRegistry.EMPTY]) {
- CodedBufferReader codedInput = CodedBufferReader(input);
+ var codedInput = CodedBufferReader(input);
_mergeFromCodedBufferReader(_fieldSet, codedInput, extensionRegistry);
codedInput.checkLastTagWas(0);
}
@@ -269,7 +271,7 @@
_mergeFromJsonMap(_fieldSet, jsonMap, extensionRegistry);
}
- static _emptyReviver(k, v) => v;
+ static dynamic _emptyReviver(k, v) => v;
/// Merges field values from a JSON object represented as a Dart map.
///
@@ -311,13 +313,13 @@
/// Returns the value of [extension].
///
/// If not set, returns the extension's default value.
- getExtension(Extension extension) {
+ dynamic getExtension(Extension extension) {
return _fieldSet._ensureExtensions()._getFieldOrDefault(extension);
}
/// Returns the value of the field associated with [tagNumber], or the
/// default value if it is not set.
- getField(int tagNumber) => _fieldSet._getField(tagNumber);
+ dynamic getField(int tagNumber) => _fieldSet._getField(tagNumber);
/// Creates List implementing a mutable repeated field.
///
@@ -339,14 +341,15 @@
///
/// For unset or cleared fields, returns null.
/// Also returns null for unknown tag numbers.
- getFieldOrNull(int tagNumber) => _fieldSet._getFieldOrNullByTag(tagNumber);
+ dynamic getFieldOrNull(int tagNumber) =>
+ _fieldSet._getFieldOrNullByTag(tagNumber);
/// Returns the default value for the given field.
///
/// For repeated fields, returns an immutable empty list
/// (unlike [getField]). For all other fields, returns
/// the same thing that getField() would for a cleared field.
- getDefaultForField(int tagNumber) =>
+ dynamic getDefaultForField(int tagNumber) =>
_fieldSet._ensureInfo(tagNumber).readonlyDefault;
/// Returns [:true:] if a value of [extension] is present.
diff --git a/protobuf/lib/src/protobuf/json.dart b/protobuf/lib/src/protobuf/json.dart
index 23eb4fb..ff1ceb5 100644
--- a/protobuf/lib/src/protobuf/json.dart
+++ b/protobuf/lib/src/protobuf/json.dart
@@ -5,8 +5,8 @@
part of protobuf;
Map<String, dynamic> _writeToJsonMap(_FieldSet fs) {
- convertToMap(dynamic fieldValue, int fieldType) {
- int baseType = PbFieldType._baseType(fieldType);
+ dynamic convertToMap(dynamic fieldValue, int fieldType) {
+ var baseType = PbFieldType._baseType(fieldType);
if (_isRepeated(fieldType)) {
return List.from(fieldValue.map((e) => convertToMap(e, baseType)));
@@ -43,12 +43,12 @@
}
}
- _writeMap(dynamic fieldValue, MapFieldInfo fi) {
- return List.from(fieldValue.entries.map((MapEntry e) => {
- '${PbMap._keyFieldNumber}': convertToMap(e.key, fi.keyFieldType),
- '${PbMap._valueFieldNumber}': convertToMap(e.value, fi.valueFieldType)
- }));
- }
+ List _writeMap(dynamic fieldValue, MapFieldInfo fi) =>
+ List.from(fieldValue.entries.map((MapEntry e) => {
+ '${PbMap._keyFieldNumber}': convertToMap(e.key, fi.keyFieldType),
+ '${PbMap._valueFieldNumber}':
+ convertToMap(e.value, fi.valueFieldType)
+ }));
var result = <String, dynamic>{};
for (var fi in fs._infosSortedByTag) {
@@ -63,7 +63,7 @@
result['${fi.tagNumber}'] = convertToMap(value, fi.type);
}
if (fs._hasExtensions) {
- for (int tagNumber in _sorted(fs._extensions._tagNumbers)) {
+ for (var tagNumber in _sorted(fs._extensions._tagNumbers)) {
var value = fs._extensions._values[tagNumber];
if (value is List && value.isEmpty) {
continue; // It's repeated or an empty byte array.
@@ -79,9 +79,9 @@
// (Called recursively on nested messages.)
void _mergeFromJsonMap(
_FieldSet fs, Map<String, dynamic> json, ExtensionRegistry registry) {
- Iterable<String> keys = json.keys;
+ var keys = json.keys;
var meta = fs._meta;
- for (String key in keys) {
+ for (var key in keys) {
var fi = meta.byTagAsString[key];
if (fi == null) {
if (registry == null) continue; // Unknown tag; skip
@@ -105,7 +105,7 @@
// alloc:
// for (t1 = J.get$iterator$ax(json), t2 = fi.tagNumber, t3 = fi.type,
// t4 = J.getInterceptor$ax(repeated); t1.moveNext$0();)
- for (int i = 0, len = jsonList.length; i < len; i++) {
+ for (var i = 0, len = jsonList.length; i < len; i++) {
var value = jsonList[i];
var convertedValue =
_convertJsonValue(fs, value, fi.tagNumber, fi.type, registry);
@@ -119,7 +119,7 @@
_FieldSet fs, List jsonList, MapFieldInfo fi, ExtensionRegistry registry) {
PbMap map = fi._ensureMapField(fs);
for (Map<String, dynamic> jsonEntry in jsonList) {
- _FieldSet entryFieldSet = map._entryFieldSet();
+ var entryFieldSet = map._entryFieldSet();
final convertedKey = _convertJsonValue(
entryFieldSet,
jsonEntry['${PbMap._keyFieldNumber}'],
@@ -156,7 +156,7 @@
/// Returns the converted value. This function returns [null] if the caller
/// should ignore the field value, because it is an unknown enum value.
/// This function throws [ArgumentError] if it cannot convert the value.
-_convertJsonValue(_FieldSet fs, value, int tagNumber, int fieldType,
+dynamic _convertJsonValue(_FieldSet fs, value, int tagNumber, int fieldType,
ExtensionRegistry registry) {
String expectedType; // for exception message
switch (PbFieldType._baseType(fieldType)) {
@@ -237,8 +237,7 @@
case PbFieldType._MESSAGE_BIT:
if (value is Map) {
Map<String, dynamic> messageValue = value;
- GeneratedMessage subMessage =
- fs._meta._makeEmptyMessage(tagNumber, registry);
+ var subMessage = fs._meta._makeEmptyMessage(tagNumber, registry);
_mergeFromJsonMap(subMessage._fieldSet, messageValue, registry);
return subMessage;
}
diff --git a/protobuf/lib/src/protobuf/json_parsing_context.dart b/protobuf/lib/src/protobuf/json_parsing_context.dart
index 7f27bbb..d9e9f53 100644
--- a/protobuf/lib/src/protobuf/json_parsing_context.dart
+++ b/protobuf/lib/src/protobuf/json_parsing_context.dart
@@ -26,7 +26,7 @@
/// Returns a FormatException indicating the indices to the current [path].
Exception parseException(String message, Object source) {
- String formattedPath = _path.map((s) => '[\"$s\"]').join();
+ var formattedPath = _path.map((s) => '[\"$s\"]').join();
return FormatException(
'Protobuf JSON decoding failed at: root$formattedPath. $message',
source);
diff --git a/protobuf/lib/src/protobuf/mixins/event_mixin.dart b/protobuf/lib/src/protobuf/mixins/event_mixin.dart
index 4741fd2..a611df0 100644
--- a/protobuf/lib/src/protobuf/mixins/event_mixin.dart
+++ b/protobuf/lib/src/protobuf/mixins/event_mixin.dart
@@ -4,10 +4,10 @@
library protobuf.mixins.event;
-import "dart:async" show Stream, StreamController, scheduleMicrotask;
-import "dart:collection" show UnmodifiableListView;
+import 'dart:async' show Stream, StreamController, scheduleMicrotask;
+import 'dart:collection' show UnmodifiableListView;
-import "package:protobuf/protobuf.dart"
+import 'package:protobuf/protobuf.dart'
show GeneratedMessage, FieldInfo, EventPlugin;
/// Provides a stream of changes to fields in a GeneratedMessage.
@@ -62,12 +62,11 @@
}
Stream<List<PbFieldChange>> get changes {
- if (_controller == null) {
- _controller = StreamController.broadcast(sync: true);
- }
+ _controller ??= StreamController.broadcast(sync: true);
return _controller.stream;
}
+ @override
bool get hasObservers => _controller != null && _controller.hasListener;
void deliverChanges() {
@@ -90,7 +89,7 @@
@override
void beforeSetField(FieldInfo fi, newValue) {
var oldValue = _parent.getFieldOrNull(fi.tagNumber);
- if (oldValue == null) oldValue = fi.readonlyDefault;
+ oldValue ??= fi.readonlyDefault;
if (identical(oldValue, newValue)) return;
addEvent(PbFieldChange(_parent, fi, oldValue, newValue));
}
diff --git a/protobuf/lib/src/protobuf/mixins/map_mixin.dart b/protobuf/lib/src/protobuf/mixins/map_mixin.dart
index 9b0a280..2608fb0 100644
--- a/protobuf/lib/src/protobuf/mixins/map_mixin.dart
+++ b/protobuf/lib/src/protobuf/mixins/map_mixin.dart
@@ -4,7 +4,7 @@
library protobuf.mixins.map;
-import "package:protobuf/protobuf.dart" show BuilderInfo;
+import 'package:protobuf/protobuf.dart' show BuilderInfo;
/// Note that this class does not claim to implement [Map]. Instead, this needs
/// to be specified using a dart_options.imports clause specifying MapMixin as a
@@ -18,10 +18,10 @@
BuilderInfo get info_;
void clear();
int getTagNumber(String fieldName);
- getField(int tagNumber);
+ dynamic getField(int tagNumber);
void setField(int tagNumber, var value);
- operator [](key) {
+ dynamic operator [](key) {
if (key is! String) return null;
var tag = getTagNumber(key);
if (tag == null) return null;
@@ -43,8 +43,8 @@
int get length => info_.byName.length;
- remove(key) {
+ dynamic remove(key) {
throw UnsupportedError(
- "remove() not supported by ${info_.qualifiedMessageName}");
+ 'remove() not supported by ${info_.qualifiedMessageName}');
}
}
diff --git a/protobuf/lib/src/protobuf/mixins/well_known.dart b/protobuf/lib/src/protobuf/mixins/well_known.dart
index 2114680..0375840 100644
--- a/protobuf/lib/src/protobuf/mixins/well_known.dart
+++ b/protobuf/lib/src/protobuf/mixins/well_known.dart
@@ -79,17 +79,16 @@
// }
static Object toProto3JsonHelper(
GeneratedMessage message, TypeRegistry typeRegistry) {
- AnyMixin any = message as AnyMixin;
- BuilderInfo info = typeRegistry.lookup(_typeNameFromUrl(any.typeUrl));
+ var any = message as AnyMixin;
+ var info = typeRegistry.lookup(_typeNameFromUrl(any.typeUrl));
if (info == null) {
throw ArgumentError(
'The type of the Any message (${any.typeUrl}) is not in the given typeRegistry.');
}
- GeneratedMessage unpacked = info.createEmptyInstance()
- ..mergeFromBuffer(any.value);
- Object proto3Json = unpacked.toProto3Json();
+ var unpacked = info.createEmptyInstance()..mergeFromBuffer(any.value);
+ var proto3Json = unpacked.toProto3Json();
if (info.toProto3Json == null) {
- Map<String, dynamic> map = proto3Json as Map<String, dynamic>;
+ var map = proto3Json as Map<String, dynamic>;
map['@type'] = any.typeUrl;
return map;
} else {
@@ -107,8 +106,8 @@
final typeUrl = object['@type'];
if (typeUrl is String) {
- AnyMixin any = message as AnyMixin;
- BuilderInfo info = typeRegistry.lookup(_typeNameFromUrl(typeUrl));
+ var any = message as AnyMixin;
+ var info = typeRegistry.lookup(_typeNameFromUrl(typeUrl));
if (info == null) {
throw context.parseException(
'Decoding Any of type ${typeUrl} not in TypeRegistry $typeRegistry',
@@ -120,7 +119,7 @@
? (Map<String, dynamic>.from(object)..remove('@type'))
: object['value'];
// TODO(sigurdm): We lose [context.path].
- GeneratedMessage packedMessage = info.createEmptyInstance()
+ var packedMessage = info.createEmptyInstance()
..mergeFromProto3Json(subJson,
typeRegistry: typeRegistry,
supportNamesWithUnderscores: context.supportNamesWithUnderscores,
@@ -136,7 +135,7 @@
}
String _typeNameFromUrl(String typeUrl) {
- int index = typeUrl.lastIndexOf('/');
+ var index = typeUrl.lastIndexOf('/');
return index < 0 ? '' : typeUrl.substring(index + 1);
}
@@ -161,14 +160,14 @@
///
/// Time zone information will not be preserved.
static void setFromDateTime(TimestampMixin target, DateTime dateTime) {
- int micros = dateTime.microsecondsSinceEpoch;
+ var micros = dateTime.microsecondsSinceEpoch;
target.seconds = Int64(micros ~/ Duration.microsecondsPerSecond);
target.nanos = (micros % Duration.microsecondsPerSecond).toInt() * 1000;
}
static String _twoDigits(int n) {
- if (n >= 10) return "${n}";
- return "0${n}";
+ if (n >= 10) return '${n}';
+ return '0${n}';
}
static final DateTime _minTimestamp = DateTime.utc(1);
@@ -192,8 +191,8 @@
// 01:30 UTC on January 15, 2017.
static Object toProto3JsonHelper(
GeneratedMessage message, TypeRegistry typeRegistry) {
- TimestampMixin timestamp = message as TimestampMixin;
- DateTime dateTime = timestamp.toDateTime();
+ var timestamp = message as TimestampMixin;
+ var dateTime = timestamp.toDateTime();
if (timestamp.nanos < 0) {
throw ArgumentError(
@@ -210,31 +209,31 @@
// Because [DateTime] doesn't have nano-second precision, we cannot use
// dateTime.toIso8601String().
- String y = '${dateTime.year}'.padLeft(4, '0');
- String m = _twoDigits(dateTime.month);
- String d = _twoDigits(dateTime.day);
- String h = _twoDigits(dateTime.hour);
- String min = _twoDigits(dateTime.minute);
- String sec = _twoDigits(dateTime.second);
- String secFrac = "";
+ var y = '${dateTime.year}'.padLeft(4, '0');
+ var m = _twoDigits(dateTime.month);
+ var d = _twoDigits(dateTime.day);
+ var h = _twoDigits(dateTime.hour);
+ var min = _twoDigits(dateTime.minute);
+ var sec = _twoDigits(dateTime.second);
+ var secFrac = '';
if (timestamp.nanos > 0) {
- secFrac = "." +
+ secFrac = '.' +
timestamp.nanos
.toString()
- .padLeft(9, "0")
+ .padLeft(9, '0')
.replaceFirst(finalGroupsOfThreeZeroes, '');
}
- return "$y-$m-${d}T$h:$min:$sec${secFrac}Z";
+ return '$y-$m-${d}T$h:$min:$sec${secFrac}Z';
}
static void fromProto3JsonHelper(GeneratedMessage message, Object json,
TypeRegistry typeRegistry, JsonParsingContext context) {
if (json is String) {
- String jsonWithoutFracSec = json;
- int nanos = 0;
+ var jsonWithoutFracSec = json;
+ var nanos = 0;
Match fracSecsMatch = RegExp(r'\.(\d+)').firstMatch(json);
if (fracSecsMatch != null) {
- String fracSecs = fracSecsMatch[1];
+ var fracSecs = fracSecsMatch[1];
if (fracSecs.length > 9) {
throw context.parseException(
'Timestamp can have at most than 9 decimal digits', json);
@@ -243,12 +242,12 @@
jsonWithoutFracSec =
json.replaceRange(fracSecsMatch.start, fracSecsMatch.end, '');
}
- DateTime dateTimeWithoutFractionalSeconds =
+ var dateTimeWithoutFractionalSeconds =
DateTime.tryParse(jsonWithoutFracSec) ??
(throw context.parseException(
'Timestamp not well formatted. ', json));
- TimestampMixin timestamp = message as TimestampMixin;
+ var timestamp = message as TimestampMixin;
setFromDateTime(timestamp, dateTimeWithoutFractionalSeconds);
timestamp.nanos = nanos;
} else {
@@ -269,33 +268,33 @@
static Object toProto3JsonHelper(
GeneratedMessage message, TypeRegistry typeRegistry) {
- DurationMixin duration = message as DurationMixin;
- String secFrac = duration.nanos
+ var duration = message as DurationMixin;
+ var secFrac = duration.nanos
// nanos and seconds should always have the same sign.
.abs()
.toString()
.padLeft(9, '0')
.replaceFirst(finalZeroes, '');
- String secPart = secFrac == '' ? '' : '.$secFrac';
- return "${duration.seconds}${secPart}s";
+ var secPart = secFrac == '' ? '' : '.$secFrac';
+ return '${duration.seconds}${secPart}s';
}
static final RegExp durationPattern = RegExp(r'(-?\d*)(?:\.(\d*))?s$');
static void fromProto3JsonHelper(GeneratedMessage message, Object json,
TypeRegistry typeRegistry, JsonParsingContext context) {
- DurationMixin duration = message as DurationMixin;
+ var duration = message as DurationMixin;
if (json is String) {
- Match match = durationPattern.matchAsPrefix(json);
+ var match = durationPattern.matchAsPrefix(json);
if (match == null) {
throw context.parseException(
'Expected a String of the form `<seconds>.<nanos>s`', json);
} else {
- String secondsString = match[1];
- Int64 seconds =
+ var secondsString = match[1];
+ var seconds =
secondsString == '' ? Int64.ZERO : Int64.parseInt(secondsString);
duration.seconds = seconds;
- int nanos = int.parse((match[2] ?? '').padRight(9, '0'));
+ var nanos = int.parse((match[2] ?? '').padRight(9, '0'));
duration.nanos = seconds < 0 ? -nanos : nanos;
}
} else {
@@ -313,7 +312,7 @@
// The JSON representation for `Struct` is JSON object.
static Object toProto3JsonHelper(
GeneratedMessage message, TypeRegistry typeRegistry) {
- StructMixin struct = message as StructMixin;
+ var struct = message as StructMixin;
return struct.fields.map((key, value) =>
MapEntry(key, ValueMixin.toProto3JsonHelper(value, typeRegistry)));
}
@@ -324,8 +323,8 @@
// Check for emptiness to avoid setting `.fields` if there are no
// values.
if (json.isNotEmpty) {
- Map<String, ValueMixin> fields = (message as StructMixin).fields;
- GeneratedMessage Function() valueCreator =
+ var fields = (message as StructMixin).fields;
+ var valueCreator =
(message.info_.fieldInfo[_fieldsFieldTagNumber] as MapFieldInfo)
.valueCreator;
@@ -371,7 +370,7 @@
// The JSON representation for `Value` is JSON value
static Object toProto3JsonHelper(
GeneratedMessage message, TypeRegistry typeRegistry) {
- ValueMixin value = message as ValueMixin;
+ var value = message as ValueMixin;
// This would ideally be a switch, but we cannot import the enum we are
// switching over.
if (value.hasNullValue()) {
@@ -393,7 +392,7 @@
static void fromProto3JsonHelper(GeneratedMessage message, Object json,
TypeRegistry typeRegistry, JsonParsingContext context) {
- ValueMixin value = message as ValueMixin;
+ var value = message as ValueMixin;
if (json == null) {
// Rely on the getter retrieving the default to provide an instance.
value.nullValue = value.nullValue;
@@ -430,7 +429,7 @@
// The JSON representation for `ListValue` is JSON array.
static Object toProto3JsonHelper(
GeneratedMessage message, TypeRegistry typeRegistry) {
- ListValueMixin list = message as ListValueMixin;
+ var list = message as ListValueMixin;
return list.values
.map((value) => ValueMixin.toProto3JsonHelper(value, typeRegistry))
.toList();
@@ -440,11 +439,10 @@
static void fromProto3JsonHelper(GeneratedMessage message, Object json,
TypeRegistry typeRegistry, JsonParsingContext context) {
- ListValueMixin list = message as ListValueMixin;
+ var list = message as ListValueMixin;
if (json is List) {
- CreateBuilderFunc subBuilder =
- message.info_.subBuilder(_valueFieldTagNumber);
- for (int i = 0; i < json.length; i++) {
+ var subBuilder = message.info_.subBuilder(_valueFieldTagNumber);
+ for (var i = 0; i < json.length; i++) {
Object element = json[i];
ValueMixin v = subBuilder();
context.addListIndex(i);
@@ -469,8 +467,8 @@
// to/from lower-camel naming conventions.
static Object toProto3JsonHelper(
GeneratedMessage message, TypeRegistry typeRegistry) {
- FieldMaskMixin fieldMask = message as FieldMaskMixin;
- for (String path in fieldMask.paths) {
+ var fieldMask = message as FieldMaskMixin;
+ for (var path in fieldMask.paths) {
if (path.contains(RegExp('[A-Z]|_[^a-z]'))) {
throw ArgumentError(
'Bad fieldmask $path. Does not round-trip to json.');
diff --git a/protobuf/lib/src/protobuf/pb_list.dart b/protobuf/lib/src/protobuf/pb_list.dart
index fcd0569..bc26f1b 100644
--- a/protobuf/lib/src/protobuf/pb_list.dart
+++ b/protobuf/lib/src/protobuf/pb_list.dart
@@ -4,7 +4,7 @@
part of protobuf;
-typedef void CheckFunc<E>(E x);
+typedef CheckFunc<E> = void Function(E x);
class FrozenPbList<E> extends PbListBase<E> {
FrozenPbList._(List<E> wrappedList) : super._(wrappedList);
@@ -13,39 +13,58 @@
FrozenPbList._(other._wrappedList);
UnsupportedError _unsupported(String method) =>
- UnsupportedError("Cannot call $method on an unmodifiable list");
+ UnsupportedError('Cannot call $method on an unmodifiable list');
- void operator []=(int index, E value) => throw _unsupported("set");
- set length(int newLength) => throw _unsupported("set length");
- void setAll(int at, Iterable<E> iterable) => throw _unsupported("setAll");
- void add(E value) => throw _unsupported("add");
- void addAll(Iterable<E> iterable) => throw _unsupported("addAll");
- void insert(int index, E element) => throw _unsupported("insert");
+ @override
+ void operator []=(int index, E value) => throw _unsupported('set');
+ @override
+ set length(int newLength) => throw _unsupported('set length');
+ @override
+ void setAll(int at, Iterable<E> iterable) => throw _unsupported('setAll');
+ @override
+ void add(E value) => throw _unsupported('add');
+ @override
+ void addAll(Iterable<E> iterable) => throw _unsupported('addAll');
+ @override
+ void insert(int index, E element) => throw _unsupported('insert');
+ @override
void insertAll(int at, Iterable<E> iterable) =>
- throw _unsupported("insertAll");
- bool remove(Object element) => throw _unsupported("remove");
- void removeWhere(bool test(E element)) => throw _unsupported("removeWhere");
- void retainWhere(bool test(E element)) => throw _unsupported("retainWhere");
- void sort([Comparator<E> compare]) => throw _unsupported("sort");
- void shuffle([math.Random random]) => throw _unsupported("shuffle");
- void clear() => throw _unsupported("clear");
- E removeAt(int index) => throw _unsupported("removeAt");
- E removeLast() => throw _unsupported("removeLast");
+ throw _unsupported('insertAll');
+ @override
+ bool remove(Object element) => throw _unsupported('remove');
+ @override
+ void removeWhere(bool Function(E element) test) =>
+ throw _unsupported('removeWhere');
+ @override
+ void retainWhere(bool Function(E element) test) =>
+ throw _unsupported('retainWhere');
+ @override
+ void sort([Comparator<E> compare]) => throw _unsupported('sort');
+ @override
+ void shuffle([math.Random random]) => throw _unsupported('shuffle');
+ @override
+ void clear() => throw _unsupported('clear');
+ @override
+ E removeAt(int index) => throw _unsupported('removeAt');
+ @override
+ E removeLast() => throw _unsupported('removeLast');
+ @override
void setRange(int start, int end, Iterable<E> iterable,
[int skipCount = 0]) =>
- throw _unsupported("setRange");
- void removeRange(int start, int end) => throw _unsupported("removeRange");
+ throw _unsupported('setRange');
+ @override
+ void removeRange(int start, int end) => throw _unsupported('removeRange');
+ @override
void replaceRange(int start, int end, Iterable<E> iterable) =>
- throw _unsupported("replaceRange");
+ throw _unsupported('replaceRange');
+ @override
void fillRange(int start, int end, [E fillValue]) =>
- throw _unsupported("fillRange");
+ throw _unsupported('fillRange');
}
class PbList<E> extends PbListBase<E> {
PbList({check = _checkNotNull}) : super._noList(check: check);
- PbList._(List<E> wrappedList) : super._(wrappedList);
-
PbList.from(List from) : super._from(from);
@Deprecated('Instead use the default constructor with a check function.'
@@ -58,6 +77,7 @@
/// Adds [value] at the end of the list, extending the length by one.
/// Throws an [UnsupportedError] if the list is not extendable.
+ @override
void add(E value) {
check(value);
_wrappedList.add(value);
@@ -66,26 +86,32 @@
/// Appends all elements of the [collection] to the end of list.
/// Extends the length of the list by the length of [collection].
/// Throws an [UnsupportedError] if the list is not extendable.
+ @override
void addAll(Iterable<E> collection) {
collection.forEach(check);
_wrappedList.addAll(collection);
}
/// Returns an [Iterable] of the objects in this list in reverse order.
+ @override
Iterable<E> get reversed => _wrappedList.reversed;
/// Sorts this list according to the order specified by the [compare]
/// function.
- void sort([int compare(E a, E b)]) => _wrappedList.sort(compare);
+ @override
+ void sort([int Function(E a, E b) compare]) => _wrappedList.sort(compare);
/// Shuffles the elements of this list randomly.
+ @override
void shuffle([math.Random random]) => _wrappedList.shuffle(random);
/// Removes all objects from this list; the length of the list becomes zero.
+ @override
void clear() => _wrappedList.clear();
/// Inserts a new element in the list.
/// The element must be valid (and not nullable) for the PbList type.
+ @override
void insert(int index, E element) {
check(element);
_wrappedList.insert(index, element);
@@ -94,6 +120,7 @@
/// Inserts all elements of [iterable] at position [index] in the list.
///
/// Elements in [iterable] must be valid and not nullable for the PbList type.
+ @override
void insertAll(int index, Iterable<E> iterable) {
iterable.forEach(check);
_wrappedList.insertAll(index, iterable);
@@ -103,29 +130,38 @@
/// position [index] in the list.
///
/// Elements in [iterable] must be valid and not nullable for the PbList type.
+ @override
void setAll(int index, Iterable<E> iterable) {
iterable.forEach(check);
_wrappedList.setAll(index, iterable);
}
/// Removes the first occurrence of [value] from this list.
+ @override
bool remove(Object value) => _wrappedList.remove(value);
/// Removes the object at position [index] from this list.
+ @override
E removeAt(int index) => _wrappedList.removeAt(index);
/// Pops and returns the last object in this list.
+ @override
E removeLast() => _wrappedList.removeLast();
/// Removes all objects from this list that satisfy [test].
- void removeWhere(bool test(E element)) => _wrappedList.removeWhere(test);
+ @override
+ void removeWhere(bool Function(E element) test) =>
+ _wrappedList.removeWhere(test);
/// Removes all objects from this list that fail to satisfy [test].
- void retainWhere(bool test(E element)) => _wrappedList.retainWhere(test);
+ @override
+ void retainWhere(bool Function(E element) test) =>
+ _wrappedList.retainWhere(test);
/// Copies [:end - start:] elements of the [from] array, starting from
/// [skipCount], into [:this:], starting at [start].
/// Throws an [UnsupportedError] if the list is not extendable.
+ @override
void setRange(int start, int end, Iterable<E> from, [int skipCount = 0]) {
// NOTE: In case `take()` returns less than `end - start` elements, the
// _wrappedList will fail with a `StateError`.
@@ -134,10 +170,12 @@
}
/// Removes the objects in the range [start] inclusive to [end] exclusive.
+ @override
void removeRange(int start, int end) => _wrappedList.removeRange(start, end);
/// Sets the objects in the range [start] inclusive to [end] exclusive to the
/// given [fillValue].
+ @override
void fillRange(int start, int end, [E fillValue]) {
check(fillValue);
_wrappedList.fillRange(start, end, fillValue);
@@ -145,6 +183,7 @@
/// Removes the objects in the range [start] inclusive to [end] exclusive and
/// inserts the contents of [replacement] in its place.
+ @override
void replaceRange(int start, int end, Iterable<E> replacement) {
final values = replacement.toList();
replacement.forEach(check);
@@ -175,86 +214,114 @@
int get hashCode => _HashUtils._hashObjects(_wrappedList);
/// Returns an [Iterator] for the list.
+ @override
Iterator<E> get iterator => _wrappedList.iterator;
/// Returns a new lazy [Iterable] with elements that are created by calling
/// `f` on each element of this `PbListBase` in iteration order.
- Iterable<T> map<T>(T f(E e)) => _wrappedList.map<T>(f);
+ @override
+ Iterable<T> map<T>(T Function(E e) f) => _wrappedList.map<T>(f);
/// Returns a new lazy [Iterable] with all elements that satisfy the predicate
/// [test].
- Iterable<E> where(bool test(E element)) => _wrappedList.where(test);
+ @override
+ Iterable<E> where(bool Function(E element) test) => _wrappedList.where(test);
/// Expands each element of this [Iterable] into zero or more elements.
- Iterable<T> expand<T>(Iterable<T> f(E element)) => _wrappedList.expand(f);
+ @override
+ Iterable<T> expand<T>(Iterable<T> Function(E element) f) =>
+ _wrappedList.expand(f);
/// Returns true if the collection contains an element equal to [element].
+ @override
bool contains(Object element) => _wrappedList.contains(element);
/// Applies the function [f] to each element of this list in iteration order.
- void forEach(void f(E element)) {
+ @override
+ void forEach(void Function(E element) f) {
_wrappedList.forEach(f);
}
/// Reduces a collection to a single value by iteratively combining elements
/// of the collection using the provided function.
- E reduce(E combine(E value, E element)) => _wrappedList.reduce(combine);
+ @override
+ E reduce(E Function(E value, E element) combine) =>
+ _wrappedList.reduce(combine);
/// Reduces a collection to a single value by iteratively combining each
/// element of the collection with an existing value.
- T fold<T>(T initialValue, T combine(T previousValue, E element)) =>
+ @override
+ T fold<T>(T initialValue, T Function(T previousValue, E element) combine) =>
_wrappedList.fold(initialValue, combine);
/// Checks whether every element of this iterable satisfies [test].
- bool every(bool test(E element)) => _wrappedList.every(test);
+ @override
+ bool every(bool Function(E element) test) => _wrappedList.every(test);
/// Converts each element to a [String] and concatenates the strings.
- String join([String separator = ""]) => _wrappedList.join(separator);
+ @override
+ String join([String separator = '']) => _wrappedList.join(separator);
/// Checks whether any element of this iterable satisfies [test].
- bool any(bool test(E element)) => _wrappedList.any(test);
+ @override
+ bool any(bool Function(E element) test) => _wrappedList.any(test);
/// Creates a [List] containing the elements of this [Iterable].
+ @override
List<E> toList({bool growable = true}) =>
_wrappedList.toList(growable: growable);
/// Creates a [Set] containing the same elements as this iterable.
+ @override
Set<E> toSet() => _wrappedList.toSet();
/// Returns `true` if there are no elements in this collection.
+ @override
bool get isEmpty => _wrappedList.isEmpty;
/// Returns `true` if there is at least one element in this collection.
+ @override
bool get isNotEmpty => _wrappedList.isNotEmpty;
/// Returns a lazy iterable of the [count] first elements of this iterable.
+ @override
Iterable<E> take(int count) => _wrappedList.take(count);
/// Returns a lazy iterable of the leading elements satisfying [test].
- Iterable<E> takeWhile(bool test(E value)) => _wrappedList.takeWhile(test);
+ @override
+ Iterable<E> takeWhile(bool Function(E value) test) =>
+ _wrappedList.takeWhile(test);
/// Returns an [Iterable] that provides all but the first [count] elements.
+ @override
Iterable<E> skip(int count) => _wrappedList.skip(count);
/// Returns an `Iterable` that skips leading elements while [test] is
/// satisfied.
- Iterable<E> skipWhile(bool test(E value)) => _wrappedList.skipWhile(test);
+ @override
+ Iterable<E> skipWhile(bool Function(E value) test) =>
+ _wrappedList.skipWhile(test);
/// Returns the first element.
+ @override
E get first => _wrappedList.first;
/// Returns the last element.
+ @override
E get last => _wrappedList.last;
/// Checks that this iterable has only one element, and returns that element.
+ @override
E get single => _wrappedList.single;
/// Returns the first element that satisfies the given predicate [test].
- E firstWhere(bool test(E element), {E orElse()}) =>
+ @override
+ E firstWhere(bool Function(E element) test, {E Function() orElse}) =>
_wrappedList.firstWhere(test, orElse: orElse);
/// Returns the last element that satisfies the given predicate [test].
- E lastWhere(bool test(E element), {E orElse()}) =>
+ @override
+ E lastWhere(bool Function(E element) test, {E Function() orElse}) =>
_wrappedList.lastWhere(test, orElse: orElse);
/// Returns the single element that satisfies [test].
@@ -263,9 +330,11 @@
// _wrappedList.singleWhere(test, orElse: orElse);
/// Returns the [index]th element.
+ @override
E elementAt(int index) => _wrappedList.elementAt(index);
/// Returns a string representation of (some of) the elements of `this`.
+ @override
String toString() => _wrappedList.toString();
/// Returns the element at the given [index] in the list or throws an
@@ -274,27 +343,33 @@
E operator [](int index) => _wrappedList[index];
/// Returns the number of elements in this collection.
+ @override
int get length => _wrappedList.length;
// TODO(jakobr): E instead of Object once dart-lang/sdk#31311 is fixed.
/// Returns the first index of [element] in this list.
+ @override
int indexOf(Object element, [int start = 0]) =>
_wrappedList.indexOf(element, start);
// TODO(jakobr): E instead of Object once dart-lang/sdk#31311 is fixed.
/// Returns the last index of [element] in this list.
+ @override
int lastIndexOf(Object element, [int start]) =>
_wrappedList.lastIndexOf(element, start);
/// Returns a new list containing the objects from [start] inclusive to [end]
/// exclusive.
+ @override
List<E> sublist(int start, [int end]) => _wrappedList.sublist(start, end);
/// Returns an [Iterable] that iterates over the objects in the range [start]
/// inclusive to [end] exclusive.
+ @override
Iterable<E> getRange(int start, int end) => _wrappedList.getRange(start, end);
/// Returns an unmodifiable [Map] view of `this`.
+ @override
Map<int, E> asMap() => _wrappedList.asMap();
/// Sets the entry at the given [index] in the list to [value].
@@ -310,6 +385,7 @@
/// Changes the length of the list. If [newLength] is greater than the current
/// [length], entries are initialized to [:null:]. Throws an
/// [UnsupportedError] if the list is not extendable.
+ @override
set length(int newLength) {
if (newLength > length) {
throw UnsupportedError('Extending protobuf lists is not supported');
diff --git a/protobuf/lib/src/protobuf/pb_map.dart b/protobuf/lib/src/protobuf/pb_map.dart
index e7b02ee..a89713a 100644
--- a/protobuf/lib/src/protobuf/pb_map.dart
+++ b/protobuf/lib/src/protobuf/pb_map.dart
@@ -93,22 +93,22 @@
return _wrappedMap.remove(key);
}
- @Deprecated("This function was not intended to be public. "
- "It will be removed from the public api in next major version. ")
+ @Deprecated('This function was not intended to be public. '
+ 'It will be removed from the public api in next major version. ')
void add(CodedBufferReader input, [ExtensionRegistry registry]) {
_mergeEntry(input, registry);
}
void _mergeEntry(CodedBufferReader input, [ExtensionRegistry registry]) {
- int length = input.readInt32();
- int oldLimit = input._currentLimit;
+ var length = input.readInt32();
+ var oldLimit = input._currentLimit;
input._currentLimit = input._bufferPos + length;
- _FieldSet entryFieldSet = _entryFieldSet();
+ var entryFieldSet = _entryFieldSet();
_mergeFromCodedBufferReader(entryFieldSet, input, registry);
input.checkLastTagWas(0);
input._currentLimit = oldLimit;
- K key = entryFieldSet._$get(0, null);
- V value = entryFieldSet._$get(1, null);
+ var key = entryFieldSet._$get<K>(0, null);
+ var value = entryFieldSet._$get<V>(1, null);
_wrappedMap[key] = value;
}
diff --git a/protobuf/lib/src/protobuf/permissive_compare.dart b/protobuf/lib/src/protobuf/permissive_compare.dart
index e31103a..7b197ec 100644
--- a/protobuf/lib/src/protobuf/permissive_compare.dart
+++ b/protobuf/lib/src/protobuf/permissive_compare.dart
@@ -11,8 +11,8 @@
const dash = 45;
const underscore = 95;
- int i = 0;
- int j = 0;
+ var i = 0;
+ var j = 0;
while (true) {
int ca, cb;
diff --git a/protobuf/lib/src/protobuf/proto3_json.dart b/protobuf/lib/src/protobuf/proto3_json.dart
index bf76d56..f0a03b2 100644
--- a/protobuf/lib/src/protobuf/proto3_json.dart
+++ b/protobuf/lib/src/protobuf/proto3_json.dart
@@ -6,7 +6,7 @@
Object _writeToProto3Json(_FieldSet fs, TypeRegistry typeRegistry) {
String convertToMapKey(dynamic key, int keyType) {
- int baseType = PbFieldType._baseType(keyType);
+ var baseType = PbFieldType._baseType(keyType);
assert(!_isRepeated(keyType));
@@ -41,7 +41,7 @@
} else if (_isEnum(fieldType)) {
return (fieldValue as ProtobufEnum).name;
} else {
- int baseType = PbFieldType._baseType(fieldType);
+ var baseType = PbFieldType._baseType(fieldType);
switch (baseType) {
case PbFieldType._BOOL_BIT:
return fieldValue ? true : false;
@@ -85,8 +85,8 @@
return fs._meta.toProto3Json(fs._message, typeRegistry);
}
- Map<String, dynamic> result = <String, dynamic>{};
- for (FieldInfo fieldInfo in fs._infosSortedByTag) {
+ var result = <String, dynamic>{};
+ for (var fieldInfo in fs._infosSortedByTag) {
var value = fs._values[fieldInfo.index];
if (value == null || (value is List && value.isEmpty)) {
continue; // It's missing, repeated, or an empty byte array.
@@ -94,7 +94,7 @@
dynamic jsonValue;
if (fieldInfo.isMapField) {
jsonValue = (value as PbMap).map((key, entryValue) {
- MapFieldInfo mapEntryInfo = fieldInfo as MapFieldInfo;
+ var mapEntryInfo = fieldInfo as MapFieldInfo;
return MapEntry(convertToMapKey(key, mapEntryInfo.keyFieldType),
valueToProto3Json(entryValue, mapEntryInfo.valueFieldType));
});
@@ -118,7 +118,7 @@
bool ignoreUnknownFields,
bool supportNamesWithUnderscores,
bool permissiveEnums) {
- JsonParsingContext context = JsonParsingContext(
+ var context = JsonParsingContext(
ignoreUnknownFields, supportNamesWithUnderscores, permissiveEnums);
void recursionHelper(Object json, _FieldSet fieldSet) {
@@ -155,7 +155,7 @@
if (value == null) {
return fieldInfo.makeDefault();
}
- int fieldType = fieldInfo.type;
+ var fieldType = fieldInfo.type;
switch (PbFieldType._baseType(fieldType)) {
case PbFieldType._BOOL_BIT:
if (value is bool) {
@@ -266,7 +266,7 @@
'Expected int or stringified int', value);
case PbFieldType._GROUP_BIT:
case PbFieldType._MESSAGE_BIT:
- GeneratedMessage subMessage = fieldInfo.subBuilder();
+ var subMessage = fieldInfo.subBuilder();
recursionHelper(value, subMessage._fieldSet);
return subMessage;
default:
@@ -316,14 +316,14 @@
return;
}
- BuilderInfo info = fieldSet._meta;
+ var info = fieldSet._meta;
final wellKnownConverter = info.fromProto3Json;
if (wellKnownConverter != null) {
wellKnownConverter(fieldSet._message, json, typeRegistry, context);
} else {
if (json is Map) {
- Map<String, FieldInfo> byName = info.byName;
+ var byName = info.byName;
json.forEach((key, value) {
if (key is! String) {
@@ -331,7 +331,7 @@
}
context.addMapIndex(key);
- FieldInfo fieldInfo = byName[key];
+ var fieldInfo = byName[key];
if (fieldInfo == null && supportNamesWithUnderscores) {
// We don't optimize for field names with underscores, instead do a
// linear search for the index.
@@ -371,8 +371,8 @@
// `null` is accepted as the empty list [].
fieldSet._ensureRepeatedField(fieldInfo);
} else if (value is List) {
- List values = fieldSet._ensureRepeatedField(fieldInfo);
- for (int i = 0; i < value.length; i++) {
+ var values = fieldSet._ensureRepeatedField(fieldInfo);
+ for (var i = 0; i < value.length; i++) {
final entry = value[i];
context.addListIndex(i);
values.add(convertProto3JsonValue(entry, fieldInfo));
diff --git a/protobuf/lib/src/protobuf/protobuf_enum.dart b/protobuf/lib/src/protobuf/protobuf_enum.dart
index b020595..8b1b19d 100644
--- a/protobuf/lib/src/protobuf/protobuf_enum.dart
+++ b/protobuf/lib/src/protobuf/protobuf_enum.dart
@@ -38,8 +38,8 @@
/// Returns a Map for all of the [ProtobufEnum]s in [byIndex], mapping each
/// [ProtobufEnum]'s [value] to the [ProtobufEnum].
static Map<int, T> initByValue<T extends ProtobufEnum>(List<T> byIndex) {
- var byValue = Map<int, T>();
- for (T v in byIndex) {
+ var byValue = <int, T>{};
+ for (var v in byIndex) {
byValue[v.value] = v;
}
return byValue;
@@ -48,10 +48,13 @@
// Subclasses will typically have a private constructor and a fixed set of
// instances, so `Object.operator==()` will work, and does not need to
// be overridden explicitly.
+ @override
bool operator ==(Object o);
+ @override
int get hashCode => value;
/// Returns this enum's [name].
+ @override
String toString() => name;
}
diff --git a/protobuf/lib/src/protobuf/readonly_message.dart b/protobuf/lib/src/protobuf/readonly_message.dart
index d78ccd6..794f762 100644
--- a/protobuf/lib/src/protobuf/readonly_message.dart
+++ b/protobuf/lib/src/protobuf/readonly_message.dart
@@ -9,49 +9,49 @@
BuilderInfo get info_;
void addExtension(Extension extension, var value) =>
- _readonly("addExtension");
+ _readonly('addExtension');
- void clear() => _readonly("clear");
+ void clear() => _readonly('clear');
- void clearExtension(Extension extension) => _readonly("clearExtension");
+ void clearExtension(Extension extension) => _readonly('clearExtension');
- void clearField(int tagNumber) => _readonly("clearField");
+ void clearField(int tagNumber) => _readonly('clearField');
List<T> createRepeatedField<T>(int tagNumber, FieldInfo<T> fi) {
- _readonly("createRepeatedField");
+ _readonly('createRepeatedField');
return null; // not reached
}
void mergeFromBuffer(List<int> input,
[ExtensionRegistry extensionRegistry = ExtensionRegistry.EMPTY]) =>
- _readonly("mergeFromBuffer");
+ _readonly('mergeFromBuffer');
void mergeFromCodedBufferReader(CodedBufferReader input,
[ExtensionRegistry extensionRegistry = ExtensionRegistry.EMPTY]) =>
- _readonly("mergeFromCodedBufferReader");
+ _readonly('mergeFromCodedBufferReader');
void mergeFromJson(String data,
[ExtensionRegistry extensionRegistry = ExtensionRegistry.EMPTY]) =>
- _readonly("mergeFromJson");
+ _readonly('mergeFromJson');
void mergeFromJsonMap(Map<String, dynamic> json,
[ExtensionRegistry extensionRegistry = ExtensionRegistry.EMPTY]) =>
- _readonly("mergeFromJsonMap");
+ _readonly('mergeFromJsonMap');
void mergeFromMessage(GeneratedMessage other) =>
- _readonly("mergeFromMessage");
+ _readonly('mergeFromMessage');
void mergeUnknownFields(UnknownFieldSet unknownFieldSet) =>
- _readonly("mergeUnknownFields");
+ _readonly('mergeUnknownFields');
void setExtension(Extension extension, var value) =>
- _readonly("setExtension");
+ _readonly('setExtension');
void setField(int tagNumber, var value, [int fieldType]) =>
- _readonly("setField");
+ _readonly('setField');
void _readonly(String methodName) {
- String messageType = info_.qualifiedMessageName;
+ var messageType = info_.qualifiedMessageName;
frozenMessageModificationHandler(messageType, methodName);
}
}
diff --git a/protobuf/lib/src/protobuf/unknown_field_set.dart b/protobuf/lib/src/protobuf/unknown_field_set.dart
index a136f36..92ffdf4 100644
--- a/protobuf/lib/src/protobuf/unknown_field_set.dart
+++ b/protobuf/lib/src/protobuf/unknown_field_set.dart
@@ -7,8 +7,7 @@
class UnknownFieldSet {
static final UnknownFieldSet emptyUnknownFieldSet = UnknownFieldSet()
.._markReadOnly();
- final Map<int, UnknownFieldSetField> _fields =
- Map<int, UnknownFieldSetField>();
+ final Map<int, UnknownFieldSetField> _fields = <int, UnknownFieldSetField>{};
UnknownFieldSet();
@@ -51,7 +50,7 @@
bool mergeFieldFromBuffer(int tag, CodedBufferReader input) {
_ensureWritable('mergeFieldFromBuffer');
- int number = getTagFieldNumber(tag);
+ var number = getTagFieldNumber(tag);
switch (getTagWireType(tag)) {
case WIRETYPE_VARINT:
mergeVarintField(number, input.readInt64());
@@ -63,7 +62,7 @@
mergeLengthDelimitedField(number, input.readBytes());
return true;
case WIRETYPE_START_GROUP:
- UnknownFieldSet subGroup = input.readUnknownFieldSetGroup(number);
+ var subGroup = input.readUnknownFieldSetGroup(number);
mergeGroupField(number, subGroup);
return true;
case WIRETYPE_END_GROUP:
@@ -79,7 +78,7 @@
void mergeFromCodedBufferReader(CodedBufferReader input) {
_ensureWritable('mergeFromCodedBufferReader');
while (true) {
- int tag = input.readTag();
+ var tag = input.readTag();
if (tag == 0 || !mergeFieldFromBuffer(tag, input)) {
break;
}
@@ -88,12 +87,12 @@
void mergeFromUnknownFieldSet(UnknownFieldSet other) {
_ensureWritable('mergeFromUnknownFieldSet');
- for (int key in other._fields.keys) {
+ for (var key in other._fields.keys) {
mergeField(key, other._fields[key]);
}
}
- _checkFieldNumber(int number) {
+ void _checkFieldNumber(int number) {
if (number == 0) {
throw ArgumentError('Zero is not a valid field number.');
}
@@ -130,6 +129,7 @@
return _fields.putIfAbsent(number, () => UnknownFieldSetField());
}
+ @override
bool operator ==(other) {
if (other is! UnknownFieldSet) return false;
@@ -137,8 +137,9 @@
return _areMapsEqual(o._fields, _fields);
}
+ @override
int get hashCode {
- int hash = 0;
+ var hash = 0;
_fields.forEach((int number, Object value) {
hash = 0x1fffffff & ((37 * hash) + number);
hash = 0x1fffffff & ((53 * hash) + value.hashCode);
@@ -146,12 +147,13 @@
return hash;
}
+ @override
String toString() => _toString('');
String _toString(String indent) {
var stringBuffer = StringBuffer();
- for (int tag in _sorted(_fields.keys)) {
+ for (var tag in _sorted(_fields.keys)) {
var field = _fields[tag];
for (var value in field.values) {
if (value is UnknownFieldSet) {
@@ -173,7 +175,7 @@
}
void writeToCodedBufferWriter(CodedBufferWriter output) {
- for (int key in _fields.keys) {
+ for (var key in _fields.keys) {
_fields[key].writeTo(key, output);
}
}
@@ -216,12 +218,13 @@
_groups = List.unmodifiable(_groups);
}
+ @override
bool operator ==(other) {
if (other is! UnknownFieldSetField) return false;
UnknownFieldSetField o = other;
if (lengthDelimited.length != o.lengthDelimited.length) return false;
- for (int i = 0; i < lengthDelimited.length; i++) {
+ for (var i = 0; i < lengthDelimited.length; i++) {
if (!_areListsEqual(o.lengthDelimited[i], lengthDelimited[i])) {
return false;
}
@@ -234,10 +237,11 @@
return true;
}
+ @override
int get hashCode {
- int hash = 0;
+ var hash = 0;
for (final value in lengthDelimited) {
- for (int i = 0; i < value.length; i++) {
+ for (var i = 0; i < value.length; i++) {
hash = 0x1fffffff & (hash + value[i]);
hash = 0x1fffffff & (hash + ((0x0007ffff & hash) << 10));
hash = hash ^ (hash >> 6);
@@ -269,7 +273,7 @@
..addAll(groups);
void writeTo(int fieldNumber, CodedBufferWriter output) {
- write(type, value) {
+ void write(type, value) {
output.writeField(fieldNumber, type, value);
}
diff --git a/protobuf/lib/src/protobuf/unpack.dart b/protobuf/lib/src/protobuf/unpack.dart
index 6ff9292..3ddbaa5 100644
--- a/protobuf/lib/src/protobuf/unpack.dart
+++ b/protobuf/lib/src/protobuf/unpack.dart
@@ -21,7 +21,7 @@
// in the type URL, for example "foo.bar.com/x/y.z" will yield type
// name "y.z".
if (!canUnpackIntoHelper(instance, typeUrl)) {
- String typeName = instance.info_.qualifiedMessageName;
+ var typeName = instance.info_.qualifiedMessageName;
throw InvalidProtocolBufferException.wrongAnyMessage(
_typeNameFromUrl(typeUrl), typeName);
}
@@ -37,6 +37,6 @@
}
String _typeNameFromUrl(String typeUrl) {
- int index = typeUrl.lastIndexOf('/');
+ var index = typeUrl.lastIndexOf('/');
return index == -1 ? '' : typeUrl.substring(index + 1);
}
diff --git a/protobuf/lib/src/protobuf/utils.dart b/protobuf/lib/src/protobuf/utils.dart
index d2af1fb..0c7e4e5 100644
--- a/protobuf/lib/src/protobuf/utils.dart
+++ b/protobuf/lib/src/protobuf/utils.dart
@@ -31,12 +31,13 @@
}
bool _areByteDataEqual(ByteData lhs, ByteData rhs) {
- asBytes(d) => Uint8List.view(d.buffer, d.offsetInBytes, d.lengthInBytes);
+ Uint8List asBytes(d) =>
+ Uint8List.view(d.buffer, d.offsetInBytes, d.lengthInBytes);
return _areListsEqual(asBytes(lhs), asBytes(rhs));
}
-@Deprecated("This function was not intended to be public. "
- "It will be removed from the public api in next major version. ")
+@Deprecated('This function was not intended to be public. '
+ 'It will be removed from the public api in next major version. ')
List<T> sorted<T>(Iterable<T> list) => List.from(list)..sort();
List<T> _sorted<T>(Iterable<T> list) => List.from(list)..sort();
diff --git a/protobuf/test/builder_info_test.dart b/protobuf/test/builder_info_test.dart
index 0d722b5..d3356cb 100644
--- a/protobuf/test/builder_info_test.dart
+++ b/protobuf/test/builder_info_test.dart
@@ -5,7 +5,7 @@
import 'package:protobuf/protobuf.dart';
import 'package:test/test.dart';
-main() {
+void main() {
group('className', () {
final qualifiedmessageName = 'proto.test.TestMessage';
final expectedMessageName = 'TestMessage';
diff --git a/protobuf/test/codec_test.dart b/protobuf/test/codec_test.dart
index 5b71aff..65d108e 100755
--- a/protobuf/test/codec_test.dart
+++ b/protobuf/test/codec_test.dart
@@ -12,18 +12,19 @@
import 'test_util.dart';
-typedef void RoundtripTester<T>(T value, List<int> bytes);
+typedef RoundtripTester<T> = void Function(T value, List<int> bytes);
void main() {
ByteData makeData(Uint8List bytes) => ByteData.view(bytes.buffer);
- convertToBytes(fieldType) => (value) {
+ Uint8List Function(dynamic) convertToBytes(fieldType) => (value) {
var writer = CodedBufferWriter()..writeField(0, fieldType, value);
return writer.toBuffer().sublist(1);
};
RoundtripTester<T> roundtripTester<T>(
- {T fromBytes(CodedBufferReader bytes), List<int> toBytes(T value)}) {
+ {T Function(CodedBufferReader bytes) fromBytes,
+ List<int> Function(T value) toBytes}) {
return (T value, List<int> bytes) {
expect(fromBytes(CodedBufferReader(bytes)), equals(value));
expect(toBytes(value), bytes);
@@ -120,7 +121,7 @@
});
test('testBool', () {
- readBool(List<int> bytes) => CodedBufferReader(bytes).readBool();
+ bool readBool(List<int> bytes) => CodedBufferReader(bytes).readBool();
expect(readBool([0x00]), isFalse);
expect(readBool([0x01]), isTrue);
@@ -129,17 +130,17 @@
// Compare two doubles, where NaNs and same-sign inifinities compare equal.
// For normal values, use equals.
- doubleEquals(expected) => expected.isNaN
+ Matcher doubleEquals(expected) => expected.isNaN
? predicate((x) => x.isNaN, 'NaN expected')
: equals(expected);
List<int> dataToBytes(ByteData byteData) => Uint8List.view(byteData.buffer);
final floatToBytes = convertToBytes(PbFieldType.OF);
- floatToBits(double value) =>
+ int floatToBits(double value) =>
makeData(floatToBytes(value)).getUint32(0, Endian.little);
void _test32(int bits, double value) {
- readFloat(int bits) {
+ double readFloat(int bits) {
var bytes = dataToBytes(ByteData(4)..setUint32(0, bits, Endian.little));
return CodedBufferReader(bytes).readFloat();
}
@@ -152,7 +153,7 @@
void _test64(List<int> hilo, double value) {
// Encode a double to its wire format.
- ByteData data = makeData(doubleToBytes(value));
+ var data = makeData(doubleToBytes(value));
var actualHilo = [
data.getUint32(4, Endian.little),
data.getUint32(0, Endian.little)
@@ -161,8 +162,8 @@
expect(actualHilo, hilo);
// Decode it again (round trip).
- List<int> bytes = dataToBytes(data);
- double reencoded = CodedBufferReader(bytes).readDouble();
+ var bytes = dataToBytes(data);
+ var reencoded = CodedBufferReader(bytes).readDouble();
expect(reencoded, doubleEquals(value));
}
diff --git a/protobuf/test/coded_buffer_reader_test.dart b/protobuf/test/coded_buffer_reader_test.dart
index 9cee2f5..2bc9994 100755
--- a/protobuf/test/coded_buffer_reader_test.dart
+++ b/protobuf/test/coded_buffer_reader_test.dart
@@ -39,7 +39,7 @@
0x65, 0x73 // 115 bytes 14 optional_bytes
]);
- testWithList(List<int> inputBuffer) {
+ void testWithList(List<int> inputBuffer) {
final cis = CodedBufferReader(inputBuffer);
expect(cis.readTag(), makeTag(103, WIRETYPE_VARINT));
@@ -103,9 +103,9 @@
});
test('testReadMaliciouslyLargeBlob', () {
- CodedBufferWriter output = CodedBufferWriter();
+ var output = CodedBufferWriter();
- int tag = makeTag(1, WIRETYPE_LENGTH_DELIMITED);
+ var tag = makeTag(1, WIRETYPE_LENGTH_DELIMITED);
output.writeInt32NoTag(tag);
output.writeInt32NoTag(0x7FFFFFFF);
// Pad with a few random bytes.
@@ -113,7 +113,7 @@
output.writeInt32NoTag(32);
output.writeInt32NoTag(47);
- CodedBufferReader input = CodedBufferReader(output.toBuffer());
+ var input = CodedBufferReader(output.toBuffer());
expect(input.readTag(), tag);
expect(() {
@@ -125,15 +125,15 @@
/// is thrown. Instead, the invalid bytes are replaced with the Unicode
/// 'replacement character' U+FFFD.
test('testReadInvalidUtf8', () {
- CodedBufferReader input = CodedBufferReader([1, 0x80]);
- String text = input.readString();
+ var input = CodedBufferReader([1, 0x80]);
+ var text = input.readString();
expect(text.codeUnitAt(0), 0xfffd);
});
test('testInvalidTag', () {
// Any tag number which corresponds to field number zero is invalid and
// should throw InvalidProtocolBufferException.
- for (int i = 0; i < 8; i++) {
+ for (var i = 0; i < 8; i++) {
expect(() {
CodedBufferReader([i]).readTag();
}, throwsInvalidProtocolBufferException);
diff --git a/protobuf/test/dummy_field_test.dart b/protobuf/test/dummy_field_test.dart
index cc142fa..3612d87 100644
--- a/protobuf/test/dummy_field_test.dart
+++ b/protobuf/test/dummy_field_test.dart
@@ -6,16 +6,18 @@
import 'package:test/test.dart';
class Message extends GeneratedMessage {
- get info_ => _i;
- static final _i = BuilderInfo("Message")
+ @override
+ BuilderInfo get info_ => _i;
+ static final _i = BuilderInfo('Message')
..add(0, null, null, null, null, null, null);
+ @override
Message createEmptyInstance() => Message();
@override
GeneratedMessage clone() => throw UnimplementedError();
}
-main() {
+void main() {
test('Has no known fields', () {
expect(Message().info_.fieldInfo, isEmpty);
});
diff --git a/protobuf/test/event_test.dart b/protobuf/test/event_test.dart
index 6216418..77c4886 100644
--- a/protobuf/test/event_test.dart
+++ b/protobuf/test/event_test.dart
@@ -5,10 +5,9 @@
/// Tests event delivery using PbEventMixin.
library event_test;
-import 'dart:typed_data' show Uint8List;
-
import 'package:protobuf/protobuf.dart'
show GeneratedMessage, Extension, ExtensionRegistry, PbFieldType;
+import 'package:protobuf/protobuf.dart';
import 'package:protobuf/src/protobuf/mixins/event_mixin.dart'
show PbEventMixin, PbFieldChange;
import 'package:test/test.dart' show test, expect;
@@ -16,14 +15,16 @@
import 'mock_util.dart' show MockMessage, mockInfo;
class Rec extends MockMessage with PbEventMixin {
- get info_ => _info;
- static final _info = mockInfo("Rec", () => Rec());
+ @override
+ BuilderInfo get info_ => _info;
+ static final _info = mockInfo('Rec', () => Rec());
+ @override
Rec createEmptyInstance() => Rec();
}
-Extension comment = Extension("Rec", "comment", 6, PbFieldType.OS);
+Extension comment = Extension('Rec', 'comment', 6, PbFieldType.OS);
-main() {
+void main() {
test('Events are sent when setting and clearing a non-repeated field', () {
var log = makeLog();
var r = Rec();
@@ -84,7 +85,7 @@
var log = makeLog();
var r = Rec()
..val = 123
- ..str = "hello"
+ ..str = 'hello'
..child = Rec()
..int32s.add(456);
@@ -99,8 +100,8 @@
checkLog(log, [
[
[1, 123, 42],
- [2, "hello", ''],
- [3, "<msg>", "<msg>"],
+ [2, 'hello', ''],
+ [3, '<msg>', '<msg>'],
[
4,
[456],
@@ -114,7 +115,7 @@
var log = makeLog();
var src = Rec()
..val = 123
- ..str = "hello"
+ ..str = 'hello'
..child = Rec()
..int32s.add(456);
@@ -129,8 +130,8 @@
checkLog(log, [
[
[1, 42, 123],
- [2, '', "hello"],
- [3, "<msg>", "<msg>"],
+ [2, '', 'hello'],
+ [3, '<msg>', '<msg>'],
[
4,
[],
@@ -155,8 +156,8 @@
checkLog(log, [
[
[1, 42, 123],
- [2, '', "hello"],
- [3, "<msg>", "<msg>"],
+ [2, '', 'hello'],
+ [3, '<msg>', '<msg>'],
[
4,
[],
@@ -169,9 +170,9 @@
test('Events are sent when merging binary', () {
var log = makeLog();
- Uint8List bytes = (Rec()
+ var bytes = (Rec()
..val = 123
- ..str = "hello"
+ ..str = 'hello'
..child = Rec()
..int32s.add(456))
.writeToBuffer();
@@ -189,8 +190,8 @@
checkLog(log, [
[
[1, 42, 123],
- [2, '', "hello"],
- [3, "<msg>", "<msg>"],
+ [2, '', 'hello'],
+ [3, '<msg>', '<msg>'],
[
4,
[],
@@ -208,58 +209,58 @@
});
final tag = comment.tagNumber;
- setComment(String value) {
+ void setComment(String value) {
r.setExtension(comment, value);
expect(r.getExtension(comment), value);
r.deliverChanges();
- checkLogOnce(log, [tag, "", value]);
+ checkLogOnce(log, [tag, '', value]);
}
- clear(String expected) {
+ void clear(String expected) {
r.clear();
r.deliverChanges();
- checkLogOnce(log, [tag, expected, ""]);
+ checkLogOnce(log, [tag, expected, '']);
}
- setComment("hello");
- clear("hello");
+ setComment('hello');
+ clear('hello');
- setComment("hello");
- r.setField(6, "hi");
+ setComment('hello');
+ r.setField(6, 'hi');
r.deliverChanges();
- checkLogOnce(log, [tag, "hello", "hi"]);
- clear("hi");
+ checkLogOnce(log, [tag, 'hello', 'hi']);
+ clear('hi');
- setComment("hello");
+ setComment('hello');
r.clearExtension(comment);
r.deliverChanges();
- checkLogOnce(log, [tag, "hello", ""]);
+ checkLogOnce(log, [tag, 'hello', '']);
- setComment("hello");
+ setComment('hello');
r.clearField(comment.tagNumber);
r.deliverChanges();
- checkLogOnce(log, [tag, "hello", ""]);
+ checkLogOnce(log, [tag, 'hello', '']);
var registry = ExtensionRegistry()..add(comment);
r.mergeFromJson('{"$tag": "hello"}', registry);
- expect(r.getExtension(comment), "hello");
+ expect(r.getExtension(comment), 'hello');
r.deliverChanges();
- checkLogOnce(log, [tag, "", "hello"]);
- clear("hello");
+ checkLogOnce(log, [tag, '', 'hello']);
+ clear('hello');
- var src = Rec()..setExtension(comment, "hello");
+ var src = Rec()..setExtension(comment, 'hello');
r.mergeFromMessage(src);
- expect(r.getExtension(comment), "hello");
+ expect(r.getExtension(comment), 'hello');
r.deliverChanges();
- checkLogOnce(log, [tag, "", "hello"]);
- clear("hello");
+ checkLogOnce(log, [tag, '', 'hello']);
+ clear('hello');
- Uint8List bytes = src.writeToBuffer();
+ var bytes = src.writeToBuffer();
r.mergeFromBuffer(bytes, registry);
- expect(r.getExtension(comment), "hello");
+ expect(r.getExtension(comment), 'hello');
r.deliverChanges();
- checkLogOnce(log, [tag, "", "hello"]);
- clear("hello");
+ checkLogOnce(log, [tag, '', 'hello']);
+ clear('hello');
});
}
@@ -291,9 +292,9 @@
}
List toTuple(PbFieldChange fc) {
- fixValue(v) {
+ dynamic fixValue(v) {
if (v is GeneratedMessage) {
- return "<msg>";
+ return '<msg>';
}
return v;
}
diff --git a/protobuf/test/json_test.dart b/protobuf/test/json_test.dart
index 2ec2d42..ce2f792 100644
--- a/protobuf/test/json_test.dart
+++ b/protobuf/test/json_test.dart
@@ -9,14 +9,14 @@
import 'mock_util.dart' show T;
-main() {
- T example = T()
+void main() {
+ var example = T()
..val = 123
- ..str = "hello"
+ ..str = 'hello'
..int32s.addAll(<int>[1, 2, 3]);
test('testWriteToJson', () {
- String json = example.writeToJson();
+ var json = example.writeToJson();
checkJsonMap(jsonDecode(json));
});
@@ -39,7 +39,7 @@
test('testMergeFromJsonMap', () {
var t = T();
- t.mergeFromJsonMap({"1": 123, "2": "hello"});
+ t.mergeFromJsonMap({'1': 123, '2': 'hello'});
checkMessage(t);
});
@@ -47,7 +47,7 @@
final value = Int64.parseInt('1234567890123456789');
final t = T()..int64 = value;
final encoded = t.writeToJsonMap();
- expect(encoded["5"], "$value");
+ expect(encoded['5'], '$value');
final decoded = T()..mergeFromJsonMap(encoded);
expect(decoded.int64, value);
});
@@ -58,20 +58,20 @@
..int64 = value
..freeze();
final encoded = frozen.writeToJsonMap();
- expect(encoded["5"], "$value");
+ expect(encoded['5'], '$value');
final decoded = T()..mergeFromJsonMap(encoded);
expect(decoded.int64, value);
});
}
-checkJsonMap(Map m) {
+void checkJsonMap(Map m) {
expect(m.length, 3);
- expect(m["1"], 123);
- expect(m["2"], "hello");
- expect(m["4"], [1, 2, 3]);
+ expect(m['1'], 123);
+ expect(m['2'], 'hello');
+ expect(m['4'], [1, 2, 3]);
}
-checkMessage(T t) {
+void checkMessage(T t) {
expect(t.val, 123);
- expect(t.str, "hello");
+ expect(t.str, 'hello');
}
diff --git a/protobuf/test/json_vm_test.dart b/protobuf/test/json_vm_test.dart
index 6f3c8ae..7c539c5 100644
--- a/protobuf/test/json_vm_test.dart
+++ b/protobuf/test/json_vm_test.dart
@@ -9,12 +9,12 @@
import 'mock_util.dart' show T;
-main() {
+void main() {
test('testInt64JsonEncoding', () {
final value = Int64(1234567890123456789);
final t = T()..int64 = value;
final encoded = t.writeToJsonMap();
- expect(encoded["5"], "$value");
+ expect(encoded['5'], '$value');
final decoded = T()..mergeFromJsonMap(encoded);
expect(decoded.int64, value);
});
diff --git a/protobuf/test/list_test.dart b/protobuf/test/list_test.dart
index bced431..aa324cc 100755
--- a/protobuf/test/list_test.dart
+++ b/protobuf/test/list_test.dart
@@ -15,11 +15,11 @@
final badArgument = throwsA(invalidArgumentException);
// Suppress an analyzer warning for a deliberate type mismatch.
-cast(x) => x;
+T cast<T>(x) => x;
void main() {
test('testPbList handles basic operations', () {
- PbList<int> lb1 = PbList();
+ var lb1 = PbList<int>();
expect(lb1, []);
lb1.add(1);
@@ -45,14 +45,14 @@
expect(last, 99);
expect(lb1.last, 6);
- int count = 0;
+ var count = 0;
lb1.forEach((int i) {
count += i;
});
expect(count, 108);
bool isEven(int i) => i % 2 == 0;
- List<int> evens = List<int>.from(lb1.where(isEven));
+ var evens = List<int>.from(lb1.where(isEven));
expect(evens, [0, 2, 6]);
expect(lb1.any(isEven), isTrue);
@@ -65,7 +65,7 @@
});
test('PbList handles range operations', () {
- PbList<int> lb2 = PbList();
+ var lb2 = PbList<int>();
lb2.addAll([1, 2, 3, 4, 5, 6, 7, 8, 9]);
expect(lb2.sublist(3, 7), [4, 5, 6, 7]);
diff --git a/protobuf/test/map_mixin_test.dart b/protobuf/test/map_mixin_test.dart
index 7200517..ec60cbb 100644
--- a/protobuf/test/map_mixin_test.dart
+++ b/protobuf/test/map_mixin_test.dart
@@ -9,6 +9,7 @@
import 'dart:collection' show MapMixin;
+import 'package:protobuf/protobuf.dart';
import 'package:protobuf/src/protobuf/mixins/map_mixin.dart';
import 'package:test/test.dart' show expect, same, test, throwsArgumentError;
@@ -16,32 +17,34 @@
// A minimal protobuf implementation compatible with PbMapMixin.
class Rec extends MockMessage with MapMixin, PbMapMixin {
- get info_ => _info;
- static final _info = mockInfo("Rec", () => Rec());
+ @override
+ BuilderInfo get info_ => _info;
+ static final _info = mockInfo('Rec', () => Rec());
+ @override
Rec createEmptyInstance() => Rec();
@override
- String toString() => "Rec(${val}, \"${str}\")";
+ String toString() => 'Rec(${val}, "${str}")';
}
-main() {
+void main() {
test('PbMapMixin methods return default field values', () {
var r = Rec();
expect(r.isEmpty, false);
expect(r.isNotEmpty, true);
- expect(r.keys, ["val", "str", "child", "int32s", "int64"]);
+ expect(r.keys, ['val', 'str', 'child', 'int32s', 'int64']);
- expect(r["val"], 42);
- expect(r["str"], "");
- expect(r["child"].runtimeType, Rec);
- expect(r["child"].toString(), 'Rec(42, "")');
- expect(r["int32s"], []);
+ expect(r['val'], 42);
+ expect(r['str'], '');
+ expect(r['child'].runtimeType, Rec);
+ expect(r['child'].toString(), 'Rec(42, "")');
+ expect(r['int32s'], []);
var v = r.values;
expect(v.length, 5);
expect(v.first, 42);
- expect(v.toList()[1], "");
+ expect(v.toList()[1], '');
expect(v.toList()[3].toString(), '[]');
expect(v.last, 0);
});
@@ -49,23 +52,23 @@
test('operator []= sets record fields', () {
var r = Rec();
- r["val"] = 123;
+ r['val'] = 123;
expect(r.val, 123);
- expect(r["val"], 123);
+ expect(r['val'], 123);
- r["str"] = "hello";
- expect(r.str, "hello");
- expect(r["str"], "hello");
+ r['str'] = 'hello';
+ expect(r.str, 'hello');
+ expect(r['str'], 'hello');
var child = Rec();
- r["child"] = child;
+ r['child'] = child;
expect(r.child, same(child));
- expect(r["child"], same(child));
+ expect(r['child'], same(child));
- expect(() => r["int32s"] = 123, throwsArgumentError);
- r["int32s"].add(123);
- expect(r["int32s"], [123]);
- expect(r["int32s"], same(r["int32s"]));
+ expect(() => r['int32s'] = 123, throwsArgumentError);
+ r['int32s'].add(123);
+ expect(r['int32s'], [123]);
+ expect(r['int32s'], same(r['int32s']));
});
test('operator== and hashCode work for Map mixin', () {
@@ -75,7 +78,7 @@
expect({} == a, false);
var b = Rec();
- expect(a.info_ == b.info_, true, reason: "BuilderInfo should be the same");
+ expect(a.info_ == b.info_, true, reason: 'BuilderInfo should be the same');
expect(a == b, true);
expect(a.hashCode, b.hashCode);
diff --git a/protobuf/test/message_test.dart b/protobuf/test/message_test.dart
index 19276ad..bce8289 100644
--- a/protobuf/test/message_test.dart
+++ b/protobuf/test/message_test.dart
@@ -5,36 +5,40 @@
/// Tests for GeneratedMessage methods.
library message_test;
+import 'package:matcher/src/interfaces.dart';
+import 'package:protobuf/protobuf.dart';
import 'package:test/test.dart' show test, expect, predicate, throwsA;
import 'mock_util.dart' show MockMessage, mockInfo;
class Rec extends MockMessage {
- get info_ => _info;
- static final _info = mockInfo("Rec", () => Rec());
+ @override
+ BuilderInfo get info_ => _info;
+ static final _info = mockInfo('Rec', () => Rec());
+ @override
Rec createEmptyInstance() => Rec();
}
-throwsError(Type expectedType, String expectedMessage) =>
+Matcher throwsError(Type expectedType, String expectedMessage) =>
throwsA(predicate((x) {
expect(x.runtimeType, expectedType);
expect(x.message, expectedMessage);
return true;
}));
-main() {
+void main() {
test('getField with invalid tag throws exception', () {
var r = Rec();
expect(() {
r.getField(123);
- }, throwsError(ArgumentError, "tag 123 not defined in Rec"));
+ }, throwsError(ArgumentError, 'tag 123 not defined in Rec'));
});
test('getDefaultForField with invalid tag throws exception', () {
var r = Rec();
expect(() {
r.getDefaultForField(123);
- }, throwsError(ArgumentError, "tag 123 not defined in Rec"));
+ }, throwsError(ArgumentError, 'tag 123 not defined in Rec'));
});
test('operator== and hashCode works for frozen message', () {
@@ -69,7 +73,7 @@
expect(a == a, true);
var b = Rec();
- expect(a.info_ == b.info_, true, reason: "BuilderInfo should be the same");
+ expect(a.info_ == b.info_, true, reason: 'BuilderInfo should be the same');
expect(a == b, true);
expect(a.hashCode, b.hashCode);
diff --git a/protobuf/test/mock_util.dart b/protobuf/test/mock_util.dart
index 8b4025a..2153dfc 100644
--- a/protobuf/test/mock_util.dart
+++ b/protobuf/test/mock_util.dart
@@ -10,22 +10,23 @@
BuilderInfo mockInfo(String className, CreateBuilderFunc create) {
return BuilderInfo(className)
- ..a(1, "val", PbFieldType.O3, defaultOrMaker: 42)
- ..a(2, "str", PbFieldType.OS)
- ..a(3, "child", PbFieldType.OM, defaultOrMaker: create, subBuilder: create)
- ..p<int>(4, "int32s", PbFieldType.P3)
- ..a(5, "int64", PbFieldType.O6);
+ ..a(1, 'val', PbFieldType.O3, defaultOrMaker: 42)
+ ..a(2, 'str', PbFieldType.OS)
+ ..a(3, 'child', PbFieldType.OM, defaultOrMaker: create, subBuilder: create)
+ ..p<int>(4, 'int32s', PbFieldType.P3)
+ ..a(5, 'int64', PbFieldType.O6);
}
/// A minimal protobuf implementation for testing.
abstract class MockMessage extends GeneratedMessage {
// subclasses must provide these
+ @override
BuilderInfo get info_;
int get val => $_get(0, 42);
set val(x) => setField(1, x);
- String get str => $_getS(1, "");
+ String get str => $_getS(1, '');
set str(x) => $_setString(1, x);
MockMessage get child => $_getN(2);
@@ -36,14 +37,17 @@
Int64 get int64 => $_get(4, Int64(0));
set int64(x) => setField(5, x);
- clone() {
- CreateBuilderFunc create = info_.byName["child"].subBuilder;
+ @override
+ GeneratedMessage clone() {
+ var create = info_.byName['child'].subBuilder;
return create()..mergeFromMessage(this);
}
}
class T extends MockMessage {
- get info_ => _info;
- static final _info = mockInfo("T", () => T());
+ @override
+ BuilderInfo get info_ => _info;
+ static final _info = mockInfo('T', () => T());
+ @override
T createEmptyInstance() => T();
}
diff --git a/protobuf/test/readonly_message_test.dart b/protobuf/test/readonly_message_test.dart
index b6fab67..92203ec 100644
--- a/protobuf/test/readonly_message_test.dart
+++ b/protobuf/test/readonly_message_test.dart
@@ -16,7 +16,7 @@
frozenMessageModificationHandler,
defaultFrozenMessageModificationHandler;
-throwsError(Type expectedType, Matcher expectedMessage) =>
+Matcher throwsError(Type expectedType, Matcher expectedMessage) =>
throwsA(predicate((x) {
expect(x.runtimeType, expectedType);
expect(x.message, expectedMessage);
@@ -26,6 +26,7 @@
class Rec extends GeneratedMessage {
static Rec getDefault() => Rec()..freeze();
static Rec create() => Rec();
+ @override
Rec createEmptyInstance() => Rec();
@override
@@ -48,14 +49,15 @@
@override
Rec clone() => Rec()..mergeFromMessage(this);
+ @override
Rec copyWith(void Function(Rec) updates) =>
super.copyWith((message) => updates(message as Rec));
}
-main() {
+void main() {
test('can write a read-only message', () {
expect(Rec.getDefault().writeToBuffer(), []);
- expect(Rec.getDefault().writeToJson(), "{}");
+ expect(Rec.getDefault().writeToJson(), '{}');
});
test("can't merge to a read-only message", () {
@@ -75,7 +77,7 @@
test('can set a field on a read-only message with a custom read-only handler',
() {
try {
- int called = 0;
+ var called = 0;
frozenMessageModificationHandler =
(String messageName, [String methodName]) {
@@ -168,10 +170,10 @@
throwsError(
UnsupportedError,
equals(
- "Attempted to call clear on a read-only message (UnknownFieldSet)")));
+ 'Attempted to call clear on a read-only message (UnknownFieldSet)')));
});
- test("can rebuild a frozen message with merge", () {
+ test('can rebuild a frozen message with merge', () {
final orig = Rec.create()
..value = 10
..freeze();
@@ -181,7 +183,7 @@
expect(rebuilt.value, 7);
});
- test("can set a field while rebuilding a frozen message", () {
+ test('can set a field while rebuilding a frozen message', () {
final orig = Rec.create()
..value = 10
..freeze();
@@ -191,7 +193,7 @@
expect(rebuilt.value, 7);
});
- test("can clear while rebuilding a frozen message", () {
+ test('can clear while rebuilding a frozen message', () {
final orig = Rec.create()
..value = 10
..freeze();
@@ -202,7 +204,7 @@
expect(rebuilt.hasValue(), false);
});
- test("can clear a field while rebuilding a frozen message", () {
+ test('can clear a field while rebuilding a frozen message', () {
final orig = Rec.create()
..value = 10
..freeze();
@@ -213,7 +215,7 @@
expect(rebuilt.hasValue(), false);
});
- test("can modify repeated fields while rebuilding a frozen message", () {
+ test('can modify repeated fields while rebuilding a frozen message', () {
var orig = Rec.create()
..ints.add(10)
..freeze();
@@ -238,7 +240,7 @@
expect(rebuilt.sub.length, 2);
});
- test("cannot modify sub-messages while rebuilding a frozen message", () {
+ test('cannot modify sub-messages while rebuilding a frozen message', () {
final subMessage = Rec.create()..value = 1;
final orig = Rec.create()
..sub.add(Rec.create()..sub.add(subMessage))
@@ -262,7 +264,7 @@
expect(rebuilt.sub[0].sub[0].value, 2);
});
- test("can modify unknown fields while rebuilding a frozen message", () {
+ test('can modify unknown fields while rebuilding a frozen message', () {
final orig = Rec.create()
..unknownFields.addField(20, UnknownFieldSetField()..fixed32s.add(1));
final rebuilt = orig.copyWith((m) => m.unknownFields.clear());
diff --git a/protobuf/test/test_util.dart b/protobuf/test/test_util.dart
index 0d53917..c01aff5 100644
--- a/protobuf/test/test_util.dart
+++ b/protobuf/test/test_util.dart
@@ -8,11 +8,11 @@
import 'package:test/test.dart';
Int64 make64(int lo, [int hi]) {
- if (hi == null) hi = lo < 0 ? -1 : 0;
+ hi ??= lo < 0 ? -1 : 0;
return Int64.fromInts(hi, lo);
}
-expect64(int lo, [int hi]) {
- final Int64 expected = make64(lo, hi);
+Matcher expect64(int lo, [int hi]) {
+ final expected = make64(lo, hi);
return predicate((Int64 actual) => actual == expected);
}