Dart null safety (#6696)

* Dart null-safety - prepare migration annotations in library files

* Dart null-safety - apply migration

* Dart null-safety - update flatc to generate valid code

* Dart null-safety - fix flatc generated code and adjust tests

* Dart null-safety - update example and the generated code in the tests folder

* Dart null safety - minor review changes

* Dart - apply `dartfmt -w .`
This commit is contained in:
Ivan Dlugos
2021-06-22 17:54:57 +02:00
committed by GitHub
parent 71d43f3be9
commit a6ee335574
23 changed files with 3352 additions and 2649 deletions

View File

@@ -26,10 +26,10 @@ void main() {
void builderTest() {
final builder = new fb.Builder(initialSize: 1024);
final int weaponOneName = builder.writeString("Sword");
final int? weaponOneName = builder.writeString("Sword");
final int weaponOneDamage = 3;
final int weaponTwoName = builder.writeString("Axe");
final int? weaponTwoName = builder.writeString("Axe");
final int weaponTwoDamage = 5;
final swordBuilder = new myGame.WeaponBuilder(builder)
@@ -45,7 +45,7 @@ void builderTest() {
final int axe = axeBuilder.finish();
// Serialize a name for our monster, called "Orc".
final int name = builder.writeString('Orc');
final int? name = builder.writeString('Orc');
// Create a list representing the inventory of the Orc. Each number
// could correspond to an item that can be claimed after he is slain.
@@ -122,27 +122,25 @@ bool verify(List<int> buffer) {
assert(monster.name == "MyMonster");
// Get and test a field of the FlatBuffer's `struct`.
var pos = monster.pos;
assert(pos != null);
var pos = monster.pos!;
assert(pos.z == 3.0);
// Get a test an element from the `inventory` FlatBuffer's `vector`.
var inv = monster.inventory;
assert(inv != null);
var inv = monster.inventory!;
assert(inv.length == 10);
assert(inv[9] == 9);
// Get and test the `weapons` FlatBuffers's `vector`.
var expected_weapon_names = ["Sword", "Axe"];
var expected_weapon_damages = [3, 5];
var weps = monster.weapons;
var weps = monster.weapons!;
for (int i = 0; i < weps.length; i++) {
assert(weps[i].name == expected_weapon_names[i]);
assert(weps[i].damage == expected_weapon_damages[i]);
}
// Get and test the `Equipment` union (`equipped` field).
assert(monster.equippedType.value == myGame.EquipmentTypeId.Weapon.value);
assert(monster.equippedType!.value == myGame.EquipmentTypeId.Weapon.value);
assert(monster.equippedType == myGame.EquipmentTypeId.Weapon);
assert(monster.equipped is myGame.Weapon);

View File

@@ -1,5 +1,5 @@
// automatically generated by the FlatBuffers compiler, do not modify
// ignore_for_file: unused_import, unused_field, unused_local_variable
// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable
library my_game.sample;
@@ -12,13 +12,16 @@ class Color {
const Color._(this.value);
factory Color.fromValue(int value) {
if (value == null) value = 0;
if (!values.containsKey(value)) {
final result = values[value];
if (result == null) {
throw new StateError('Invalid value $value for bit flag enum Color');
}
return values[value];
return result;
}
static Color? _createOrNull(int? value) =>
value == null ? null : Color.fromValue(value);
static const int minValue = 0;
static const int maxValue = 2;
static bool containsValue(int value) => values.containsKey(value);
@@ -26,7 +29,10 @@ class Color {
static const Color Red = const Color._(0);
static const Color Green = const Color._(1);
static const Color Blue = const Color._(2);
static const Map<int,Color> values = {0: Red,1: Green,2: Blue,};
static const Map<int, Color> values = {
0: Red,
1: Green,
2: Blue};
static const fb.Reader<Color> reader = const _ColorReader();
@@ -52,20 +58,25 @@ class EquipmentTypeId {
const EquipmentTypeId._(this.value);
factory EquipmentTypeId.fromValue(int value) {
if (value == null) value = 0;
if (!values.containsKey(value)) {
final result = values[value];
if (result == null) {
throw new StateError('Invalid value $value for bit flag enum EquipmentTypeId');
}
return values[value];
return result;
}
static EquipmentTypeId? _createOrNull(int? value) =>
value == null ? null : EquipmentTypeId.fromValue(value);
static const int minValue = 0;
static const int maxValue = 1;
static bool containsValue(int value) => values.containsKey(value);
static const EquipmentTypeId NONE = const EquipmentTypeId._(0);
static const EquipmentTypeId Weapon = const EquipmentTypeId._(1);
static const Map<int,EquipmentTypeId> values = {0: NONE,1: Weapon,};
static const Map<int, EquipmentTypeId> values = {
0: NONE,
1: Weapon};
static const fb.Reader<EquipmentTypeId> reader = const _EquipmentTypeIdReader();
@@ -116,9 +127,7 @@ class _Vec3Reader extends fb.StructReader<Vec3> {
}
class Vec3Builder {
Vec3Builder(this.fbBuilder) {
assert(fbBuilder != null);
}
Vec3Builder(this.fbBuilder) {}
final fb.Builder fbBuilder;
@@ -137,9 +146,9 @@ class Vec3ObjectBuilder extends fb.ObjectBuilder {
final double _z;
Vec3ObjectBuilder({
double x,
double y,
double z,
required double x,
required double y,
required double z,
})
: _x = x,
_y = y,
@@ -147,10 +156,7 @@ class Vec3ObjectBuilder extends fb.ObjectBuilder {
/// Finish building, and store into the [fbBuilder].
@override
int finish(
fb.Builder fbBuilder) {
assert(fbBuilder != null);
int finish(fb.Builder fbBuilder) {
fbBuilder.putFloat32(_z);
fbBuilder.putFloat32(_y);
fbBuilder.putFloat32(_x);
@@ -159,7 +165,7 @@ class Vec3ObjectBuilder extends fb.ObjectBuilder {
/// Convenience method to serialize to byte list.
@override
Uint8List toBytes([String fileIdentifier]) {
Uint8List toBytes([String? fileIdentifier]) {
fb.Builder fbBuilder = new fb.Builder();
int offset = finish(fbBuilder);
return fbBuilder.finish(offset, fileIdentifier);
@@ -177,21 +183,21 @@ class Monster {
final fb.BufferContext _bc;
final int _bcOffset;
Vec3 get pos => Vec3.reader.vTableGet(_bc, _bcOffset, 4, null);
Vec3? get pos => Vec3.reader.vTableGetNullable(_bc, _bcOffset, 4);
int get mana => const fb.Int16Reader().vTableGet(_bc, _bcOffset, 6, 150);
int get hp => const fb.Int16Reader().vTableGet(_bc, _bcOffset, 8, 100);
String get name => const fb.StringReader().vTableGet(_bc, _bcOffset, 10, null);
List<int> get inventory => const fb.ListReader<int>(const fb.Uint8Reader()).vTableGet(_bc, _bcOffset, 14, null);
Color get color => new Color.fromValue(const fb.Int8Reader().vTableGet(_bc, _bcOffset, 16, 2));
List<Weapon> get weapons => const fb.ListReader<Weapon>(Weapon.reader).vTableGet(_bc, _bcOffset, 18, null);
EquipmentTypeId get equippedType => new EquipmentTypeId.fromValue(const fb.Uint8Reader().vTableGet(_bc, _bcOffset, 20, 0));
dynamic get equipped {
String? get name => const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 10);
List<int>? get inventory => const fb.ListReader<int>(const fb.Uint8Reader()).vTableGetNullable(_bc, _bcOffset, 14);
Color get color => Color.fromValue(const fb.Int8Reader().vTableGet(_bc, _bcOffset, 16, 2));
List<Weapon>? get weapons => const fb.ListReader<Weapon>(Weapon.reader).vTableGetNullable(_bc, _bcOffset, 18);
EquipmentTypeId? get equippedType => EquipmentTypeId._createOrNull(const fb.Uint8Reader().vTableGetNullable(_bc, _bcOffset, 20));
dynamic? get equipped {
switch (equippedType?.value) {
case 1: return Weapon.reader.vTableGet(_bc, _bcOffset, 22, null);
case 1: return Weapon.reader.vTableGetNullable(_bc, _bcOffset, 22);
default: return null;
}
}
List<Vec3> get path => const fb.ListReader<Vec3>(Vec3.reader).vTableGet(_bc, _bcOffset, 24, null);
List<Vec3>? get path => const fb.ListReader<Vec3>(Vec3.reader).vTableGetNullable(_bc, _bcOffset, 24);
@override
String toString() {
@@ -208,9 +214,7 @@ class _MonsterReader extends fb.TableReader<Monster> {
}
class MonsterBuilder {
MonsterBuilder(this.fbBuilder) {
assert(fbBuilder != null);
}
MonsterBuilder(this.fbBuilder) {}
final fb.Builder fbBuilder;
@@ -222,39 +226,39 @@ class MonsterBuilder {
fbBuilder.addStruct(0, offset);
return fbBuilder.offset;
}
int addMana(int mana) {
int addMana(int? mana) {
fbBuilder.addInt16(1, mana);
return fbBuilder.offset;
}
int addHp(int hp) {
int addHp(int? hp) {
fbBuilder.addInt16(2, hp);
return fbBuilder.offset;
}
int addNameOffset(int offset) {
int addNameOffset(int? offset) {
fbBuilder.addOffset(3, offset);
return fbBuilder.offset;
}
int addInventoryOffset(int offset) {
int addInventoryOffset(int? offset) {
fbBuilder.addOffset(5, offset);
return fbBuilder.offset;
}
int addColor(Color color) {
int addColor(Color? color) {
fbBuilder.addInt8(6, color?.value);
return fbBuilder.offset;
}
int addWeaponsOffset(int offset) {
int addWeaponsOffset(int? offset) {
fbBuilder.addOffset(7, offset);
return fbBuilder.offset;
}
int addEquippedType(EquipmentTypeId equippedType) {
int addEquippedType(EquipmentTypeId? equippedType) {
fbBuilder.addUint8(8, equippedType?.value);
return fbBuilder.offset;
}
int addEquippedOffset(int offset) {
int addEquippedOffset(int? offset) {
fbBuilder.addOffset(9, offset);
return fbBuilder.offset;
}
int addPathOffset(int offset) {
int addPathOffset(int? offset) {
fbBuilder.addOffset(10, offset);
return fbBuilder.offset;
}
@@ -265,28 +269,28 @@ class MonsterBuilder {
}
class MonsterObjectBuilder extends fb.ObjectBuilder {
final Vec3ObjectBuilder _pos;
final int _mana;
final int _hp;
final String _name;
final List<int> _inventory;
final Color _color;
final List<WeaponObjectBuilder> _weapons;
final EquipmentTypeId _equippedType;
final dynamic _equipped;
final List<Vec3ObjectBuilder> _path;
final Vec3ObjectBuilder? _pos;
final int? _mana;
final int? _hp;
final String? _name;
final List<int>? _inventory;
final Color? _color;
final List<WeaponObjectBuilder>? _weapons;
final EquipmentTypeId? _equippedType;
final dynamic? _equipped;
final List<Vec3ObjectBuilder>? _path;
MonsterObjectBuilder({
Vec3ObjectBuilder pos,
int mana,
int hp,
String name,
List<int> inventory,
Color color,
List<WeaponObjectBuilder> weapons,
EquipmentTypeId equippedType,
dynamic equipped,
List<Vec3ObjectBuilder> path,
Vec3ObjectBuilder? pos,
int? mana,
int? hp,
String? name,
List<int>? inventory,
Color? color,
List<WeaponObjectBuilder>? weapons,
EquipmentTypeId? equippedType,
dynamic? equipped,
List<Vec3ObjectBuilder>? path,
})
: _pos = pos,
_mana = mana,
@@ -301,50 +305,37 @@ class MonsterObjectBuilder extends fb.ObjectBuilder {
/// Finish building, and store into the [fbBuilder].
@override
int finish(
fb.Builder fbBuilder) {
assert(fbBuilder != null);
final int nameOffset = fbBuilder.writeString(_name);
final int inventoryOffset = _inventory?.isNotEmpty == true
? fbBuilder.writeListUint8(_inventory)
int finish(fb.Builder fbBuilder) {
final int? nameOffset = fbBuilder.writeString(_name);
final int? inventoryOffset = _inventory?.isNotEmpty == true
? fbBuilder.writeListUint8(_inventory!)
: null;
final int weaponsOffset = _weapons?.isNotEmpty == true
? fbBuilder.writeList(_weapons.map((b) => b.getOrCreateOffset(fbBuilder)).toList())
final int? weaponsOffset = _weapons?.isNotEmpty == true
? fbBuilder.writeList(_weapons!.map((b) => b.getOrCreateOffset(fbBuilder)).toList())
: null;
final int equippedOffset = _equipped?.getOrCreateOffset(fbBuilder);
final int pathOffset = _path?.isNotEmpty == true
? fbBuilder.writeListOfStructs(_path)
final int? equippedOffset = _equipped?.getOrCreateOffset(fbBuilder);
final int? pathOffset = _path?.isNotEmpty == true
? fbBuilder.writeListOfStructs(_path!)
: null;
fbBuilder.startTable();
if (_pos != null) {
fbBuilder.addStruct(0, _pos.finish(fbBuilder));
fbBuilder.addStruct(0, _pos!.finish(fbBuilder));
}
fbBuilder.addInt16(1, _mana);
fbBuilder.addInt16(2, _hp);
if (nameOffset != null) {
fbBuilder.addOffset(3, nameOffset);
}
if (inventoryOffset != null) {
fbBuilder.addOffset(5, inventoryOffset);
}
fbBuilder.addOffset(3, nameOffset);
fbBuilder.addOffset(5, inventoryOffset);
fbBuilder.addInt8(6, _color?.value);
if (weaponsOffset != null) {
fbBuilder.addOffset(7, weaponsOffset);
}
fbBuilder.addOffset(7, weaponsOffset);
fbBuilder.addUint8(8, _equippedType?.value);
if (equippedOffset != null) {
fbBuilder.addOffset(9, equippedOffset);
}
if (pathOffset != null) {
fbBuilder.addOffset(10, pathOffset);
}
fbBuilder.addOffset(9, equippedOffset);
fbBuilder.addOffset(10, pathOffset);
return fbBuilder.endTable();
}
/// Convenience method to serialize to byte list.
@override
Uint8List toBytes([String fileIdentifier]) {
Uint8List toBytes([String? fileIdentifier]) {
fb.Builder fbBuilder = new fb.Builder();
int offset = finish(fbBuilder);
return fbBuilder.finish(offset, fileIdentifier);
@@ -362,7 +353,7 @@ class Weapon {
final fb.BufferContext _bc;
final int _bcOffset;
String get name => const fb.StringReader().vTableGet(_bc, _bcOffset, 4, null);
String? get name => const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 4);
int get damage => const fb.Int16Reader().vTableGet(_bc, _bcOffset, 6, 0);
@override
@@ -380,9 +371,7 @@ class _WeaponReader extends fb.TableReader<Weapon> {
}
class WeaponBuilder {
WeaponBuilder(this.fbBuilder) {
assert(fbBuilder != null);
}
WeaponBuilder(this.fbBuilder) {}
final fb.Builder fbBuilder;
@@ -390,11 +379,11 @@ class WeaponBuilder {
fbBuilder.startTable();
}
int addNameOffset(int offset) {
int addNameOffset(int? offset) {
fbBuilder.addOffset(0, offset);
return fbBuilder.offset;
}
int addDamage(int damage) {
int addDamage(int? damage) {
fbBuilder.addInt16(1, damage);
return fbBuilder.offset;
}
@@ -405,34 +394,29 @@ class WeaponBuilder {
}
class WeaponObjectBuilder extends fb.ObjectBuilder {
final String _name;
final int _damage;
final String? _name;
final int? _damage;
WeaponObjectBuilder({
String name,
int damage,
String? name,
int? damage,
})
: _name = name,
_damage = damage;
/// Finish building, and store into the [fbBuilder].
@override
int finish(
fb.Builder fbBuilder) {
assert(fbBuilder != null);
final int nameOffset = fbBuilder.writeString(_name);
int finish(fb.Builder fbBuilder) {
final int? nameOffset = fbBuilder.writeString(_name);
fbBuilder.startTable();
if (nameOffset != null) {
fbBuilder.addOffset(0, nameOffset);
}
fbBuilder.addOffset(0, nameOffset);
fbBuilder.addInt16(1, _damage);
return fbBuilder.endTable();
}
/// Convenience method to serialize to byte list.
@override
Uint8List toBytes([String fileIdentifier]) {
Uint8List toBytes([String? fileIdentifier]) {
fb.Builder fbBuilder = new fb.Builder();
int offset = finish(fbBuilder);
return fbBuilder.finish(offset, fileIdentifier);

View File

@@ -28,13 +28,17 @@ typedef void StructBuilder();
class BufferContext {
final ByteData _buffer;
ByteData get buffer => _buffer;
/// Create from a FlatBuffer represented by a list of bytes (uint8).
factory BufferContext.fromBytes(List<int> byteList) {
Uint8List uint8List = _asUint8List(byteList);
ByteData buf = new ByteData.view(uint8List.buffer, uint8List.offsetInBytes);
return new BufferContext._(buf);
return BufferContext(buf);
}
BufferContext._(this._buffer);
/// Create from a FlatBuffer represented by ByteData.
BufferContext(this._buffer);
int derefObject(int offset) {
return offset + _getUint32(offset);
@@ -43,31 +47,23 @@ class BufferContext {
Uint8List _asUint8LIst(int offset, int length) =>
_buffer.buffer.asUint8List(_buffer.offsetInBytes + offset, length);
double _getFloat64(int offset) =>
_buffer.getFloat64(offset, Endian.little);
double _getFloat64(int offset) => _buffer.getFloat64(offset, Endian.little);
double _getFloat32(int offset) =>
_buffer.getFloat32(offset, Endian.little);
double _getFloat32(int offset) => _buffer.getFloat32(offset, Endian.little);
int _getInt64(int offset) =>
_buffer.getInt64(offset, Endian.little);
int _getInt64(int offset) => _buffer.getInt64(offset, Endian.little);
int _getInt32(int offset) =>
_buffer.getInt32(offset, Endian.little);
int _getInt32(int offset) => _buffer.getInt32(offset, Endian.little);
int _getInt16(int offset) =>
_buffer.getInt16(offset, Endian.little);
int _getInt16(int offset) => _buffer.getInt16(offset, Endian.little);
int _getInt8(int offset) => _buffer.getInt8(offset);
int _getUint64(int offset) =>
_buffer.getUint64(offset, Endian.little);
int _getUint64(int offset) => _buffer.getUint64(offset, Endian.little);
int _getUint32(int offset) =>
_buffer.getUint32(offset, Endian.little);
int _getUint32(int offset) => _buffer.getUint32(offset, Endian.little);
int _getUint16(int offset) =>
_buffer.getUint16(offset, Endian.little);
int _getUint16(int offset) => _buffer.getUint16(offset, Endian.little);
int _getUint8(int offset) => _buffer.getUint8(offset);
@@ -84,7 +80,7 @@ class BufferContext {
/// Class implemented by typed builders generated by flatc.
abstract class ObjectBuilder {
int _firstOffset;
int? _firstOffset;
/// Can be used to write the data represented by this builder to the [Builder]
/// and reuse the offset created in multiple tables.
@@ -94,7 +90,7 @@ abstract class ObjectBuilder {
/// first call to this method.
int getOrCreateOffset(Builder fbBuilder) {
_firstOffset ??= finish(fbBuilder);
return _firstOffset;
return _firstOffset!;
}
/// Writes the data in this helper to the [Builder].
@@ -110,8 +106,8 @@ class Builder {
final int initialSize;
/// The list of existing VTable(s).
//final List<_VTable> _vTables = <_VTable>[];
final List<int> _vTables = <int>[];
final List<int> _vTables = List<int>.filled(16, 0, growable: true)
..length = 0;
ByteData _buf;
@@ -125,16 +121,16 @@ class Builder {
int _tail = 0;
/// The location of the end of the current table, measured in bytes from the
/// end of [_buf], or `null` if a table is not currently being built.
int _currentTableEndTail;
/// end of [_buf].
int _currentTableEndTail = 0;
_VTable _currentVTable;
_VTable? _currentVTable;
/// Map containing all strings that have been written so far. This allows us
/// to avoid duplicating strings.
///
/// Allocated only if `internStrings` is set to true on the constructor.
Map<String, int> _strings;
Map<String, int>? _strings;
/// Creates a new FlatBuffers Builder.
///
@@ -155,7 +151,7 @@ class Builder {
/// Add the [field] with the given boolean [value]. The field is not added if
/// the [value] is equal to [def]. Booleans are stored as 8-bit fields with
/// `0` for `false` and `1` for `true`.
void addBool(int field, bool value, [bool def]) {
void addBool(int field, bool? value, [bool? def]) {
_ensureCurrentVTable();
if (value != null && value != def) {
_prepare(_sizeofUint8, 1);
@@ -166,7 +162,7 @@ class Builder {
/// Add the [field] with the given 32-bit signed integer [value]. The field is
/// not added if the [value] is equal to [def].
void addInt32(int field, int value, [int def]) {
void addInt32(int field, int? value, [int? def]) {
_ensureCurrentVTable();
if (value != null && value != def) {
_prepare(_sizeofInt32, 1);
@@ -177,7 +173,7 @@ class Builder {
/// Add the [field] with the given 32-bit signed integer [value]. The field is
/// not added if the [value] is equal to [def].
void addInt16(int field, int value, [int def]) {
void addInt16(int field, int? value, [int? def]) {
_ensureCurrentVTable();
if (value != null && value != def) {
_prepare(_sizeofInt16, 1);
@@ -188,7 +184,7 @@ class Builder {
/// Add the [field] with the given 8-bit signed integer [value]. The field is
/// not added if the [value] is equal to [def].
void addInt8(int field, int value, [int def]) {
void addInt8(int field, int? value, [int? def]) {
_ensureCurrentVTable();
if (value != null && value != def) {
_prepare(_sizeofInt8, 1);
@@ -200,11 +196,11 @@ class Builder {
void addStruct(int field, int offset) {
_ensureCurrentVTable();
_trackField(field);
_currentVTable.addField(field, offset);
_currentVTable!.addField(field, offset);
}
/// Add the [field] referencing an object with the given [offset].
void addOffset(int field, int offset) {
void addOffset(int field, int? offset) {
_ensureCurrentVTable();
if (offset != null) {
_prepare(_sizeofUint32, 1);
@@ -215,7 +211,7 @@ class Builder {
/// Add the [field] with the given 32-bit unsigned integer [value]. The field
/// is not added if the [value] is equal to [def].
void addUint32(int field, int value, [int def]) {
void addUint32(int field, int? value, [int? def]) {
_ensureCurrentVTable();
if (value != null && value != def) {
_prepare(_sizeofUint32, 1);
@@ -226,7 +222,7 @@ class Builder {
/// Add the [field] with the given 32-bit unsigned integer [value]. The field
/// is not added if the [value] is equal to [def].
void addUint16(int field, int value, [int def]) {
void addUint16(int field, int? value, [int? def]) {
_ensureCurrentVTable();
if (value != null && value != def) {
_prepare(_sizeofUint16, 1);
@@ -237,7 +233,7 @@ class Builder {
/// Add the [field] with the given 8-bit unsigned integer [value]. The field
/// is not added if the [value] is equal to [def].
void addUint8(int field, int value, [int def]) {
void addUint8(int field, int? value, [int? def]) {
_ensureCurrentVTable();
if (value != null && value != def) {
_prepare(_sizeofUint8, 1);
@@ -248,7 +244,7 @@ class Builder {
/// Add the [field] with the given 32-bit float [value]. The field
/// is not added if the [value] is equal to [def].
void addFloat32(int field, double value, [double def]) {
void addFloat32(int field, double? value, [double? def]) {
_ensureCurrentVTable();
if (value != null && value != def) {
_prepare(_sizeofFloat32, 1);
@@ -259,7 +255,7 @@ class Builder {
/// Add the [field] with the given 64-bit double [value]. The field
/// is not added if the [value] is equal to [def].
void addFloat64(int field, double value, [double def]) {
void addFloat64(int field, double? value, [double? def]) {
_ensureCurrentVTable();
if (value != null && value != def) {
_prepare(_sizeofFloat64, 1);
@@ -270,7 +266,7 @@ class Builder {
/// Add the [field] with the given 64-bit unsigned integer [value]. The field
/// is not added if the [value] is equal to [def].
void addUint64(int field, int value, [double def]) {
void addUint64(int field, int? value, [double? def]) {
_ensureCurrentVTable();
if (value != null && value != def) {
_prepare(_sizeofUint64, 1);
@@ -281,7 +277,7 @@ class Builder {
/// Add the [field] with the given 64-bit unsigned integer [value]. The field
/// is not added if the [value] is equal to [def].
void addInt64(int field, int value, [double def]) {
void addInt64(int field, int? value, [double? def]) {
_ensureCurrentVTable();
if (value != null && value != def) {
_prepare(_sizeofInt64, 1);
@@ -299,11 +295,12 @@ class Builder {
_prepare(_sizeofInt32, 1);
int tableTail = _tail;
// Prepare the size of the current table.
_currentVTable.tableSize = tableTail - _currentTableEndTail;
final currentVTable = _currentVTable!;
currentVTable.tableSize = tableTail - _currentTableEndTail;
// Prepare the VTable to use for the current table.
int vTableTail;
int? vTableTail;
{
_currentVTable.computeFieldOffsets(tableTail);
currentVTable.computeFieldOffsets(tableTail);
// Try to find an existing compatible VTable.
// Search backward - more likely to have recently used one
for (int i = _vTables.length - 1; i >= 0; i--) {
@@ -311,19 +308,19 @@ class Builder {
final int vt2Start = _buf.lengthInBytes - vt2Offset;
final int vt2Size = _buf.getUint16(vt2Start, Endian.little);
if (_currentVTable._vTableSize == vt2Size &&
_currentVTable._offsetsMatch(vt2Start, _buf)) {
if (currentVTable._vTableSize == vt2Size &&
currentVTable._offsetsMatch(vt2Start, _buf)) {
vTableTail = vt2Offset;
break;
}
}
// Write a new VTable.
if (vTableTail == null) {
_prepare(_sizeofUint16, _currentVTable.numOfUint16);
_prepare(_sizeofUint16, _currentVTable!.numOfUint16);
vTableTail = _tail;
_currentVTable.tail = vTableTail;
_currentVTable.output(_buf, _buf.lengthInBytes - _tail);
_vTables.add(_currentVTable.tail);
currentVTable.tail = vTableTail;
currentVTable.output(_buf, _buf.lengthInBytes - _tail);
_vTables.add(currentVTable.tail);
}
}
// Set the VTable offset.
@@ -346,7 +343,7 @@ class Builder {
/// written object. If [fileIdentifier] is specified (and not `null`), it is
/// interpreted as a 4-byte Latin-1 encoded string that should be placed at
/// bytes 4-7 of the file.
Uint8List finish(int offset, [String fileIdentifier]) {
Uint8List finish(int offset, [String? fileIdentifier]) {
_prepare(max(_sizeofUint32, _maxAlign), fileIdentifier == null ? 1 : 2);
final finishedSize = size();
_setUint32AtTail(_buf, finishedSize, finishedSize - offset);
@@ -444,7 +441,7 @@ class Builder {
_maxAlign = 1;
_tail = 0;
_currentVTable = null;
_vTables.clear();
_vTables.length = 0;
if (_strings != null) {
_strings = new Map<String, int>();
}
@@ -613,7 +610,7 @@ class Builder {
/// Write the given list of bools as unsigend 8-bit integer [values].
int writeListBool(List<bool> values) {
return writeListUint8(values?.map((b) => b ? 1 : 0)?.toList());
return writeListUint8(values.map((b) => b ? 1 : 0).toList());
}
/// Write the given list of signed 8-bit integer [values].
@@ -648,11 +645,11 @@ class Builder {
/// Write the given string [value] and return its offset, or `null` if
/// the [value] is `null`.
int writeString(String value) {
int? writeString(String? value) {
_ensureNoVTable();
if (value != null) {
if (_strings != null) {
return _strings.putIfAbsent(value, () => _writeString(value));
return _strings!.putIfAbsent(value, () => _writeString(value));
} else {
return _writeString(value);
}
@@ -732,7 +729,7 @@ class Builder {
/// Record the offset of the given [field].
void _trackField(int field) {
_currentVTable.addField(field, _tail);
_currentVTable!.addField(field, _tail);
}
static void _setFloat64AtTail(ByteData _buf, int tail, double x) {
@@ -848,6 +845,7 @@ class Float32Reader extends Reader<double> {
class Int64Reader extends Reader<int> {
const Int64Reader() : super();
@override
int get size => _sizeofInt64;
@@ -915,19 +913,23 @@ abstract class Reader<T> {
T read(BufferContext bc, int offset);
/// Read the value of the given [field] in the given [object].
T vTableGet(BufferContext object, int offset, int field, [T defaultValue]) {
T vTableGet(BufferContext object, int offset, int field, T defaultValue) {
int fieldOffset = _vTableFieldOffset(object, offset, field);
return fieldOffset == 0 ? defaultValue : read(object, offset + fieldOffset);
}
/// Read the value of the given [field] in the given [object].
T? vTableGetNullable(BufferContext object, int offset, int field) {
int fieldOffset = _vTableFieldOffset(object, offset, field);
return fieldOffset == 0 ? null : read(object, offset + fieldOffset);
}
int _vTableFieldOffset(BufferContext object, int offset, int field) {
int vTableSOffset = object._getInt32(offset);
int vTableOffset = offset - vTableSOffset;
int vTableSize = object._getUint16(vTableOffset);
int vTableFieldOffset = field;
if (vTableFieldOffset < vTableSize) {
int fieldOffsetInObject =
object._getUint16(vTableOffset + vTableFieldOffset);
if (fieldOffsetInObject != 0) {
return read(object, offset + fieldOffsetInObject);
}
}
return defaultValue;
if (field >= vTableSize) return 0;
return object._getUint16(vTableOffset + field);
}
}
@@ -1101,20 +1103,20 @@ class _FbFloat32List extends _FbList<double> {
class _FbGenericList<E> extends _FbList<E> {
final Reader<E> elementReader;
List<E> _items;
List<E?>? _items;
_FbGenericList(this.elementReader, BufferContext bp, int offset)
: super(bp, offset);
@override
E operator [](int i) {
_items ??= new List<E>(length);
E item = _items[i];
_items ??= List<E?>.filled(length, null);
E? item = _items![i];
if (item == null) {
item = elementReader.read(bc, offset + 4 + elementReader.size * i);
_items[i] = item;
_items![i] = item;
}
return item;
return item!;
}
}
@@ -1122,14 +1124,14 @@ class _FbGenericList<E> extends _FbList<E> {
abstract class _FbList<E> extends Object with ListMixin<E> implements List<E> {
final BufferContext bc;
final int offset;
int _length;
int? _length;
_FbList(this.bc, this.offset);
@override
int get length {
_length ??= bc._getUint32(offset);
return _length;
return _length!;
}
@override
@@ -1185,15 +1187,15 @@ class _FbBoolList extends _FbList<bool> {
class _VTable {
static const int _metadataLength = 4;
final List<int> fieldTails = <int>[];
final List<int> fieldOffsets = <int>[];
final fieldTails = <int?>[];
final fieldOffsets = <int>[];
/// The size of the table that uses this VTable.
int tableSize;
int tableSize = 0;
/// The tail of this VTable. It is used to share the same VTable between
/// The tail of this VTable. It is used to share the same VTable between
/// multiple tables of identical structure.
int tail;
int tail = 0;
int get _vTableSize => numOfUint16 * _sizeofUint16;
@@ -1209,8 +1211,7 @@ class _VTable {
bool _offsetsMatch(int vt2Start, ByteData buf) {
for (int i = 0; i < fieldOffsets.length; i++) {
if (fieldOffsets[i] !=
buf.getUint16(
vt2Start + _metadataLength + (2 * i), Endian.little)) {
buf.getUint16(vt2Start + _metadataLength + (2 * i), Endian.little)) {
return false;
}
}
@@ -1220,7 +1221,7 @@ class _VTable {
/// Fill the [fieldOffsets] field.
void computeFieldOffsets(int tableTail) {
assert(fieldOffsets.isEmpty);
for (int fieldTail in fieldTails) {
for (int? fieldTail in fieldTails) {
int fieldOffset = fieldTail == null ? 0 : tableTail - fieldTail;
fieldOffsets.add(fieldOffset);
}

View File

@@ -6,37 +6,26 @@ import 'types.dart';
/// The main builder class for creation of a FlexBuffer.
class Builder {
ByteData _buffer;
List<_StackValue> _stack;
List<_StackPointer> _stackPointers;
int _offset;
bool _finished;
Map<String, _StackValue> _stringCache;
Map<String, _StackValue> _keyCache;
Map<_KeysHash, _StackValue> _keyVectorCache;
Map<int, _StackValue> _indirectIntCache;
Map<double, _StackValue> _indirectDoubleCache;
List<_StackValue> _stack = [];
List<_StackPointer> _stackPointers = [];
int _offset = 0;
bool _finished = false;
Map<String, _StackValue> _stringCache = {};
Map<String, _StackValue> _keyCache = {};
Map<_KeysHash, _StackValue> _keyVectorCache = {};
Map<int, _StackValue> _indirectIntCache = {};
Map<double, _StackValue> _indirectDoubleCache = {};
/// Instantiate the builder if you intent to gradually build up the buffer by calling
/// add... methods and calling [finish] to receive the the resulting byte array.
///
/// The default size of internal buffer is set to 2048. Provide a different value in order to avoid buffer copies.
Builder({int size = 2048}) {
_buffer = ByteData(size);
_stack = [];
_stackPointers = [];
_offset = 0;
_finished = false;
_stringCache = {};
_keyCache = {};
_keyVectorCache = {};
_indirectIntCache = {};
_indirectDoubleCache = {};
}
Builder({int size = 2048}) : _buffer = ByteData(size) {}
/// Use this method in order to turn an object into a FlexBuffer directly.
///
/// Use the manual instantiation of the [Builder] and gradual addition of values, if performance is more important than convenience.
static ByteBuffer buildFromObject(Object value) {
static ByteBuffer buildFromObject(Object? value) {
final builder = Builder();
builder._add(value);
final buffer = builder.finish();
@@ -45,7 +34,7 @@ class Builder {
return byteData.buffer;
}
void _add(Object value) {
void _add(Object? value) {
if (value == null) {
addNull();
} else if (value is bool) {
@@ -106,7 +95,7 @@ class Builder {
void addString(String value) {
_integrityCheckOnValueAddition();
if (_stringCache.containsKey(value)) {
_stack.add(_stringCache[value]);
_stack.add(_stringCache[value]!);
return;
}
final utf8String = utf8.encode(value);
@@ -118,7 +107,8 @@ class Builder {
final newOffset = _newOffset(length + 1);
_pushBuffer(utf8String);
_offset = newOffset;
final stackValue = _StackValue.WithOffset(stringOffset, ValueType.String, bitWidth);
final stackValue =
_StackValue.WithOffset(stringOffset, ValueType.String, bitWidth);
_stack.add(stackValue);
_stringCache[value] = stackValue;
}
@@ -129,7 +119,7 @@ class Builder {
void addKey(String value) {
_integrityCheckOnKeyAddition();
if (_keyCache.containsKey(value)) {
_stack.add(_keyCache[value]);
_stack.add(_keyCache[value]!);
return;
}
final utf8String = utf8.encode(value);
@@ -138,7 +128,8 @@ class Builder {
final newOffset = _newOffset(length + 1);
_pushBuffer(utf8String);
_offset = newOffset;
final stackValue = _StackValue.WithOffset(keyOffset, ValueType.Key, BitWidth.width8);
final stackValue =
_StackValue.WithOffset(keyOffset, ValueType.Key, BitWidth.width8);
_stack.add(stackValue);
_keyCache[value] = stackValue;
}
@@ -156,7 +147,8 @@ class Builder {
final newOffset = _newOffset(length);
_pushBuffer(value.asUint8List());
_offset = newOffset;
final stackValue = _StackValue.WithOffset(blobOffset, ValueType.Blob, bitWidth);
final stackValue =
_StackValue.WithOffset(blobOffset, ValueType.Blob, bitWidth);
_stack.add(stackValue);
}
@@ -169,7 +161,7 @@ class Builder {
void addIntIndirectly(int value, {bool cache = false}) {
_integrityCheckOnValueAddition();
if (_indirectIntCache.containsKey(value)) {
_stack.add(_indirectIntCache[value]);
_stack.add(_indirectIntCache[value]!);
return;
}
final stackValue = _StackValue.WithInt(value);
@@ -177,7 +169,8 @@ class Builder {
final newOffset = _newOffset(byteWidth);
final valueOffset = _offset;
_pushBuffer(stackValue.asU8List(stackValue.width));
final stackOffset = _StackValue.WithOffset(valueOffset, ValueType.IndirectInt, stackValue.width);
final stackOffset = _StackValue.WithOffset(
valueOffset, ValueType.IndirectInt, stackValue.width);
_stack.add(stackOffset);
_offset = newOffset;
if (cache) {
@@ -193,7 +186,7 @@ class Builder {
void addDoubleIndirectly(double value, {bool cache = false}) {
_integrityCheckOnValueAddition();
if (cache && _indirectDoubleCache.containsKey(value)) {
_stack.add(_indirectDoubleCache[value]);
_stack.add(_indirectDoubleCache[value]!);
return;
}
final stackValue = _StackValue.WithDouble(value);
@@ -201,7 +194,8 @@ class Builder {
final newOffset = _newOffset(byteWidth);
final valueOffset = _offset;
_pushBuffer(stackValue.asU8List(stackValue.width));
final stackOffset = _StackValue.WithOffset(valueOffset, ValueType.IndirectFloat, stackValue.width);
final stackOffset = _StackValue.WithOffset(
valueOffset, ValueType.IndirectFloat, stackValue.width);
_stack.add(stackOffset);
_offset = newOffset;
if (cache) {
@@ -258,8 +252,10 @@ class Builder {
tmp._offset = _offset;
tmp._stack = List.from(_stack);
tmp._stackPointers = List.from(_stackPointers);
tmp._buffer.buffer.asUint8List().setAll(0, _buffer.buffer.asUint8List(0, _offset));
for (var i = 0; i < tmp._stackPointers.length; i++){
tmp._buffer.buffer
.asUint8List()
.setAll(0, _buffer.buffer.asUint8List(0, _offset));
for (var i = 0; i < tmp._stackPointers.length; i++) {
tmp.end();
}
final buffer = tmp.finish();
@@ -267,14 +263,15 @@ class Builder {
bd.buffer.asUint8List().setAll(0, buffer);
return bd.buffer;
}
void _integrityCheckOnValueAddition() {
if (_finished) {
throw StateError('Adding values after finish is prohibited');
}
if (_stackPointers.isNotEmpty && _stackPointers.last.isVector == false) {
if (_stack.last.type != ValueType.Key) {
throw StateError('Adding value to a map before adding a key is prohibited');
throw StateError(
'Adding value to a map before adding a key is prohibited');
}
}
}
@@ -290,7 +287,8 @@ class Builder {
void _finish() {
if (_stack.length != 1) {
throw StateError('Stack has to be exactly 1, but is ${_stack.length}. You have to end all started vectors and maps, before calling [finish]');
throw StateError(
'Stack has to be exactly 1, but is ${_stack.length}. You have to end all started vectors and maps, before calling [finish]');
}
final value = _stack[0];
final byteWidth = _align(value.elementWidth(_offset, 0));
@@ -299,8 +297,9 @@ class Builder {
_writeUInt(byteWidth, 1);
_finished = true;
}
_StackValue _createVector(int start, int vecLength, int step, [_StackValue keys]) {
_StackValue _createVector(int start, int vecLength, int step,
[_StackValue? keys]) {
var bitWidth = BitWidthUtil.uwidth(vecLength);
var prefixElements = 1;
if (keys != null) {
@@ -327,7 +326,9 @@ class Builder {
}
}
final byteWidth = _align(bitWidth);
final fix = typed & ValueTypeUtils.isNumber(vectorType) && vecLength >= 2 && vecLength <= 4;
final fix = typed & ValueTypeUtils.isNumber(vectorType) &&
vecLength >= 2 &&
vecLength <= 4;
if (keys != null) {
_writeStackValue(keys, byteWidth);
_writeUInt(1 << keys.width.index, byteWidth);
@@ -348,7 +349,8 @@ class Builder {
return _StackValue.WithOffset(vecOffset, ValueType.Map, bitWidth);
}
if (typed) {
final vType = ValueTypeUtils.toTypedVector(vectorType, fix ? vecLength : 0);
final vType =
ValueTypeUtils.toTypedVector(vectorType, fix ? vecLength : 0);
return _StackValue.WithOffset(vecOffset, vType, bitWidth);
}
return _StackValue.WithOffset(vecOffset, ValueType.Vector, bitWidth);
@@ -363,12 +365,13 @@ class Builder {
void _sortKeysAndEndMap(_StackPointer pointer) {
if (((_stack.length - pointer.stackPosition) & 1) == 1) {
throw StateError('The stack needs to hold key value pairs (even number of elements). Check if you combined [addKey] with add... method calls properly.');
throw StateError(
'The stack needs to hold key value pairs (even number of elements). Check if you combined [addKey] with add... method calls properly.');
}
var sorted = true;
for (var i = pointer.stackPosition; i < _stack.length - 2; i += 2) {
if (_shouldFlip(_stack[i], _stack[i+2])) {
if (_shouldFlip(_stack[i], _stack[i + 2])) {
sorted = false;
break;
}
@@ -394,12 +397,12 @@ class Builder {
}
_endMap(pointer);
}
void _endMap(_StackPointer pointer) {
final vecLength = (_stack.length - pointer.stackPosition) >> 1;
final offsets = <int>[];
for (var i = pointer.stackPosition; i < _stack.length; i += 2) {
offsets.add(_stack[i].offset);
offsets.add(_stack[i].offset!);
}
final keysHash = _KeysHash(offsets);
var keysStackValue;
@@ -409,21 +412,23 @@ class Builder {
keysStackValue = _createVector(pointer.stackPosition, vecLength, 2);
_keyVectorCache[keysHash] = keysStackValue;
}
final vec = _createVector(pointer.stackPosition + 1, vecLength, 2, keysStackValue);
final vec =
_createVector(pointer.stackPosition + 1, vecLength, 2, keysStackValue);
_stack.removeRange(pointer.stackPosition, _stack.length);
_stack.add(vec);
}
bool _shouldFlip(_StackValue v1, _StackValue v2) {
if (v1.type != ValueType.Key || v2.type != ValueType.Key) {
throw StateError('Stack values are not keys $v1 | $v2. Check if you combined [addKey] with add... method calls properly.');
throw StateError(
'Stack values are not keys $v1 | $v2. Check if you combined [addKey] with add... method calls properly.');
}
var c1, c2;
var index = 0;
do {
c1 = _buffer.getUint8(v1.offset + index);
c2 = _buffer.getUint8(v2.offset + index);
c1 = _buffer.getUint8(v1.offset! + index);
c2 = _buffer.getUint8(v2.offset! + index);
if (c2 < c1) return true;
if (c1 < c2) return false;
index += 1;
@@ -440,11 +445,12 @@ class Builder {
void _writeStackValue(_StackValue value, int byteWidth) {
final newOffset = _newOffset(byteWidth);
if (value.isOffset) {
final relativeOffset = _offset - value.offset;
final relativeOffset = _offset - value.offset!;
if (byteWidth == 8 || relativeOffset < (1 << (byteWidth * 8))) {
_writeUInt(relativeOffset, byteWidth);
} else {
throw StateError('Unexpected size $byteWidth. This might be a bug. Please create an issue https://github.com/google/flatbuffers/issues/new');
throw StateError(
'Unexpected size $byteWidth. This might be a bug. Please create an issue https://github.com/google/flatbuffers/issues/new');
}
} else {
_pushBuffer(value.asU8List(BitWidthUtil.fromByteWidth(byteWidth)));
@@ -467,16 +473,13 @@ class Builder {
}
if (prevSize < size) {
final newBuf = ByteData(size);
newBuf.buffer
.asUint8List()
.setAll(0, _buffer.buffer.asUint8List());
newBuf.buffer.asUint8List().setAll(0, _buffer.buffer.asUint8List());
}
return newOffset;
}
void _pushInt(int value, BitWidth width) {
switch (width) {
case BitWidth.width8:
_buffer.setInt8(_offset, value);
break;
@@ -494,7 +497,6 @@ class Builder {
void _pushUInt(int value, BitWidth width) {
switch (width) {
case BitWidth.width8:
_buffer.setUint8(_offset, value);
break;
@@ -516,37 +518,39 @@ class Builder {
}
class _StackValue {
Object _value;
int _offset;
late Object _value;
int? _offset;
ValueType _type;
BitWidth _width;
_StackValue.WithNull() {
_type = ValueType.Null;
_width = BitWidth.width8;
}
_StackValue.WithInt(int value) {
_type = value != null ? ValueType.Int : ValueType.Null;
_width = BitWidthUtil.width(value);
_value = value;
}
_StackValue.WithBool(bool value) {
_type = value != null ? ValueType.Bool : ValueType.Null;
_width = BitWidth.width8;
_value = value;
}
_StackValue.WithDouble(double value) {
_type = value != null ? ValueType.Float : ValueType.Null;
_width = BitWidthUtil.width(value);
_value = value;
}
_StackValue.WithOffset(int value, ValueType type, BitWidth width) {
_offset = value;
_type = type;
_width = width;
}
_StackValue.WithNull()
: _type = ValueType.Null,
_width = BitWidth.width8 {}
_StackValue.WithInt(int value)
: _type = ValueType.Int,
_width = BitWidthUtil.width(value),
_value = value {}
_StackValue.WithBool(bool value)
: _type = ValueType.Bool,
_width = BitWidth.width8,
_value = value {}
_StackValue.WithDouble(double value)
: _type = ValueType.Float,
_width = BitWidthUtil.width(value),
_value = value {}
_StackValue.WithOffset(int value, ValueType type, BitWidth width)
: _offset = value,
_type = type,
_width = width {}
BitWidth storedWidth({BitWidth width = BitWidth.width8}) {
return ValueTypeUtils.isInline(_type) ? BitWidthUtil.max(_width, width) : _width;
return ValueTypeUtils.isInline(_type)
? BitWidthUtil.max(_width, width)
: _width;
}
int storedPackedType({BitWidth width = BitWidth.width8}) {
@@ -555,16 +559,18 @@ class _StackValue {
BitWidth elementWidth(int size, int index) {
if (ValueTypeUtils.isInline(_type)) return _width;
for(var i = 0; i < 4; i++) {
final offset = offsetLoc - _offset!;
for (var i = 0; i < 4; i++) {
final width = 1 << i;
final offsetLoc = size + BitWidthUtil.paddingSize(size, width) + index * width;
final offset = offsetLoc - _offset;
final offsetLoc =
size + BitWidthUtil.paddingSize(size, width) + index * width;
final bitWidth = BitWidthUtil.uwidth(offset);
if (1 << bitWidth.index == width) {
return bitWidth;
}
}
throw StateError('Element is of unknown. Size: $size at index: $index. This might be a bug. Please create an issue https://github.com/google/flatbuffers/issues/new');
throw StateError(
'Element is of unknown. Size: $size at index: $index. This might be a bug. Please create an issue https://github.com/google/flatbuffers/issues/new');
}
List<int> asU8List(BitWidth width) {
@@ -572,30 +578,30 @@ class _StackValue {
if (_type == ValueType.Float) {
if (width == BitWidth.width32) {
final result = ByteData(4);
result.setFloat32(0, _value, Endian.little);
result.setFloat32(0, _value as double, Endian.little);
return result.buffer.asUint8List();
} else {
final result = ByteData(8);
result.setFloat64(0, _value, Endian.little);
result.setFloat64(0, _value as double, Endian.little);
return result.buffer.asUint8List();
}
} else {
switch(width) {
switch (width) {
case BitWidth.width8:
final result = ByteData(1);
result.setInt8(0, _value);
result.setInt8(0, _value as int);
return result.buffer.asUint8List();
case BitWidth.width16:
final result = ByteData(2);
result.setInt16(0, _value, Endian.little);
result.setInt16(0, _value as int, Endian.little);
return result.buffer.asUint8List();
case BitWidth.width32:
final result = ByteData(4);
result.setInt32(0, _value, Endian.little);
result.setInt32(0, _value as int, Endian.little);
return result.buffer.asUint8List();
case BitWidth.width64:
final result = ByteData(8);
result.setInt64(0, _value, Endian.little);
result.setInt64(0, _value as int, Endian.little);
return result.buffer.asUint8List();
}
}
@@ -607,11 +613,12 @@ class _StackValue {
}
if (_type == ValueType.Bool) {
final result = ByteData(1);
result.setInt8(0, _value ? 1 : 0);
result.setInt8(0, _value as bool ? 1 : 0);
return result.buffer.asUint8List();
}
throw StateError('Unexpected type: $_type. This might be a bug. Please create an issue https://github.com/google/flatbuffers/issues/new');
throw StateError(
'Unexpected type: $_type. This might be a bug. Please create an issue https://github.com/google/flatbuffers/issues/new');
}
ValueType get type {
@@ -625,7 +632,8 @@ class _StackValue {
bool get isOffset {
return !ValueTypeUtils.isInline(_type);
}
int get offset => _offset;
int? get offset => _offset;
bool get isFloat32 {
return _type == ValueType.Float && _width == BitWidth.width32;

View File

@@ -11,14 +11,15 @@ class Reference {
final int _offset;
final BitWidth _parentWidth;
final String _path;
int _byteWidth;
ValueType _valueType;
int _length;
final int _byteWidth;
final ValueType _valueType;
int? _length;
Reference._(this._buffer, this._offset, this._parentWidth, int packedType, this._path) {
_byteWidth = 1 << (packedType & 3);
_valueType = ValueTypeUtils.fromInt(packedType >> 2);
}
Reference._(
this._buffer, this._offset, this._parentWidth, int packedType, this._path,
[int? byteWidth, ValueType? valueType])
: _byteWidth = byteWidth ?? 1 << (packedType & 3),
_valueType = valueType ?? ValueTypeUtils.fromInt(packedType >> 2) {}
/// Use this method to access the root value of a FlexBuffer.
static Reference fromBuffer(ByteBuffer buffer) {
@@ -30,31 +31,44 @@ class Reference {
final byteWidth = byteData.getUint8(len - 1);
final packedType = byteData.getUint8(len - 2);
final offset = len - byteWidth - 2;
return Reference._(ByteData.view(buffer), offset, BitWidthUtil.fromByteWidth(byteWidth), packedType, "/");
return Reference._(ByteData.view(buffer), offset,
BitWidthUtil.fromByteWidth(byteWidth), packedType, "/");
}
/// Returns true if the underlying value is null.
bool get isNull => _valueType == ValueType.Null;
/// Returns true if the underlying value can be represented as [num].
bool get isNum => ValueTypeUtils.isNumber(_valueType) || ValueTypeUtils.isIndirectNumber(_valueType);
bool get isNum =>
ValueTypeUtils.isNumber(_valueType) ||
ValueTypeUtils.isIndirectNumber(_valueType);
/// Returns true if the underlying value was encoded as a float (direct or indirect).
bool get isDouble => _valueType == ValueType.Float || _valueType == ValueType.IndirectFloat;
bool get isDouble =>
_valueType == ValueType.Float || _valueType == ValueType.IndirectFloat;
/// Returns true if the underlying value was encoded as an int or uint (direct or indirect).
bool get isInt => isNum && !isDouble;
/// Returns true if the underlying value was encoded as a string or a key.
bool get isString => _valueType == ValueType.String || _valueType == ValueType.Key;
bool get isString =>
_valueType == ValueType.String || _valueType == ValueType.Key;
/// Returns true if the underlying value was encoded as a bool.
bool get isBool => _valueType == ValueType.Bool;
/// Returns true if the underlying value was encoded as a blob.
bool get isBlob => _valueType == ValueType.Blob;
/// Returns true if the underlying value points to a vector.
bool get isVector => ValueTypeUtils.isAVector(_valueType);
/// Returns true if the underlying value points to a map.
bool get isMap => _valueType == ValueType.Map;
/// If this [isBool], returns the bool value. Otherwise, returns null.
bool get boolValue {
if(_valueType == ValueType.Bool) {
bool? get boolValue {
if (_valueType == ValueType.Bool) {
return _readInt(_offset, _parentWidth) != 0;
}
return null;
@@ -63,7 +77,7 @@ class Reference {
/// Returns an [int], if the underlying value can be represented as an int.
///
/// Otherwise returns [null].
int get intValue {
int? get intValue {
if (_valueType == ValueType.Int) {
return _readInt(_offset, _parentWidth);
}
@@ -82,7 +96,7 @@ class Reference {
/// Returns [double], if the underlying value [isDouble].
///
/// Otherwise returns [null].
double get doubleValue {
double? get doubleValue {
if (_valueType == ValueType.Float) {
return _readFloat(_offset, _parentWidth);
}
@@ -95,12 +109,12 @@ class Reference {
/// Returns [num], if the underlying value is numeric, be it int uint, or float (direct or indirect).
///
/// Otherwise returns [null].
num get numValue => doubleValue ?? intValue;
num? get numValue => doubleValue ?? intValue;
/// Returns [String] value or null otherwise.
///
/// This method performers a utf8 decoding, as FlexBuffers format stores strings in utf8 encoding.
String get stringValue {
///
/// This method performers a utf8 decoding, as FlexBuffers format stores strings in utf8 encoding.
String? get stringValue {
if (_valueType == ValueType.String || _valueType == ValueType.Key) {
return utf8.decode(_buffer.buffer.asUint8List(_indirect, length));
}
@@ -108,7 +122,7 @@ class Reference {
}
/// Returns [Uint8List] value or null otherwise.
Uint8List get blobValue {
Uint8List? get blobValue {
if (_valueType == ValueType.Blob) {
return _buffer.buffer.asUint8List(_indirect, length);
}
@@ -122,22 +136,31 @@ class Reference {
Reference operator [](Object key) {
if (key is int && ValueTypeUtils.isAVector(_valueType)) {
final index = key;
if(index >= length || index < 0) {
throw ArgumentError('Key: [$key] is not applicable on: $_path of: $_valueType length: $length');
if (index >= length || index < 0) {
throw ArgumentError(
'Key: [$key] is not applicable on: $_path of: $_valueType length: $length');
}
final elementOffset = _indirect + index * _byteWidth;
final reference = Reference._(_buffer, elementOffset, BitWidthUtil.fromByteWidth(_byteWidth), 0, "$_path[$index]");
reference._byteWidth = 1;
int packedType = 0;
int? byteWidth;
ValueType? valueType;
if (ValueTypeUtils.isTypedVector(_valueType)) {
reference._valueType = ValueTypeUtils.typedVectorElementType(_valueType);
return reference;
byteWidth = 1;
valueType = ValueTypeUtils.typedVectorElementType(_valueType);
} else if (ValueTypeUtils.isFixedTypedVector(_valueType)) {
byteWidth = 1;
valueType = ValueTypeUtils.fixedTypedVectorElementType(_valueType);
} else {
packedType = _buffer.getUint8(_indirect + length * _byteWidth + index);
}
if(ValueTypeUtils.isFixedTypedVector(_valueType)) {
reference._valueType = ValueTypeUtils.fixedTypedVectorElementType(_valueType);
return reference;
}
final packedType = _buffer.getUint8(_indirect + length * _byteWidth + index);
return Reference._(_buffer, elementOffset, BitWidthUtil.fromByteWidth(_byteWidth), packedType, "$_path[$index]");
return Reference._(
_buffer,
elementOffset,
BitWidthUtil.fromByteWidth(_byteWidth),
packedType,
"$_path[$index]",
byteWidth,
valueType);
}
if (key is String && _valueType == ValueType.Map) {
final index = _keyIndex(key);
@@ -145,13 +168,14 @@ class Reference {
return _valueForIndexWithKey(index, key);
}
}
throw ArgumentError('Key: [$key] is not applicable on: $_path of: $_valueType');
throw ArgumentError(
'Key: [$key] is not applicable on: $_path of: $_valueType');
}
/// Get an iterable if the underlying flexBuffer value is a vector.
/// Otherwise throws an exception.
Iterable<Reference> get vectorIterable {
if(isVector == false) {
if (isVector == false) {
throw UnsupportedError('Value is not a vector. It is: $_valueType');
}
return _VectorIterator(this);
@@ -160,7 +184,7 @@ class Reference {
/// Get an iterable for keys if the underlying flexBuffer value is a map.
/// Otherwise throws an exception.
Iterable<String> get mapKeyIterable {
if(isMap == false) {
if (isMap == false) {
throw UnsupportedError('Value is not a map. It is: $_valueType');
}
return _MapKeyIterator(this);
@@ -169,7 +193,7 @@ class Reference {
/// Get an iterable for values if the underlying flexBuffer value is a map.
/// Otherwise throws an exception.
Iterable<Reference> get mapValueIterable {
if(isMap == false) {
if (isMap == false) {
throw UnsupportedError('Value is not a map. It is: $_valueType');
}
return _MapValueIterator(this);
@@ -181,59 +205,62 @@ class Reference {
/// If the underlying value is a vector, or map, the length reflects number of elements / element pairs.
/// If the values is a string or a blob, the length reflects a number of bytes the value occupies (strings are encoded in utf8 format).
int get length {
if (_length != null) {
return _length;
}
// needs to be checked before more generic isAVector
if(ValueTypeUtils.isFixedTypedVector(_valueType)) {
_length = ValueTypeUtils.fixedTypedVectorElementSize(_valueType);
} else if(_valueType == ValueType.Blob || ValueTypeUtils.isAVector(_valueType) || _valueType == ValueType.Map){
_length = _readUInt(_indirect - _byteWidth, BitWidthUtil.fromByteWidth(_byteWidth));
} else if (_valueType == ValueType.Null) {
_length = 0;
} else if (_valueType == ValueType.String) {
final indirect = _indirect;
var size_byte_width = _byteWidth;
var size = _readUInt(indirect - size_byte_width, BitWidthUtil.fromByteWidth(size_byte_width));
while (_buffer.getInt8(indirect + size) != 0) {
size_byte_width <<= 1;
size = _readUInt(indirect - size_byte_width, BitWidthUtil.fromByteWidth(size_byte_width));
if (_length == null) {
// needs to be checked before more generic isAVector
if (ValueTypeUtils.isFixedTypedVector(_valueType)) {
_length = ValueTypeUtils.fixedTypedVectorElementSize(_valueType);
} else if (_valueType == ValueType.Blob ||
ValueTypeUtils.isAVector(_valueType) ||
_valueType == ValueType.Map) {
_length = _readUInt(
_indirect - _byteWidth, BitWidthUtil.fromByteWidth(_byteWidth));
} else if (_valueType == ValueType.Null) {
_length = 0;
} else if (_valueType == ValueType.String) {
final indirect = _indirect;
var size_byte_width = _byteWidth;
var size = _readUInt(indirect - size_byte_width,
BitWidthUtil.fromByteWidth(size_byte_width));
while (_buffer.getInt8(indirect + size) != 0) {
size_byte_width <<= 1;
size = _readUInt(indirect - size_byte_width,
BitWidthUtil.fromByteWidth(size_byte_width));
}
_length = size;
} else if (_valueType == ValueType.Key) {
final indirect = _indirect;
var size = 1;
while (_buffer.getInt8(indirect + size) != 0) {
size += 1;
}
_length = size;
} else {
_length = 1;
}
_length = size;
} else if (_valueType == ValueType.Key) {
final indirect = _indirect;
var size = 1;
while (_buffer.getInt8(indirect + size) != 0) {
size += 1;
}
_length = size;
} else {
_length = 1;
}
return _length;
return _length!;
}
/// Returns a minified JSON representation of the underlying FlexBuffer value.
///
/// This method involves materializing the entire object tree, which may be
/// expensive. It is more efficient to work with [Reference] and access only the needed data.
/// Blob values are represented as base64 encoded string.
String get json {
if(_valueType == ValueType.Bool) {
return boolValue ? 'true' : 'false';
if (_valueType == ValueType.Bool) {
return boolValue! ? 'true' : 'false';
}
if (_valueType == ValueType.Null) {
return 'null';
}
if(ValueTypeUtils.isNumber(_valueType)) {
if (ValueTypeUtils.isNumber(_valueType)) {
return jsonEncode(numValue);
}
if (_valueType == ValueType.String) {
return jsonEncode(stringValue);
}
if (_valueType == ValueType.Blob) {
return jsonEncode(base64Encode(blobValue));
return jsonEncode(base64Encode(blobValue!));
}
if (ValueTypeUtils.isAVector(_valueType)) {
final result = StringBuffer();
@@ -261,7 +288,8 @@ class Reference {
result.write('}');
return result.toString();
}
throw UnsupportedError('Type: $_valueType is not supported for JSON conversion');
throw UnsupportedError(
'Type: $_valueType is not supported for JSON conversion');
}
/// Computes the indirect offset of the value.
@@ -316,16 +344,20 @@ class Reference {
}
void _validateOffset(int offset, BitWidth width) {
if (_offset < 0 || _buffer.lengthInBytes <= offset + width.index || offset & (BitWidthUtil.toByteWidth(width) - 1) != 0) {
if (_offset < 0 ||
_buffer.lengthInBytes <= offset + width.index ||
offset & (BitWidthUtil.toByteWidth(width) - 1) != 0) {
throw StateError('Bad offset: $offset, width: $width');
}
}
int _keyIndex(String key) {
int? _keyIndex(String key) {
final input = utf8.encode(key);
final keysVectorOffset = _indirect - _byteWidth * 3;
final indirectOffset = keysVectorOffset - _readUInt(keysVectorOffset, BitWidthUtil.fromByteWidth(_byteWidth));
final byteWidth = _readUInt(keysVectorOffset + _byteWidth, BitWidthUtil.fromByteWidth(_byteWidth));
final indirectOffset = keysVectorOffset -
_readUInt(keysVectorOffset, BitWidthUtil.fromByteWidth(_byteWidth));
final byteWidth = _readUInt(
keysVectorOffset + _byteWidth, BitWidthUtil.fromByteWidth(_byteWidth));
var low = 0;
var high = length - 1;
while (low <= high) {
@@ -341,9 +373,11 @@ class Reference {
return null;
}
int _diffKeys(List<int> input, int index, int indirect_offset, int byteWidth) {
int _diffKeys(
List<int> input, int index, int indirect_offset, int byteWidth) {
final keyOffset = indirect_offset + index * byteWidth;
final keyIndirectOffset = keyOffset - _readUInt(keyOffset, BitWidthUtil.fromByteWidth(byteWidth));
final keyIndirectOffset =
keyOffset - _readUInt(keyOffset, BitWidthUtil.fromByteWidth(byteWidth));
for (var i = 0; i < input.length; i++) {
final dif = input[i] - _buffer.getUint8(keyIndirectOffset + i);
if (dif != 0) {
@@ -357,38 +391,42 @@ class Reference {
final indirect = _indirect;
final elementOffset = indirect + index * _byteWidth;
final packedType = _buffer.getUint8(indirect + length * _byteWidth + index);
return Reference._(_buffer, elementOffset, BitWidthUtil.fromByteWidth(_byteWidth), packedType, "$_path/$key");
return Reference._(_buffer, elementOffset,
BitWidthUtil.fromByteWidth(_byteWidth), packedType, "$_path/$key");
}
Reference _valueForIndex(int index) {
final indirect = _indirect;
final elementOffset = indirect + index * _byteWidth;
final packedType = _buffer.getUint8(indirect + length * _byteWidth + index);
return Reference._(_buffer, elementOffset, BitWidthUtil.fromByteWidth(_byteWidth), packedType, "$_path/[$index]");
return Reference._(_buffer, elementOffset,
BitWidthUtil.fromByteWidth(_byteWidth), packedType, "$_path/[$index]");
}
String _keyForIndex(int index) {
final keysVectorOffset = _indirect - _byteWidth * 3;
final indirectOffset = keysVectorOffset - _readUInt(keysVectorOffset, BitWidthUtil.fromByteWidth(_byteWidth));
final byteWidth = _readUInt(keysVectorOffset + _byteWidth, BitWidthUtil.fromByteWidth(_byteWidth));
final indirectOffset = keysVectorOffset -
_readUInt(keysVectorOffset, BitWidthUtil.fromByteWidth(_byteWidth));
final byteWidth = _readUInt(
keysVectorOffset + _byteWidth, BitWidthUtil.fromByteWidth(_byteWidth));
final keyOffset = indirectOffset + index * byteWidth;
final keyIndirectOffset = keyOffset - _readUInt(keyOffset, BitWidthUtil.fromByteWidth(byteWidth));
final keyIndirectOffset =
keyOffset - _readUInt(keyOffset, BitWidthUtil.fromByteWidth(byteWidth));
var length = 0;
while (_buffer.getUint8(keyIndirectOffset + length) != 0) {
length += 1;
}
return utf8.decode(_buffer.buffer.asUint8List(keyIndirectOffset, length));
}
}
class _VectorIterator with IterableMixin<Reference> implements Iterator<Reference> {
class _VectorIterator
with IterableMixin<Reference>
implements Iterator<Reference> {
final Reference _vector;
int index;
int index = -1;
_VectorIterator(this._vector) {
index = -1;
}
_VectorIterator(this._vector);
@override
Reference get current => _vector[index];
@@ -405,11 +443,9 @@ class _VectorIterator with IterableMixin<Reference> implements Iterator<Referenc
class _MapKeyIterator with IterableMixin<String> implements Iterator<String> {
final Reference _map;
int index;
int index = -1;
_MapKeyIterator(this._map) {
index = -1;
}
_MapKeyIterator(this._map);
@override
String get current => _map._keyForIndex(index);
@@ -424,13 +460,13 @@ class _MapKeyIterator with IterableMixin<String> implements Iterator<String> {
Iterator<String> get iterator => this;
}
class _MapValueIterator with IterableMixin<Reference> implements Iterator<Reference> {
class _MapValueIterator
with IterableMixin<Reference>
implements Iterator<Reference> {
final Reference _map;
int index;
int index = -1;
_MapValueIterator(this._map) {
index = -1;
}
_MapValueIterator(this._map);
@override
Reference get current => _map._valueForIndex(index);

View File

@@ -1,17 +1,13 @@
import 'dart:typed_data';
/// Represents the number of bits a value occupies.
enum BitWidth {
width8,
width16,
width32,
width64
}
enum BitWidth { width8, width16, width32, width64 }
class BitWidthUtil {
static int toByteWidth(BitWidth self) {
return 1 << self.index;
}
static BitWidth width(num value) {
if (value.toInt() == value) {
var v = value.toInt().abs();
@@ -20,8 +16,11 @@ class BitWidthUtil {
if (v >> 31 == 0) return BitWidth.width32;
return BitWidth.width64;
}
return value == _toF32(value) ? BitWidth.width32 : BitWidth.width64;
return value == _toF32(value as double)
? BitWidth.width32
: BitWidth.width64;
}
static BitWidth uwidth(num value) {
if (value.toInt() == value) {
var v = value.toInt().abs();
@@ -30,8 +29,11 @@ class BitWidthUtil {
if (v >> 32 == 0) return BitWidth.width32;
return BitWidth.width64;
}
return value == _toF32(value) ? BitWidth.width32 : BitWidth.width64;
return value == _toF32(value as double)
? BitWidth.width32
: BitWidth.width64;
}
static BitWidth fromByteWidth(int value) {
if (value == 1) {
return BitWidth.width8;
@@ -47,9 +49,11 @@ class BitWidthUtil {
}
throw Exception('Unexpected value ${value}');
}
static int paddingSize(int bufSize, int scalarSize) {
return (~bufSize + 1) & (scalarSize - 1);
}
static double _toF32(double value) {
var bdata = ByteData(4);
bdata.setFloat32(0, value);
@@ -66,15 +70,36 @@ class BitWidthUtil {
/// Represents all internal FlexBuffer types.
enum ValueType {
Null, Int, UInt, Float,
Key, String, IndirectInt, IndirectUInt, IndirectFloat,
Map, Vector, VectorInt, VectorUInt, VectorFloat, VectorKey,
@Deprecated('VectorString is deprecated due to a flaw in the binary format (https://github.com/google/flatbuffers/issues/5627)')
Null,
Int,
UInt,
Float,
Key,
String,
IndirectInt,
IndirectUInt,
IndirectFloat,
Map,
Vector,
VectorInt,
VectorUInt,
VectorFloat,
VectorKey,
@Deprecated(
'VectorString is deprecated due to a flaw in the binary format (https://github.com/google/flatbuffers/issues/5627)')
VectorString,
VectorInt2, VectorUInt2, VectorFloat2,
VectorInt3, VectorUInt3, VectorFloat3,
VectorInt4, VectorUInt4, VectorFloat4,
Blob, Bool, VectorBool
VectorInt2,
VectorUInt2,
VectorFloat2,
VectorInt3,
VectorUInt3,
VectorFloat3,
VectorInt4,
VectorUInt4,
VectorFloat4,
Blob,
Bool,
VectorBool
}
class ValueTypeUtils {
@@ -89,71 +114,70 @@ class ValueTypeUtils {
}
static bool isInline(ValueType self) {
return self == ValueType.Bool
|| toInt(self) <= toInt(ValueType.Float);
return self == ValueType.Bool || toInt(self) <= toInt(ValueType.Float);
}
static bool isNumber(ValueType self) {
return toInt(self) >= toInt(ValueType.Int)
&& toInt(self) <= toInt(ValueType.Float);
return toInt(self) >= toInt(ValueType.Int) &&
toInt(self) <= toInt(ValueType.Float);
}
static bool isIndirectNumber(ValueType self) {
return toInt(self) >= toInt(ValueType.IndirectInt)
&& toInt(self) <= toInt(ValueType.IndirectFloat);
return toInt(self) >= toInt(ValueType.IndirectInt) &&
toInt(self) <= toInt(ValueType.IndirectFloat);
}
static bool isTypedVectorElement(ValueType self) {
return self == ValueType.Bool ||
(
toInt(self) >= toInt(ValueType.Int)
&& toInt(self) <= toInt(ValueType.String)
);
(toInt(self) >= toInt(ValueType.Int) &&
toInt(self) <= toInt(ValueType.String));
}
static bool isTypedVector(ValueType self) {
return self == ValueType.VectorBool ||
(
toInt(self) >= toInt(ValueType.VectorInt)
&& toInt(self) <= toInt(ValueType.VectorString)
);
(toInt(self) >= toInt(ValueType.VectorInt) &&
toInt(self) <= toInt(ValueType.VectorString));
}
static bool isFixedTypedVector(ValueType self) {
return (
toInt(self) >= toInt(ValueType.VectorInt2)
&& toInt(self) <= toInt(ValueType.VectorFloat4)
);
return (toInt(self) >= toInt(ValueType.VectorInt2) &&
toInt(self) <= toInt(ValueType.VectorFloat4));
}
static bool isAVector(ValueType self) {
return (
isTypedVector(self) || isFixedTypedVector(self) || self == ValueType.Vector
);
return (isTypedVector(self) ||
isFixedTypedVector(self) ||
self == ValueType.Vector);
}
static ValueType toTypedVector(ValueType self, int length) {
if (length == 0) {
return ValueTypeUtils.fromInt(toInt(self) - toInt(ValueType.Int) + toInt(ValueType.VectorInt));
return ValueTypeUtils.fromInt(
toInt(self) - toInt(ValueType.Int) + toInt(ValueType.VectorInt));
}
if (length == 2) {
return ValueTypeUtils.fromInt(toInt(self) - toInt(ValueType.Int) + toInt(ValueType.VectorInt2));
return ValueTypeUtils.fromInt(
toInt(self) - toInt(ValueType.Int) + toInt(ValueType.VectorInt2));
}
if (length == 3) {
return ValueTypeUtils.fromInt(toInt(self) - toInt(ValueType.Int) + toInt(ValueType.VectorInt3));
return ValueTypeUtils.fromInt(
toInt(self) - toInt(ValueType.Int) + toInt(ValueType.VectorInt3));
}
if (length == 4) {
return ValueTypeUtils.fromInt(toInt(self) - toInt(ValueType.Int) + toInt(ValueType.VectorInt4));
return ValueTypeUtils.fromInt(
toInt(self) - toInt(ValueType.Int) + toInt(ValueType.VectorInt4));
}
throw Exception('unexpected length ' + length.toString());
}
static ValueType typedVectorElementType(ValueType self) {
return ValueTypeUtils.fromInt(toInt(self) - toInt(ValueType.VectorInt) + toInt(ValueType.Int));
return ValueTypeUtils.fromInt(
toInt(self) - toInt(ValueType.VectorInt) + toInt(ValueType.Int));
}
static ValueType fixedTypedVectorElementType(ValueType self) {
return ValueTypeUtils.fromInt((toInt(self) - toInt(ValueType.VectorInt2)) % 3 + toInt(ValueType.Int));
return ValueTypeUtils.fromInt(
(toInt(self) - toInt(ValueType.VectorInt2)) % 3 + toInt(ValueType.Int));
}
static int fixedTypedVectorElementSize(ValueType self) {

View File

@@ -13,8 +13,8 @@ authors:
homepage: https://github.com/google/flatbuffers
documentation: https://google.github.io/flatbuffers/index.html
dev_dependencies:
test: ^1.3.0
test_reflective_loader: ^0.1.4
path: ^1.5.1
test: ^1.17.7
test_reflective_loader: ^0.2.0
path: ^1.8.0
environment:
sdk: '>=2.0.0-dev.28.0 <3.0.0'
sdk: '>=2.12.0 <3.0.0'

View File

@@ -39,26 +39,26 @@ class CheckOtherLangaugesData {
expect(mon.hp, 80);
expect(mon.mana, 150);
expect(mon.name, 'MyMonster');
expect(mon.pos.x, 1.0);
expect(mon.pos.y, 2.0);
expect(mon.pos.z, 3.0);
expect(mon.pos.test1, 3.0);
expect(mon.pos.test2.value, 2.0);
expect(mon.pos.test3.a, 5);
expect(mon.pos.test3.b, 6);
expect(mon.testType.value, example.AnyTypeId.Monster.value);
expect(mon.pos!.x, 1.0);
expect(mon.pos!.y, 2.0);
expect(mon.pos!.z, 3.0);
expect(mon.pos!.test1, 3.0);
expect(mon.pos!.test2.value, 2.0);
expect(mon.pos!.test3.a, 5);
expect(mon.pos!.test3.b, 6);
expect(mon.testType!.value, example.AnyTypeId.Monster.value);
expect(mon.test is example.Monster, true);
final monster2 = mon.test as example.Monster;
expect(monster2.name, "Fred");
expect(mon.inventory.length, 5);
expect(mon.inventory.reduce((cur, next) => cur + next), 10);
expect(mon.test4.length, 2);
expect(
mon.test4[0].a + mon.test4[0].b + mon.test4[1].a + mon.test4[1].b, 100);
expect(mon.testarrayofstring.length, 2);
expect(mon.testarrayofstring[0], "test1");
expect(mon.testarrayofstring[1], "test2");
expect(mon.inventory!.length, 5);
expect(mon.inventory!.reduce((cur, next) => cur + next), 10);
final test4 = mon.test4!;
expect(test4.length, 2);
expect(test4[0].a + test4[0].b + test4[1].a + test4[1].b, 100);
expect(mon.testarrayofstring!.length, 2);
expect(mon.testarrayofstring![0], "test1");
expect(mon.testarrayofstring![1], "test2");
// this will fail if accessing any field fails.
expect(
@@ -68,7 +68,7 @@ class CheckOtherLangaugesData {
'mana: 150, hp: 80, name: MyMonster, inventory: [0, 1, 2, 3, 4], '
'color: Color{value: 8}, testType: AnyTypeId{value: 1}, '
'test: Monster{pos: null, mana: 150, hp: 100, name: Fred, '
'inventory: null, color: Color{value: 8}, testType: AnyTypeId{value: 0}, '
'inventory: null, color: Color{value: 8}, testType: null, '
'test: null, test4: null, testarrayofstring: null, '
'testarrayoftables: null, enemy: null, testnestedflatbuffer: null, '
'testempty: null, testbool: false, testhashs32Fnv1: 0, '
@@ -82,14 +82,13 @@ class CheckOtherLangaugesData {
'vectorOfWeakReferences: null, vectorOfStrongReferrables: null, '
'coOwningReference: 0, vectorOfCoOwningReferences: null, '
'nonOwningReference: 0, vectorOfNonOwningReferences: null, '
'anyUniqueType: AnyUniqueAliasesTypeId{value: 0}, anyUnique: null, '
'anyAmbiguousType: AnyAmbiguousAliasesTypeId{value: 0}, '
'anyUniqueType: null, anyUnique: null, anyAmbiguousType: null, '
'anyAmbiguous: null, vectorOfEnums: null, signedEnum: Race{value: -1}, '
'testrequirednestedflatbuffer: null, scalarKeySortedTables: null}, '
'test4: [Test{a: 10, b: 20}, Test{a: 30, b: 40}], '
'testarrayofstring: [test1, test2], testarrayoftables: null, '
'enemy: Monster{pos: null, mana: 150, hp: 100, name: Fred, '
'inventory: null, color: Color{value: 8}, testType: AnyTypeId{value: 0}, '
'inventory: null, color: Color{value: 8}, testType: null, '
'test: null, test4: null, testarrayofstring: null, '
'testarrayoftables: null, enemy: null, testnestedflatbuffer: null, '
'testempty: null, testbool: false, testhashs32Fnv1: 0, '
@@ -103,8 +102,7 @@ class CheckOtherLangaugesData {
'vectorOfWeakReferences: null, vectorOfStrongReferrables: null, '
'coOwningReference: 0, vectorOfCoOwningReferences: null, '
'nonOwningReference: 0, vectorOfNonOwningReferences: null, '
'anyUniqueType: AnyUniqueAliasesTypeId{value: 0}, anyUnique: null, '
'anyAmbiguousType: AnyAmbiguousAliasesTypeId{value: 0}, '
'anyUniqueType: null, anyUnique: null, anyAmbiguousType: null, '
'anyAmbiguous: null, vectorOfEnums: null, signedEnum: Race{value: -1}, '
'testrequirednestedflatbuffer: null, scalarKeySortedTables: null}, '
'testnestedflatbuffer: null, testempty: null, testbool: true, '
@@ -126,8 +124,8 @@ class CheckOtherLangaugesData {
'vectorOfStrongReferrables: null, coOwningReference: 0, '
'vectorOfCoOwningReferences: null, nonOwningReference: 0, '
'vectorOfNonOwningReferences: null, '
'anyUniqueType: AnyUniqueAliasesTypeId{value: 0}, anyUnique: null, '
'anyAmbiguousType: AnyAmbiguousAliasesTypeId{value: 0}, '
'anyUniqueType: null, anyUnique: null, '
'anyAmbiguousType: null, '
'anyAmbiguous: null, vectorOfEnums: null, signedEnum: Race{value: -1}, '
'testrequirednestedflatbuffer: null, scalarKeySortedTables: [Stat{id: '
'miss, val: 0, count: 0}, Stat{id: hit, val: 10, count: 1}]}',
@@ -137,7 +135,7 @@ class CheckOtherLangaugesData {
@reflectiveTest
class BuilderTest {
void test_monsterBuilder([Builder builder]) {
void test_monsterBuilder([Builder? builder]) {
final fbBuilder = builder ?? new Builder();
final str = fbBuilder.writeString('MyMonster');
@@ -183,10 +181,10 @@ class BuilderTest {
fbBuilder.finish(mon);
}
void test_error_addInt32_withoutStartTable([Builder builder]) {
void test_error_addInt32_withoutStartTable([Builder? builder]) {
builder ??= new Builder();
expect(() {
builder.addInt32(0, 0);
builder!.addInt32(0, 0);
}, throwsStateError);
}
@@ -288,7 +286,7 @@ class BuilderTest {
20);
}
void test_table_format([Builder builder]) {
void test_table_format([Builder? builder]) {
Uint8List byteList;
{
builder ??= new Builder(initialSize: 0);
@@ -326,8 +324,8 @@ class BuilderTest {
List<int> byteList;
{
Builder builder = new Builder(initialSize: 0);
int latinStringOffset = builder.writeString(latinString);
int unicodeStringOffset = builder.writeString(unicodeString);
int? latinStringOffset = builder.writeString(latinString);
int? unicodeStringOffset = builder.writeString(unicodeString);
builder.startTable();
builder.addOffset(0, latinStringOffset);
builder.addOffset(1, unicodeStringOffset);
@@ -337,17 +335,21 @@ class BuilderTest {
// read and verify
BufferContext buf = new BufferContext.fromBytes(byteList);
int objectOffset = buf.derefObject(0);
expect(const StringReader().vTableGet(buf, objectOffset, indexToField(0)),
expect(
const StringReader()
.vTableGetNullable(buf, objectOffset, indexToField(0)),
latinString);
expect(const StringReader().vTableGet(buf, objectOffset, indexToField(1)),
expect(
const StringReader()
.vTableGetNullable(buf, objectOffset, indexToField(1)),
unicodeString);
}
void test_table_types([Builder builder]) {
void test_table_types([Builder? builder]) {
List<int> byteList;
{
builder ??= new Builder(initialSize: 0);
int stringOffset = builder.writeString('12345');
int? stringOffset = builder.writeString('12345');
builder.startTable();
builder.addBool(0, true);
builder.addInt8(1, 10);
@@ -363,18 +365,32 @@ class BuilderTest {
BufferContext buf = new BufferContext.fromBytes(byteList);
int objectOffset = buf.derefObject(0);
expect(
const BoolReader().vTableGet(buf, objectOffset, indexToField(0)), true);
const BoolReader()
.vTableGetNullable(buf, objectOffset, indexToField(0)),
true);
expect(
const Int8Reader().vTableGet(buf, objectOffset, indexToField(1)), 10);
const Int8Reader()
.vTableGetNullable(buf, objectOffset, indexToField(1)),
10);
expect(
const Int32Reader().vTableGet(buf, objectOffset, indexToField(2)), 20);
expect(const StringReader().vTableGet(buf, objectOffset, indexToField(3)),
const Int32Reader()
.vTableGetNullable(buf, objectOffset, indexToField(2)),
20);
expect(
const StringReader()
.vTableGetNullable(buf, objectOffset, indexToField(3)),
'12345');
expect(
const Int32Reader().vTableGet(buf, objectOffset, indexToField(4)), 40);
expect(const Uint32Reader().vTableGet(buf, objectOffset, indexToField(5)),
const Int32Reader()
.vTableGetNullable(buf, objectOffset, indexToField(4)),
40);
expect(
const Uint32Reader()
.vTableGetNullable(buf, objectOffset, indexToField(5)),
0x9ABCDEF0);
expect(const Uint8Reader().vTableGet(buf, objectOffset, indexToField(6)),
expect(
const Uint8Reader()
.vTableGetNullable(buf, objectOffset, indexToField(6)),
0x9A);
}
@@ -488,7 +504,7 @@ class BuilderTest {
}
}
void test_writeList_ofObjects([Builder builder]) {
void test_writeList_ofObjects([Builder? builder]) {
List<int> byteList;
{
builder ??= new Builder(initialSize: 0);
@@ -527,9 +543,9 @@ class BuilderTest {
List<int> byteList;
{
Builder builder = new Builder(initialSize: 0);
int str1 = builder.writeString('12345');
int str2 = builder.writeString('ABC');
int offset = builder.writeList([str1, str2]);
int? str1 = builder.writeString('12345');
int? str2 = builder.writeString('ABC');
int offset = builder.writeList([str1!, str2!]);
byteList = builder.finish(offset);
}
// read and verify
@@ -541,12 +557,12 @@ class BuilderTest {
expect(items, contains('ABC'));
}
void test_writeList_ofStrings_inObject([Builder builder]) {
void test_writeList_ofStrings_inObject([Builder? builder]) {
List<int> byteList;
{
builder ??= new Builder(initialSize: 0);
int listOffset = builder.writeList(
[builder.writeString('12345'), builder.writeString('ABC')]);
[builder.writeString('12345')!, builder.writeString('ABC')!]);
builder.startTable();
builder.addOffset(0, listOffset);
int offset = builder.endTable();
@@ -555,7 +571,7 @@ class BuilderTest {
// read and verify
BufferContext buf = new BufferContext.fromBytes(byteList);
StringListWrapperImpl reader = new StringListWrapperReader().read(buf, 0);
List<String> items = reader.items;
List<String>? items = reader.items;
expect(items, hasLength(2));
expect(items, contains('12345'));
expect(items, contains('ABC'));
@@ -605,7 +621,7 @@ class BuilderTest {
void test_reset() {
// We'll run a selection of tests , reusing the builder between them.
final testCases = <void Function(Builder)>[
final testCases = <void Function(Builder?)>[
test_monsterBuilder,
test_error_addInt32_withoutStartTable,
test_table_format,
@@ -624,14 +640,14 @@ class BuilderTest {
// print the order so failures are reproducible
printOnFailure('Running reset() test cases in order: $indexes');
Builder builder;
Builder? builder;
indexes.forEach((index) {
if (builder == null) {
// Initial size small enough so at least one test case increases it.
// On the other hand, it's large enough so that some test cases don't.
builder = Builder(initialSize: 32);
} else {
builder.reset();
builder!.reset();
}
testCases[index](builder);
});
@@ -739,8 +755,8 @@ class StringListWrapperImpl {
StringListWrapperImpl(this.bp, this.offset);
List<String> get items => const ListReader<String>(const StringReader())
.vTableGet(bp, offset, indexToField(0));
List<String>? get items => const ListReader<String>(const StringReader())
.vTableGetNullable(bp, offset, indexToField(0));
}
class StringListWrapperReader extends TableReader<StringListWrapperImpl> {

View File

@@ -58,18 +58,18 @@ void main() {
{
var flx = Builder();
flx.addString('hello 😱');
expect(flx.finish(), [10, 104, 101, 108, 108, 111, 32, 240, 159, 152, 177, 0, 11, 20, 1]);
expect(flx.finish(),
[10, 104, 101, 108, 108, 111, 32, 240, 159, 152, 177, 0, 11, 20, 1]);
}
});
test('build vector', (){
test('build vector', () {
{
var flx = Builder()
..startVector()
..addInt(1)
..addInt(2)
..end()
;
..end();
expect(flx.finish(), [1, 2, 2, 64, 1]);
}
{
@@ -77,8 +77,7 @@ void main() {
..startVector()
..addInt(-1)
..addInt(256)
..end()
;
..end();
expect(flx.finish(), [255, 255, 0, 1, 4, 65, 1]);
}
{
@@ -86,8 +85,7 @@ void main() {
..startVector()
..addInt(-45)
..addInt(256000)
..end()
;
..end();
expect(flx.finish(), [211, 255, 255, 255, 0, 232, 3, 0, 8, 66, 1]);
}
{
@@ -95,9 +93,28 @@ void main() {
..startVector()
..addDouble(1.1)
..addDouble(-256)
..end()
;
expect(flx.finish(), [154, 153, 153, 153, 153, 153, 241, 63, 0, 0, 0, 0, 0, 0, 112, 192, 16, 75, 1]);
..end();
expect(flx.finish(), [
154,
153,
153,
153,
153,
153,
241,
63,
0,
0,
0,
0,
0,
0,
112,
192,
16,
75,
1
]);
}
{
var flx = Builder()
@@ -105,8 +122,7 @@ void main() {
..addInt(1)
..addInt(2)
..addInt(4)
..end()
;
..end();
expect(flx.finish(), [1, 2, 4, 3, 76, 1]);
}
{
@@ -115,19 +131,17 @@ void main() {
..addInt(-1)
..addInt(256)
..addInt(4)
..end()
;
..end();
expect(flx.finish(), [255, 255, 0, 1, 4, 0, 6, 77, 1]);
}
{
var flx = Builder()
..startVector()
..startVector()
..addInt(61)
..end()
..addInt(64)
..startVector()
..addInt(61)
..end()
;
..addInt(64)
..end();
expect(flx.finish(), [1, 61, 2, 2, 64, 44, 4, 4, 40, 1]);
}
{
@@ -136,9 +150,31 @@ void main() {
..addString('foo')
..addString('bar')
..addString('baz')
..end()
;
expect(flx.finish(), [3, 102, 111, 111, 0, 3, 98, 97, 114, 0, 3, 98, 97, 122, 0, 3, 15, 11, 7, 3, 60, 1]);
..end();
expect(flx.finish(), [
3,
102,
111,
111,
0,
3,
98,
97,
114,
0,
3,
98,
97,
122,
0,
3,
15,
11,
7,
3,
60,
1
]);
}
{
var flx = Builder()
@@ -149,9 +185,34 @@ void main() {
..addString('foo')
..addString('bar')
..addString('baz')
..end()
;
expect(flx.finish(), [3, 102, 111, 111, 0, 3, 98, 97, 114, 0, 3, 98, 97, 122, 0, 6, 15, 11, 7, 18, 14, 10, 6, 60, 1]);
..end();
expect(flx.finish(), [
3,
102,
111,
111,
0,
3,
98,
97,
114,
0,
3,
98,
97,
122,
0,
6,
15,
11,
7,
18,
14,
10,
6,
60,
1
]);
}
{
var flx = Builder()
@@ -159,8 +220,7 @@ void main() {
..addBool(true)
..addBool(false)
..addBool(true)
..end()
;
..end();
expect(flx.finish(), [3, 1, 0, 1, 3, 144, 1]);
}
{
@@ -171,29 +231,83 @@ void main() {
..addInt(-5)
..addDouble(1.3)
..addBool(true)
..end()
;
..end();
expect(flx.finish(), [
3, 102, 111, 111, 0, 0, 0, 0,
5, 0, 0, 0, 0, 0, 0, 0,
15, 0, 0, 0, 0, 0, 0, 0,
1, 0, 0, 0, 0, 0, 0, 0,
251, 255, 255, 255, 255, 255, 255, 255,
205, 204, 204, 204, 204, 204, 244, 63,
1, 0, 0, 0, 0, 0, 0, 0,
20, 4, 4, 15, 104, 45, 43, 1]);
3,
102,
111,
111,
0,
0,
0,
0,
5,
0,
0,
0,
0,
0,
0,
0,
15,
0,
0,
0,
0,
0,
0,
0,
1,
0,
0,
0,
0,
0,
0,
0,
251,
255,
255,
255,
255,
255,
255,
255,
205,
204,
204,
204,
204,
204,
244,
63,
1,
0,
0,
0,
0,
0,
0,
0,
20,
4,
4,
15,
104,
45,
43,
1
]);
}
});
test('build map', ()
{
test('build map', () {
{
var flx = Builder()
..startMap()
..addKey('a')
..addInt(12)
..end()
;
..end();
expect(flx.finish(), [97, 0, 1, 3, 1, 1, 1, 12, 4, 2, 36, 1]);
}
{
@@ -203,105 +317,270 @@ void main() {
..addInt(12)
..addKey('')
..addInt(45)
..end()
;
expect(flx.finish(), [97, 0, 0, 2, 2, 5, 2, 1, 2, 45, 12, 4, 4, 4, 36, 1]);
..end();
expect(
flx.finish(), [97, 0, 0, 2, 2, 5, 2, 1, 2, 45, 12, 4, 4, 4, 36, 1]);
}
{
var flx = Builder()
..startVector()
..startMap()
..addKey('something')
..addInt(12)
..end()
..startMap()
..addKey('something')
..addInt(45)
..end()
..startMap()
..addKey('something')
..addInt(12)
..end()
;
expect(flx.finish(), [115, 111, 109, 101, 116, 104, 105, 110, 103, 0,
1, 11, 1, 1, 1, 12, 4, 6, 1, 1, 45, 4, 2, 8, 4, 36, 36, 4, 40, 1]);
..startMap()
..addKey('something')
..addInt(45)
..end()
..end();
expect(flx.finish(), [
115,
111,
109,
101,
116,
104,
105,
110,
103,
0,
1,
11,
1,
1,
1,
12,
4,
6,
1,
1,
45,
4,
2,
8,
4,
36,
36,
4,
40,
1
]);
}
});
test('build blob', ()
{
test('build blob', () {
{
var flx = Builder()
..addBlob(Uint8List.fromList([1, 2, 3]).buffer)
;
var flx = Builder()..addBlob(Uint8List.fromList([1, 2, 3]).buffer);
expect(flx.finish(), [3, 1, 2, 3, 3, 100, 1]);
}
});
test('build from object', (){
expect(Builder.buildFromObject(Uint8List.fromList([1, 2, 3]).buffer).asUint8List(), [3, 1, 2, 3, 3, 100, 1]);
test('build from object', () {
expect(
Builder.buildFromObject(Uint8List.fromList([1, 2, 3]).buffer)
.asUint8List(),
[3, 1, 2, 3, 3, 100, 1]);
expect(Builder.buildFromObject(null).asUint8List(), [0, 0, 1]);
expect(Builder.buildFromObject(true).asUint8List(), [1, 104, 1]);
expect(Builder.buildFromObject(false).asUint8List(), [0, 104, 1]);
expect(Builder.buildFromObject(25).asUint8List(), [25, 4, 1]);
expect(Builder.buildFromObject(-250).asUint8List(), [6, 255, 5, 2]);
expect(Builder.buildFromObject(-2.50).asUint8List(), [0, 0, 32, 192, 14, 4]);
expect(Builder.buildFromObject('Maxim').asUint8List(), [5, 77, 97, 120, 105, 109, 0, 6, 20, 1]);
expect(Builder.buildFromObject([1, 3.3, 'max', true, null, false]).asUint8List(), [
3, 109, 97, 120, 0, 0, 0, 0,
6, 0, 0, 0, 0, 0, 0, 0,
1, 0, 0, 0, 0, 0, 0, 0,
102, 102, 102, 102, 102, 102, 10, 64,
31, 0, 0, 0, 0, 0, 0, 0,
1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0,
4, 15, 20, 104, 0, 104, 54, 43, 1
]);
expect(Builder.buildFromObject([{'something':12}, {'something': 45}]).asUint8List(), [
115, 111, 109, 101, 116, 104, 105, 110, 103, 0,
1, 11, 1, 1, 1, 12, 4, 6, 1, 1, 45, 4, 2, 8, 4, 36, 36, 4, 40, 1
]);
expect(
Builder.buildFromObject(-2.50).asUint8List(), [0, 0, 32, 192, 14, 4]);
expect(Builder.buildFromObject('Maxim').asUint8List(),
[5, 77, 97, 120, 105, 109, 0, 6, 20, 1]);
expect(
Builder.buildFromObject([1, 3.3, 'max', true, null, false])
.asUint8List(),
[
3,
109,
97,
120,
0,
0,
0,
0,
6,
0,
0,
0,
0,
0,
0,
0,
1,
0,
0,
0,
0,
0,
0,
0,
102,
102,
102,
102,
102,
102,
10,
64,
31,
0,
0,
0,
0,
0,
0,
0,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
4,
15,
20,
104,
0,
104,
54,
43,
1
]);
expect(
Builder.buildFromObject([
{'something': 12},
{'something': 45}
]).asUint8List(),
[
115,
111,
109,
101,
116,
104,
105,
110,
103,
0,
1,
11,
1,
1,
1,
12,
4,
6,
1,
1,
45,
4,
2,
8,
4,
36,
36,
4,
40,
1
]);
});
test('add double indirectly', (){
var flx = Builder()
..addDoubleIndirectly(0.1)
;
test('add double indirectly', () {
var flx = Builder()..addDoubleIndirectly(0.1);
expect(flx.finish(), [154, 153, 153, 153, 153, 153, 185, 63, 8, 35, 1]);
});
test('add double indirectly to vector with cache', (){
test('add double indirectly to vector with cache', () {
var flx = Builder()
..startVector()
..addDoubleIndirectly(0.1, cache: true)
..addDoubleIndirectly(0.1, cache: true)
..addDoubleIndirectly(0.1, cache: true)
..addDoubleIndirectly(0.1, cache: true)
..end()
;
expect(flx.finish(), [154, 153, 153, 153, 153, 153, 185, 63,
4, 9, 10, 11, 12, 35, 35, 35, 35, 8, 40, 1]);
..end();
expect(flx.finish(), [
154,
153,
153,
153,
153,
153,
185,
63,
4,
9,
10,
11,
12,
35,
35,
35,
35,
8,
40,
1
]);
});
test('add int indirectly', (){
var flx = Builder()
..addIntIndirectly(2345234523452345)
;
test('add int indirectly', () {
var flx = Builder()..addIntIndirectly(2345234523452345);
expect(flx.finish(), [185, 115, 175, 118, 250, 84, 8, 0, 8, 27, 1]);
});
test('add int indirectly to vector with cache', (){
test('add int indirectly to vector with cache', () {
var flx = Builder()
..startVector()
..addIntIndirectly(2345234523452345, cache: true)
..addIntIndirectly(2345234523452345, cache: true)
..addIntIndirectly(2345234523452345, cache: true)
..addIntIndirectly(2345234523452345, cache: true)
..end()
;
expect(flx.finish(), [185, 115, 175, 118, 250, 84, 8, 0,
4, 9, 10, 11, 12, 27, 27, 27, 27, 8, 40, 1]);
..end();
expect(flx.finish(), [
185,
115,
175,
118,
250,
84,
8,
0,
4,
9,
10,
11,
12,
27,
27,
27,
27,
8,
40,
1
]);
});
test('snapshot', (){
test('snapshot', () {
var flx = Builder();
flx.startVector();
flx.addInt(12);
@@ -312,4 +591,3 @@ void main() {
expect(flx.snapshot().asUint8List(), [12, 24, 45, 3, 76, 1]);
});
}

File diff suppressed because it is too large Load Diff

View File

@@ -48,69 +48,116 @@ void main() {
expect(ValueTypeUtils.isFixedTypedVector(ValueType.VectorInt), isFalse);
});
test('to typed vector', () {
expect(ValueTypeUtils.toTypedVector(ValueType.Int,0), equals(ValueType.VectorInt));
expect(ValueTypeUtils.toTypedVector(ValueType.UInt,0), equals(ValueType.VectorUInt));
expect(ValueTypeUtils.toTypedVector(ValueType.Bool,0), equals(ValueType.VectorBool));
expect(ValueTypeUtils.toTypedVector(ValueType.Float,0), equals(ValueType.VectorFloat));
expect(ValueTypeUtils.toTypedVector(ValueType.Key,0), equals(ValueType.VectorKey));
expect(ValueTypeUtils.toTypedVector(ValueType.String,0), equals(ValueType.VectorString));
expect(ValueTypeUtils.toTypedVector(ValueType.Int, 0),
equals(ValueType.VectorInt));
expect(ValueTypeUtils.toTypedVector(ValueType.UInt, 0),
equals(ValueType.VectorUInt));
expect(ValueTypeUtils.toTypedVector(ValueType.Bool, 0),
equals(ValueType.VectorBool));
expect(ValueTypeUtils.toTypedVector(ValueType.Float, 0),
equals(ValueType.VectorFloat));
expect(ValueTypeUtils.toTypedVector(ValueType.Key, 0),
equals(ValueType.VectorKey));
expect(ValueTypeUtils.toTypedVector(ValueType.String, 0),
equals(ValueType.VectorString));
expect(ValueTypeUtils.toTypedVector(ValueType.Int,2), equals(ValueType.VectorInt2));
expect(ValueTypeUtils.toTypedVector(ValueType.UInt,2), equals(ValueType.VectorUInt2));
expect(ValueTypeUtils.toTypedVector(ValueType.Float,2), equals(ValueType.VectorFloat2));
expect(ValueTypeUtils.toTypedVector(ValueType.Int, 2),
equals(ValueType.VectorInt2));
expect(ValueTypeUtils.toTypedVector(ValueType.UInt, 2),
equals(ValueType.VectorUInt2));
expect(ValueTypeUtils.toTypedVector(ValueType.Float, 2),
equals(ValueType.VectorFloat2));
expect(ValueTypeUtils.toTypedVector(ValueType.Int,3), equals(ValueType.VectorInt3));
expect(ValueTypeUtils.toTypedVector(ValueType.UInt,3), equals(ValueType.VectorUInt3));
expect(ValueTypeUtils.toTypedVector(ValueType.Float,3), equals(ValueType.VectorFloat3));
expect(ValueTypeUtils.toTypedVector(ValueType.Int, 3),
equals(ValueType.VectorInt3));
expect(ValueTypeUtils.toTypedVector(ValueType.UInt, 3),
equals(ValueType.VectorUInt3));
expect(ValueTypeUtils.toTypedVector(ValueType.Float, 3),
equals(ValueType.VectorFloat3));
expect(ValueTypeUtils.toTypedVector(ValueType.Int,4), equals(ValueType.VectorInt4));
expect(ValueTypeUtils.toTypedVector(ValueType.UInt,4), equals(ValueType.VectorUInt4));
expect(ValueTypeUtils.toTypedVector(ValueType.Float,4), equals(ValueType.VectorFloat4));
expect(ValueTypeUtils.toTypedVector(ValueType.Int, 4),
equals(ValueType.VectorInt4));
expect(ValueTypeUtils.toTypedVector(ValueType.UInt, 4),
equals(ValueType.VectorUInt4));
expect(ValueTypeUtils.toTypedVector(ValueType.Float, 4),
equals(ValueType.VectorFloat4));
});
test('typed vector element type', () {
expect(ValueTypeUtils.typedVectorElementType(ValueType.VectorInt), equals(ValueType.Int));
expect(ValueTypeUtils.typedVectorElementType(ValueType.VectorUInt), equals(ValueType.UInt));
expect(ValueTypeUtils.typedVectorElementType(ValueType.VectorFloat), equals(ValueType.Float));
expect(ValueTypeUtils.typedVectorElementType(ValueType.VectorString), equals(ValueType.String));
expect(ValueTypeUtils.typedVectorElementType(ValueType.VectorKey), equals(ValueType.Key));
expect(ValueTypeUtils.typedVectorElementType(ValueType.VectorBool), equals(ValueType.Bool));
expect(ValueTypeUtils.typedVectorElementType(ValueType.VectorInt),
equals(ValueType.Int));
expect(ValueTypeUtils.typedVectorElementType(ValueType.VectorUInt),
equals(ValueType.UInt));
expect(ValueTypeUtils.typedVectorElementType(ValueType.VectorFloat),
equals(ValueType.Float));
expect(ValueTypeUtils.typedVectorElementType(ValueType.VectorString),
equals(ValueType.String));
expect(ValueTypeUtils.typedVectorElementType(ValueType.VectorKey),
equals(ValueType.Key));
expect(ValueTypeUtils.typedVectorElementType(ValueType.VectorBool),
equals(ValueType.Bool));
});
test('fixed typed vector element type', () {
expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorInt2), equals(ValueType.Int));
expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorInt3), equals(ValueType.Int));
expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorInt4), equals(ValueType.Int));
expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorInt2),
equals(ValueType.Int));
expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorInt3),
equals(ValueType.Int));
expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorInt4),
equals(ValueType.Int));
expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorUInt2), equals(ValueType.UInt));
expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorUInt3), equals(ValueType.UInt));
expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorUInt4), equals(ValueType.UInt));
expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorUInt2),
equals(ValueType.UInt));
expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorUInt3),
equals(ValueType.UInt));
expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorUInt4),
equals(ValueType.UInt));
expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorFloat2), equals(ValueType.Float));
expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorFloat3), equals(ValueType.Float));
expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorFloat4), equals(ValueType.Float));
expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorFloat2),
equals(ValueType.Float));
expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorFloat3),
equals(ValueType.Float));
expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorFloat4),
equals(ValueType.Float));
});
test('fixed typed vector element size', () {
expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorInt2), equals(2));
expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorInt3), equals(3));
expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorInt4), equals(4));
expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorInt2),
equals(2));
expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorInt3),
equals(3));
expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorInt4),
equals(4));
expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorUInt2), equals(2));
expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorUInt3), equals(3));
expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorUInt4), equals(4));
expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorUInt2),
equals(2));
expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorUInt3),
equals(3));
expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorUInt4),
equals(4));
expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorFloat2), equals(2));
expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorFloat3), equals(3));
expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorFloat4), equals(4));
expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorFloat2),
equals(2));
expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorFloat3),
equals(3));
expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorFloat4),
equals(4));
});
test('packed type', () {
expect(ValueTypeUtils.packedType(ValueType.Null, BitWidth.width8), equals(0));
expect(ValueTypeUtils.packedType(ValueType.Null, BitWidth.width16), equals(1));
expect(ValueTypeUtils.packedType(ValueType.Null, BitWidth.width32), equals(2));
expect(ValueTypeUtils.packedType(ValueType.Null, BitWidth.width64), equals(3));
expect(
ValueTypeUtils.packedType(ValueType.Null, BitWidth.width8), equals(0));
expect(
ValueTypeUtils.packedType(ValueType.Null, BitWidth.width16), equals(1));
expect(
ValueTypeUtils.packedType(ValueType.Null, BitWidth.width32), equals(2));
expect(
ValueTypeUtils.packedType(ValueType.Null, BitWidth.width64), equals(3));
expect(ValueTypeUtils.packedType(ValueType.Int, BitWidth.width8), equals(4));
expect(ValueTypeUtils.packedType(ValueType.Int, BitWidth.width16), equals(5));
expect(ValueTypeUtils.packedType(ValueType.Int, BitWidth.width32), equals(6));
expect(ValueTypeUtils.packedType(ValueType.Int, BitWidth.width64), equals(7));
expect(
ValueTypeUtils.packedType(ValueType.Int, BitWidth.width8), equals(4));
expect(
ValueTypeUtils.packedType(ValueType.Int, BitWidth.width16), equals(5));
expect(
ValueTypeUtils.packedType(ValueType.Int, BitWidth.width32), equals(6));
expect(
ValueTypeUtils.packedType(ValueType.Int, BitWidth.width64), equals(7));
});
test('bit width', () {
expect(BitWidthUtil.width(0), BitWidth.width8);

View File

@@ -1,5 +1,5 @@
// automatically generated by the FlatBuffers compiler, do not modify
// ignore_for_file: unused_import, unused_field, unused_local_variable
// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable
library my_game.example2;
@@ -29,7 +29,7 @@ class Monster {
MonsterT unpack() => MonsterT();
static int pack(fb.Builder fbBuilder, MonsterT object) {
static int pack(fb.Builder fbBuilder, MonsterT? object) {
if (object == null) return 0;
return object.pack(fbBuilder);
}
@@ -37,8 +37,6 @@ class Monster {
class MonsterT {
int pack(fb.Builder fbBuilder) {
assert(fbBuilder != null);
fbBuilder.startTable();
return fbBuilder.endTable();
}
@@ -63,17 +61,14 @@ class MonsterObjectBuilder extends fb.ObjectBuilder {
/// Finish building, and store into the [fbBuilder].
@override
int finish(
fb.Builder fbBuilder) {
assert(fbBuilder != null);
int finish(fb.Builder fbBuilder) {
fbBuilder.startTable();
return fbBuilder.endTable();
}
/// Convenience method to serialize to byte list.
@override
Uint8List toBytes([String fileIdentifier]) {
Uint8List toBytes([String? fileIdentifier]) {
fb.Builder fbBuilder = new fb.Builder();
int offset = finish(fbBuilder);
return fbBuilder.finish(offset, fileIdentifier);

File diff suppressed because it is too large Load Diff

View File

@@ -1,5 +1,5 @@
// automatically generated by the FlatBuffers compiler, do not modify
// ignore_for_file: unused_import, unused_field, unused_local_variable
// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable
library my_game;
@@ -29,7 +29,7 @@ class InParentNamespace {
InParentNamespaceT unpack() => InParentNamespaceT();
static int pack(fb.Builder fbBuilder, InParentNamespaceT object) {
static int pack(fb.Builder fbBuilder, InParentNamespaceT? object) {
if (object == null) return 0;
return object.pack(fbBuilder);
}
@@ -37,8 +37,6 @@ class InParentNamespace {
class InParentNamespaceT {
int pack(fb.Builder fbBuilder) {
assert(fbBuilder != null);
fbBuilder.startTable();
return fbBuilder.endTable();
}
@@ -63,17 +61,14 @@ class InParentNamespaceObjectBuilder extends fb.ObjectBuilder {
/// Finish building, and store into the [fbBuilder].
@override
int finish(
fb.Builder fbBuilder) {
assert(fbBuilder != null);
int finish(fb.Builder fbBuilder) {
fbBuilder.startTable();
return fbBuilder.endTable();
}
/// Convenience method to serialize to byte list.
@override
Uint8List toBytes([String fileIdentifier]) {
Uint8List toBytes([String? fileIdentifier]) {
fb.Builder fbBuilder = new fb.Builder();
int offset = finish(fbBuilder);
return fbBuilder.finish(offset, fileIdentifier);

View File

@@ -1,4 +1,5 @@
#!/bin/bash
set -euo
#
# Copyright 2018 Dan Field. All rights reserved.
#

View File

@@ -63,7 +63,7 @@ class DartGenerator : public BaseGenerator {
code.clear();
code = code + "// " + FlatBuffersGeneratedWarning() + "\n";
code = code +
"// ignore_for_file: unused_import, unused_field, "
"// ignore_for_file: unused_import, unused_field, unused_element, "
"unused_local_variable\n\n";
if (!kv->first.empty()) { code += "library " + kv->first + ";\n\n"; }
@@ -231,17 +231,19 @@ class DartGenerator : public BaseGenerator {
code += " final int value;\n";
code += " const " + name + "._(this.value);\n\n";
code += " factory " + name + ".fromValue(int value) {\n";
code += " if (value == null) value = 0;\n";
code += " if (!values.containsKey(value)) {\n";
code += " final result = values[value];\n";
code += " if (result == null) {\n";
code +=
" throw new StateError('Invalid value $value for bit flag enum ";
code += name + "');\n";
code += " }\n";
code += " return values[value];\n";
code += " return result;\n";
code += " }\n\n";
code += " static " + name + "? _createOrNull(int? value) => \n";
code += " value == null ? null : " + name + ".fromValue(value);\n\n";
// this is meaningless for bit_flags
// however, note that unlike "regular" dart enums this enum can still have
// holes.
@@ -267,10 +269,11 @@ class DartGenerator : public BaseGenerator {
code += "const " + name + "._(" + enum_def.ToString(ev) + ");\n";
}
code += " static const Map<int," + name + "> values = {";
code += " static const Map<int, " + name + "> values = {\n";
for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) {
auto &ev = **it;
code += enum_def.ToString(ev) + ": " + ev.name + ",";
if (it != enum_def.Vals().begin()) code += ",\n";
code += " " + enum_def.ToString(ev) + ": " + ev.name;
}
code += "};\n\n";
@@ -430,8 +433,6 @@ class DartGenerator : public BaseGenerator {
code += "class " + object_name + " {\n";
code += " " + object_name + "._(this._bc, this._bcOffset);\n";
// TODO why not generate the (reader) factory constructor for "structs"?
// Currently only genreated for "tables" but should work for both...
if (!struct_def.fixed) {
code += " factory " + object_name + "(List<int> bytes) {\n";
code += " " + _kFb + ".BufferContext rootRef = new " + _kFb +
@@ -463,7 +464,7 @@ class DartGenerator : public BaseGenerator {
"\n" + GenStructObjectAPIUnpack(struct_def, non_deprecated_fields);
code += "\n static int pack(fb.Builder fbBuilder, " + struct_def.name +
"T object) {\n";
"T? object) {\n";
code += " if (object == null) return 0;\n";
code += " return object.pack(fbBuilder);\n";
code += " }\n";
@@ -505,12 +506,31 @@ class DartGenerator : public BaseGenerator {
std::string type_name = GenDartTypeName(
field.value.type, struct_def.defined_namespace, field, "T");
std::string defaultValue = getDefaultValue(field.value);
bool isNullable = defaultValue.empty() && !struct_def.fixed;
GenDocComment(field.doc_comment, &code, "", " ");
code += " " + type_name + " " + field_name + ";\n";
code += " " + type_name + (isNullable ? "? " : " ") + field_name + ";\n";
if (!constructor_args.empty()) constructor_args += ",\n";
// TODO for null safety: add `required` if struct_def.fixed
constructor_args += " this." + field_name;
constructor_args += " ";
constructor_args += (struct_def.fixed ? "required " : "");
constructor_args += "this." + field_name;
if (!struct_def.fixed && !defaultValue.empty()) {
if (IsEnum(field.value.type)) {
auto &enum_def = *field.value.type.enum_def;
for (auto enumIt = enum_def.Vals().begin();
enumIt != enum_def.Vals().end(); ++enumIt) {
auto &ev = **enumIt;
if (enum_def.ToString(ev) == defaultValue) {
constructor_args += " = " + enum_def.name + "." + ev.name;
break;
}
}
} else {
constructor_args += " = " + defaultValue;
}
}
}
if (!constructor_args.empty()) {
@@ -539,11 +559,15 @@ class DartGenerator : public BaseGenerator {
constructor_args += " " + field_name + ": " + field_name;
const Type &type = field.value.type;
bool isNullable =
getDefaultValue(field.value).empty() && !struct_def.fixed;
std::string nullableValueAccessOperator = isNullable ? "?" : "";
if (type.base_type == BASE_TYPE_STRUCT) {
constructor_args += "?.unpack()";
constructor_args += nullableValueAccessOperator + ".unpack()";
} else if (type.base_type == BASE_TYPE_VECTOR &&
type.VectorType().base_type == BASE_TYPE_STRUCT) {
constructor_args += "?.map((e) => e.unpack())?.toList()";
constructor_args +=
nullableValueAccessOperator + ".map((e) => e.unpack()).toList()";
}
}
@@ -613,8 +637,11 @@ class DartGenerator : public BaseGenerator {
field.value.type, struct_def.defined_namespace, field);
GenDocComment(field.doc_comment, &code, "", " ");
std::string defaultValue = getDefaultValue(field.value);
bool isNullable = defaultValue.empty() && !struct_def.fixed;
code += " " + type_name + " get " + field_name;
code += " " + type_name + (isNullable ? "?" : "");
code += " get " + field_name;
if (field.value.type.base_type == BASE_TYPE_UNION) {
code += " {\n";
code += " switch (" + field_name + "Type?.value) {\n";
@@ -626,8 +653,8 @@ class DartGenerator : public BaseGenerator {
auto enum_name = NamespaceAliasFromUnionType(
enum_def.defined_namespace, ev.union_type);
code += " case " + enum_def.ToString(ev) + ": return " +
enum_name + ".reader.vTableGet(_bc, _bcOffset, " +
NumToString(field.value.offset) + ", null);\n";
enum_name + ".reader.vTableGetNullable(_bc, _bcOffset, " +
NumToString(field.value.offset) + ");\n";
}
code += " default: return null;\n";
code += " }\n";
@@ -636,10 +663,9 @@ class DartGenerator : public BaseGenerator {
code += " => ";
if (field.value.type.enum_def &&
field.value.type.base_type != BASE_TYPE_VECTOR) {
code += "new " +
GenDartTypeName(field.value.type,
code += GenDartTypeName(field.value.type,
struct_def.defined_namespace, field) +
".fromValue(";
(isNullable ? "._createOrNull(" : ".fromValue(");
}
code += GenReaderTypeName(field.value.type,
@@ -648,33 +674,13 @@ class DartGenerator : public BaseGenerator {
code +=
".read(_bc, _bcOffset + " + NumToString(field.value.offset) + ")";
} else {
code += ".vTableGet(_bc, _bcOffset, " +
NumToString(field.value.offset) + ", ";
if (!field.value.constant.empty() && field.value.constant != "0") {
if (IsBool(field.value.type.base_type)) {
code += "true";
} else if (field.value.constant == "nan" ||
field.value.constant == "+nan" ||
field.value.constant == "-nan") {
code += "double.nan";
} else if (field.value.constant == "inf" ||
field.value.constant == "+inf") {
code += "double.infinity";
} else if (field.value.constant == "-inf") {
code += "double.negativeInfinity";
} else {
code += field.value.constant;
}
code += ".vTableGet";
std::string offset = NumToString(field.value.offset);
if (isNullable) {
code += "Nullable(_bc, _bcOffset, " + offset + ")";
} else {
if (IsBool(field.value.type.base_type)) {
code += "false";
} else if (IsScalar(field.value.type.base_type)) {
code += "0";
} else {
code += "null";
}
code += "(_bc, _bcOffset, " + offset + ", " + defaultValue + ")";
}
code += ")";
}
if (field.value.type.enum_def &&
field.value.type.base_type != BASE_TYPE_VECTOR) {
@@ -708,6 +714,29 @@ class DartGenerator : public BaseGenerator {
return code;
}
std::string getDefaultValue(const Value &value) const {
if (!value.constant.empty() && value.constant != "0") {
if (IsBool(value.type.base_type)) {
return "true";
} else if (value.constant == "nan" || value.constant == "+nan" ||
value.constant == "-nan") {
return "double.nan";
} else if (value.constant == "inf" || value.constant == "+inf") {
return "double.infinity";
} else if (value.constant == "-inf") {
return "double.negativeInfinity";
} else {
return value.constant;
}
} else if (IsBool(value.type.base_type)) {
return "false";
} else if (IsScalar(value.type.base_type) && !IsUnion(value.type)) {
return "0";
} else {
return "";
}
}
void GenReader(const StructDef &struct_def, std::string *reader_name_ptr,
std::string *code_ptr) {
auto &code = *code_ptr;
@@ -742,9 +771,7 @@ class DartGenerator : public BaseGenerator {
auto &builder_name = *builder_name_ptr;
code += "class " + builder_name + " {\n";
code += " " + builder_name + "(this.fbBuilder) {\n";
code += " assert(fbBuilder != null);\n";
code += " }\n\n";
code += " " + builder_name + "(this.fbBuilder) {}\n\n";
code += " final " + _kFb + ".Builder fbBuilder;\n\n";
if (struct_def.fixed) {
@@ -793,7 +820,7 @@ class DartGenerator : public BaseGenerator {
} else {
code += " fbBuilder.put" + GenType(field.value.type) + "(";
code += field.name;
if (field.value.type.enum_def) { code += "?.value"; }
if (field.value.type.enum_def) { code += ".value"; }
code += ");\n";
}
}
@@ -821,7 +848,7 @@ class DartGenerator : public BaseGenerator {
code += " int add" + MakeCamel(field.name) + "(";
code += GenDartTypeName(field.value.type, struct_def.defined_namespace,
field);
code += " " + MakeCamel(field.name, false) + ") {\n";
code += "? " + MakeCamel(field.name, false) + ") {\n";
code += " fbBuilder.add" + GenType(field.value.type) + "(" +
NumToString(offset) + ", ";
code += MakeCamel(field.name, false);
@@ -832,7 +859,7 @@ class DartGenerator : public BaseGenerator {
code +=
" fbBuilder.addStruct(" + NumToString(offset) + ", offset);\n";
} else {
code += " int add" + MakeCamel(field.name) + "Offset(int offset) {\n";
code += " int add" + MakeCamel(field.name) + "Offset(int? offset) {\n";
code +=
" fbBuilder.addOffset(" + NumToString(offset) + ", offset);\n";
}
@@ -862,7 +889,8 @@ class DartGenerator : public BaseGenerator {
code += " final " +
GenDartTypeName(field.value.type, struct_def.defined_namespace,
field, "ObjectBuilder") +
" _" + MakeCamel(field.name, false) + ";\n";
(struct_def.fixed ? "" : "?") + " _" +
MakeCamel(field.name, false) + ";\n";
}
code += "\n";
code += " " + builder_name + "(";
@@ -874,10 +902,12 @@ class DartGenerator : public BaseGenerator {
auto pair = *it;
auto &field = *pair.second;
code += " " +
code += " ";
code += (struct_def.fixed ? "required " : "") +
GenDartTypeName(field.value.type, struct_def.defined_namespace,
field, "ObjectBuilder") +
" " + MakeCamel(field.name, false) + ",\n";
(struct_def.fixed ? "" : "?") + " " +
MakeCamel(field.name, false) + ",\n";
}
code += " })\n";
code += " : ";
@@ -900,14 +930,13 @@ class DartGenerator : public BaseGenerator {
code += " /// Finish building, and store into the [fbBuilder].\n";
code += " @override\n";
code += " int finish(\n";
code += " " + _kFb + ".Builder fbBuilder) {\n";
code += " int finish(" + _kFb + ".Builder fbBuilder) {\n";
code += GenObjectBuilderImplementation(struct_def, non_deprecated_fields);
code += " }\n\n";
code += " /// Convenience method to serialize to byte list.\n";
code += " @override\n";
code += " Uint8List toBytes([String fileIdentifier]) {\n";
code += " Uint8List toBytes([String? fileIdentifier]) {\n";
code += " " + _kFb + ".Builder fbBuilder = new ";
code += _kFb + ".Builder();\n";
code += " int offset = finish(fbBuilder);\n";
@@ -920,7 +949,7 @@ class DartGenerator : public BaseGenerator {
const StructDef &struct_def,
const std::vector<std::pair<int, FieldDef *>> &non_deprecated_fields,
bool prependUnderscore = true, bool pack = false) {
std::string code = " assert(fbBuilder != null);\n";
std::string code;
for (auto it = non_deprecated_fields.begin();
it != non_deprecated_fields.end(); ++it) {
const FieldDef &field = *it->second;
@@ -936,36 +965,38 @@ class DartGenerator : public BaseGenerator {
if (pack && IsVector(field.value.type) &&
field.value.type.VectorType().base_type == BASE_TYPE_STRUCT &&
field.value.type.struct_def->fixed) {
code += " int " + offset_name + " = null;\n";
code += " int? " + offset_name + " = null;\n";
code += " if (" + field_name + "?.isNotEmpty == true) {\n";
code += " " + field_name + ".forEach((e) => e.pack(fbBuilder));\n";
code +=
" " + field_name + "!.forEach((e) => e.pack(fbBuilder));\n";
code += " " + MakeCamel(field.name, false) +
"Offset = fbBuilder.endStructVector(" + field_name +
".length);\n";
"!.length);\n";
code += " }\n";
continue;
}
code += " final int " + offset_name;
code += " final int? " + offset_name;
if (IsVector(field.value.type)) {
code += " = " + field_name + "?.isNotEmpty == true\n";
code += " ? fbBuilder.writeList";
switch (field.value.type.VectorType().base_type) {
case BASE_TYPE_STRING:
code += "(" + field_name +
".map((b) => fbBuilder.writeString(b)).toList())";
"!.map((b) => fbBuilder.writeString(b)!).toList())";
break;
case BASE_TYPE_STRUCT:
if (field.value.type.struct_def->fixed) {
code += "OfStructs(" + field_name + ")";
code += "OfStructs(" + field_name + "!)";
} else {
code += "(" + field_name + ".map((b) => b." +
code += "(" + field_name + "!.map((b) => b." +
(pack ? "pack" : "getOrCreateOffset") +
"(fbBuilder)).toList())";
}
break;
default:
code += GenType(field.value.type.VectorType()) + "(" + field_name;
code +=
GenType(field.value.type.VectorType()) + "(" + field_name + "!";
if (field.value.type.enum_def) {
code += ".map((f) => f.value).toList()";
}
@@ -979,7 +1010,7 @@ class DartGenerator : public BaseGenerator {
(pack ? "pack" : "getOrCreateOffset") + "(fbBuilder);\n";
}
}
code += "\n";
if (struct_def.fixed) {
code += StructObjectBuilderBody(non_deprecated_fields, prependUnderscore,
pack);
@@ -1012,7 +1043,7 @@ class DartGenerator : public BaseGenerator {
code += " fbBuilder.put" + GenType(field.value.type) + "(";
if (prependUnderscore) { code += "_"; }
code += field.name;
if (field.value.type.enum_def) { code += "?.value"; }
if (field.value.type.enum_def) { code += ".value"; }
code += ");\n";
}
}
@@ -1039,19 +1070,19 @@ class DartGenerator : public BaseGenerator {
if (IsScalar(field.value.type.base_type)) {
code += " fbBuilder.add" + GenType(field.value.type) + "(" +
NumToString(offset) + ", " + field_name;
if (field.value.type.enum_def) { code += "?.value"; }
if (field.value.type.enum_def) {
bool isNullable = getDefaultValue(field.value).empty();
code += (isNullable || !pack) ? "?.value" : ".value";
}
code += ");\n";
} else if (IsStruct(field.value.type)) {
code += " if (" + field_name + " != null) {\n";
code += " fbBuilder.addStruct(" + NumToString(offset) + ", " +
field_name + (pack ? ".pack" : ".finish") + "(fbBuilder));\n";
field_name + (pack ? "!.pack" : "!.finish") + "(fbBuilder));\n";
code += " }\n";
} else {
code +=
" if (" + MakeCamel(field.name, false) + "Offset != null) {\n";
code += " fbBuilder.addOffset(" + NumToString(offset) + ", " +
code += " fbBuilder.addOffset(" + NumToString(offset) + ", " +
MakeCamel(field.name, false) + "Offset);\n";
code += " }\n";
}
}
code += " return fbBuilder.endTable();\n";

View File

@@ -1,5 +1,5 @@
// automatically generated by the FlatBuffers compiler, do not modify
// ignore_for_file: unused_import, unused_field, unused_local_variable
// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable
library my_game;
@@ -27,8 +27,8 @@ class MonsterExtra {
double get f1 => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 14, double.nan);
double get f2 => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 16, double.infinity);
double get f3 => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 18, double.negativeInfinity);
List<double> get dvec => const fb.ListReader<double>(const fb.Float64Reader()).vTableGet(_bc, _bcOffset, 20, null);
List<double> get fvec => const fb.ListReader<double>(const fb.Float32Reader()).vTableGet(_bc, _bcOffset, 22, null);
List<double>? get dvec => const fb.ListReader<double>(const fb.Float64Reader()).vTableGetNullable(_bc, _bcOffset, 20);
List<double>? get fvec => const fb.ListReader<double>(const fb.Float32Reader()).vTableGetNullable(_bc, _bcOffset, 22);
@override
String toString() {
@@ -47,7 +47,7 @@ class MonsterExtra {
dvec: dvec,
fvec: fvec);
static int pack(fb.Builder fbBuilder, MonsterExtraT object) {
static int pack(fb.Builder fbBuilder, MonsterExtraT? object) {
if (object == null) return 0;
return object.pack(fbBuilder);
}
@@ -62,30 +62,28 @@ class MonsterExtraT {
double f1;
double f2;
double f3;
List<double> dvec;
List<double> fvec;
List<double>? dvec;
List<double>? fvec;
MonsterExtraT({
this.d0,
this.d1,
this.d2,
this.d3,
this.f0,
this.f1,
this.f2,
this.f3,
this.d0 = double.nan,
this.d1 = double.nan,
this.d2 = double.infinity,
this.d3 = double.negativeInfinity,
this.f0 = double.nan,
this.f1 = double.nan,
this.f2 = double.infinity,
this.f3 = double.negativeInfinity,
this.dvec,
this.fvec});
int pack(fb.Builder fbBuilder) {
assert(fbBuilder != null);
final int dvecOffset = dvec?.isNotEmpty == true
? fbBuilder.writeListFloat64(dvec)
final int? dvecOffset = dvec?.isNotEmpty == true
? fbBuilder.writeListFloat64(dvec!)
: null;
final int fvecOffset = fvec?.isNotEmpty == true
? fbBuilder.writeListFloat32(fvec)
final int? fvecOffset = fvec?.isNotEmpty == true
? fbBuilder.writeListFloat32(fvec!)
: null;
fbBuilder.startTable();
fbBuilder.addFloat64(0, d0);
fbBuilder.addFloat64(1, d1);
@@ -95,12 +93,8 @@ class MonsterExtraT {
fbBuilder.addFloat32(5, f1);
fbBuilder.addFloat32(6, f2);
fbBuilder.addFloat32(7, f3);
if (dvecOffset != null) {
fbBuilder.addOffset(8, dvecOffset);
}
if (fvecOffset != null) {
fbBuilder.addOffset(9, fvecOffset);
}
fbBuilder.addOffset(8, dvecOffset);
fbBuilder.addOffset(9, fvecOffset);
return fbBuilder.endTable();
}
@@ -119,9 +113,7 @@ class _MonsterExtraReader extends fb.TableReader<MonsterExtra> {
}
class MonsterExtraBuilder {
MonsterExtraBuilder(this.fbBuilder) {
assert(fbBuilder != null);
}
MonsterExtraBuilder(this.fbBuilder) {}
final fb.Builder fbBuilder;
@@ -129,43 +121,43 @@ class MonsterExtraBuilder {
fbBuilder.startTable();
}
int addD0(double d0) {
int addD0(double? d0) {
fbBuilder.addFloat64(0, d0);
return fbBuilder.offset;
}
int addD1(double d1) {
int addD1(double? d1) {
fbBuilder.addFloat64(1, d1);
return fbBuilder.offset;
}
int addD2(double d2) {
int addD2(double? d2) {
fbBuilder.addFloat64(2, d2);
return fbBuilder.offset;
}
int addD3(double d3) {
int addD3(double? d3) {
fbBuilder.addFloat64(3, d3);
return fbBuilder.offset;
}
int addF0(double f0) {
int addF0(double? f0) {
fbBuilder.addFloat32(4, f0);
return fbBuilder.offset;
}
int addF1(double f1) {
int addF1(double? f1) {
fbBuilder.addFloat32(5, f1);
return fbBuilder.offset;
}
int addF2(double f2) {
int addF2(double? f2) {
fbBuilder.addFloat32(6, f2);
return fbBuilder.offset;
}
int addF3(double f3) {
int addF3(double? f3) {
fbBuilder.addFloat32(7, f3);
return fbBuilder.offset;
}
int addDvecOffset(int offset) {
int addDvecOffset(int? offset) {
fbBuilder.addOffset(8, offset);
return fbBuilder.offset;
}
int addFvecOffset(int offset) {
int addFvecOffset(int? offset) {
fbBuilder.addOffset(9, offset);
return fbBuilder.offset;
}
@@ -176,28 +168,28 @@ class MonsterExtraBuilder {
}
class MonsterExtraObjectBuilder extends fb.ObjectBuilder {
final double _d0;
final double _d1;
final double _d2;
final double _d3;
final double _f0;
final double _f1;
final double _f2;
final double _f3;
final List<double> _dvec;
final List<double> _fvec;
final double? _d0;
final double? _d1;
final double? _d2;
final double? _d3;
final double? _f0;
final double? _f1;
final double? _f2;
final double? _f3;
final List<double>? _dvec;
final List<double>? _fvec;
MonsterExtraObjectBuilder({
double d0,
double d1,
double d2,
double d3,
double f0,
double f1,
double f2,
double f3,
List<double> dvec,
List<double> fvec,
double? d0,
double? d1,
double? d2,
double? d3,
double? f0,
double? f1,
double? f2,
double? f3,
List<double>? dvec,
List<double>? fvec,
})
: _d0 = d0,
_d1 = d1,
@@ -212,16 +204,13 @@ class MonsterExtraObjectBuilder extends fb.ObjectBuilder {
/// Finish building, and store into the [fbBuilder].
@override
int finish(
fb.Builder fbBuilder) {
assert(fbBuilder != null);
final int dvecOffset = _dvec?.isNotEmpty == true
? fbBuilder.writeListFloat64(_dvec)
int finish(fb.Builder fbBuilder) {
final int? dvecOffset = _dvec?.isNotEmpty == true
? fbBuilder.writeListFloat64(_dvec!)
: null;
final int fvecOffset = _fvec?.isNotEmpty == true
? fbBuilder.writeListFloat32(_fvec)
final int? fvecOffset = _fvec?.isNotEmpty == true
? fbBuilder.writeListFloat32(_fvec!)
: null;
fbBuilder.startTable();
fbBuilder.addFloat64(0, _d0);
fbBuilder.addFloat64(1, _d1);
@@ -231,18 +220,14 @@ class MonsterExtraObjectBuilder extends fb.ObjectBuilder {
fbBuilder.addFloat32(5, _f1);
fbBuilder.addFloat32(6, _f2);
fbBuilder.addFloat32(7, _f3);
if (dvecOffset != null) {
fbBuilder.addOffset(8, dvecOffset);
}
if (fvecOffset != null) {
fbBuilder.addOffset(9, fvecOffset);
}
fbBuilder.addOffset(8, dvecOffset);
fbBuilder.addOffset(9, fvecOffset);
return fbBuilder.endTable();
}
/// Convenience method to serialize to byte list.
@override
Uint8List toBytes([String fileIdentifier]) {
Uint8List toBytes([String? fileIdentifier]) {
fb.Builder fbBuilder = new fb.Builder();
int offset = finish(fbBuilder);
return fbBuilder.finish(offset, fileIdentifier);

View File

@@ -1,5 +1,5 @@
// automatically generated by the FlatBuffers compiler, do not modify
// ignore_for_file: unused_import, unused_field, unused_local_variable
// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable
library my_game.example2;
@@ -29,7 +29,7 @@ class Monster {
MonsterT unpack() => MonsterT();
static int pack(fb.Builder fbBuilder, MonsterT object) {
static int pack(fb.Builder fbBuilder, MonsterT? object) {
if (object == null) return 0;
return object.pack(fbBuilder);
}
@@ -37,8 +37,6 @@ class Monster {
class MonsterT {
int pack(fb.Builder fbBuilder) {
assert(fbBuilder != null);
fbBuilder.startTable();
return fbBuilder.endTable();
}
@@ -63,17 +61,14 @@ class MonsterObjectBuilder extends fb.ObjectBuilder {
/// Finish building, and store into the [fbBuilder].
@override
int finish(
fb.Builder fbBuilder) {
assert(fbBuilder != null);
int finish(fb.Builder fbBuilder) {
fbBuilder.startTable();
return fbBuilder.endTable();
}
/// Convenience method to serialize to byte list.
@override
Uint8List toBytes([String fileIdentifier]) {
Uint8List toBytes([String? fileIdentifier]) {
fb.Builder fbBuilder = new fb.Builder();
int offset = finish(fbBuilder);
return fbBuilder.finish(offset, fileIdentifier);

File diff suppressed because it is too large Load Diff

View File

@@ -1,5 +1,5 @@
// automatically generated by the FlatBuffers compiler, do not modify
// ignore_for_file: unused_import, unused_field, unused_local_variable
// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable
library my_game;
@@ -29,7 +29,7 @@ class InParentNamespace {
InParentNamespaceT unpack() => InParentNamespaceT();
static int pack(fb.Builder fbBuilder, InParentNamespaceT object) {
static int pack(fb.Builder fbBuilder, InParentNamespaceT? object) {
if (object == null) return 0;
return object.pack(fbBuilder);
}
@@ -37,8 +37,6 @@ class InParentNamespace {
class InParentNamespaceT {
int pack(fb.Builder fbBuilder) {
assert(fbBuilder != null);
fbBuilder.startTable();
return fbBuilder.endTable();
}
@@ -63,17 +61,14 @@ class InParentNamespaceObjectBuilder extends fb.ObjectBuilder {
/// Finish building, and store into the [fbBuilder].
@override
int finish(
fb.Builder fbBuilder) {
assert(fbBuilder != null);
int finish(fb.Builder fbBuilder) {
fbBuilder.startTable();
return fbBuilder.endTable();
}
/// Convenience method to serialize to byte list.
@override
Uint8List toBytes([String fileIdentifier]) {
Uint8List toBytes([String? fileIdentifier]) {
fb.Builder fbBuilder = new fb.Builder();
int offset = finish(fbBuilder);
return fbBuilder.finish(offset, fileIdentifier);

View File

@@ -1,5 +1,5 @@
// automatically generated by the FlatBuffers compiler, do not modify
// ignore_for_file: unused_import, unused_field, unused_local_variable
// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable
library namespace_a.namespace_b;
@@ -12,20 +12,25 @@ class UnionInNestedNSTypeId {
const UnionInNestedNSTypeId._(this.value);
factory UnionInNestedNSTypeId.fromValue(int value) {
if (value == null) value = 0;
if (!values.containsKey(value)) {
final result = values[value];
if (result == null) {
throw new StateError('Invalid value $value for bit flag enum UnionInNestedNSTypeId');
}
return values[value];
return result;
}
static UnionInNestedNSTypeId? _createOrNull(int? value) =>
value == null ? null : UnionInNestedNSTypeId.fromValue(value);
static const int minValue = 0;
static const int maxValue = 1;
static bool containsValue(int value) => values.containsKey(value);
static const UnionInNestedNSTypeId NONE = const UnionInNestedNSTypeId._(0);
static const UnionInNestedNSTypeId TableInNestedNS = const UnionInNestedNSTypeId._(1);
static const Map<int,UnionInNestedNSTypeId> values = {0: NONE,1: TableInNestedNS,};
static const Map<int, UnionInNestedNSTypeId> values = {
0: NONE,
1: TableInNestedNS};
static const fb.Reader<UnionInNestedNSTypeId> reader = const _UnionInNestedNSTypeIdReader();
@@ -51,13 +56,16 @@ class EnumInNestedNS {
const EnumInNestedNS._(this.value);
factory EnumInNestedNS.fromValue(int value) {
if (value == null) value = 0;
if (!values.containsKey(value)) {
final result = values[value];
if (result == null) {
throw new StateError('Invalid value $value for bit flag enum EnumInNestedNS');
}
return values[value];
return result;
}
static EnumInNestedNS? _createOrNull(int? value) =>
value == null ? null : EnumInNestedNS.fromValue(value);
static const int minValue = 0;
static const int maxValue = 2;
static bool containsValue(int value) => values.containsKey(value);
@@ -65,7 +73,10 @@ class EnumInNestedNS {
static const EnumInNestedNS A = const EnumInNestedNS._(0);
static const EnumInNestedNS B = const EnumInNestedNS._(1);
static const EnumInNestedNS C = const EnumInNestedNS._(2);
static const Map<int,EnumInNestedNS> values = {0: A,1: B,2: C,};
static const Map<int, EnumInNestedNS> values = {
0: A,
1: B,
2: C};
static const fb.Reader<EnumInNestedNS> reader = const _EnumInNestedNSReader();
@@ -108,7 +119,7 @@ class TableInNestedNS {
TableInNestedNST unpack() => TableInNestedNST(
foo: foo);
static int pack(fb.Builder fbBuilder, TableInNestedNST object) {
static int pack(fb.Builder fbBuilder, TableInNestedNST? object) {
if (object == null) return 0;
return object.pack(fbBuilder);
}
@@ -118,11 +129,9 @@ class TableInNestedNST {
int foo;
TableInNestedNST({
this.foo});
this.foo = 0});
int pack(fb.Builder fbBuilder) {
assert(fbBuilder != null);
fbBuilder.startTable();
fbBuilder.addInt32(0, foo);
return fbBuilder.endTable();
@@ -143,9 +152,7 @@ class _TableInNestedNSReader extends fb.TableReader<TableInNestedNS> {
}
class TableInNestedNSBuilder {
TableInNestedNSBuilder(this.fbBuilder) {
assert(fbBuilder != null);
}
TableInNestedNSBuilder(this.fbBuilder) {}
final fb.Builder fbBuilder;
@@ -153,7 +160,7 @@ class TableInNestedNSBuilder {
fbBuilder.startTable();
}
int addFoo(int foo) {
int addFoo(int? foo) {
fbBuilder.addInt32(0, foo);
return fbBuilder.offset;
}
@@ -164,19 +171,16 @@ class TableInNestedNSBuilder {
}
class TableInNestedNSObjectBuilder extends fb.ObjectBuilder {
final int _foo;
final int? _foo;
TableInNestedNSObjectBuilder({
int foo,
int? foo,
})
: _foo = foo;
/// Finish building, and store into the [fbBuilder].
@override
int finish(
fb.Builder fbBuilder) {
assert(fbBuilder != null);
int finish(fb.Builder fbBuilder) {
fbBuilder.startTable();
fbBuilder.addInt32(0, _foo);
return fbBuilder.endTable();
@@ -184,7 +188,7 @@ class TableInNestedNSObjectBuilder extends fb.ObjectBuilder {
/// Convenience method to serialize to byte list.
@override
Uint8List toBytes([String fileIdentifier]) {
Uint8List toBytes([String? fileIdentifier]) {
fb.Builder fbBuilder = new fb.Builder();
int offset = finish(fbBuilder);
return fbBuilder.finish(offset, fileIdentifier);
@@ -210,7 +214,7 @@ class StructInNestedNS {
a: a,
b: b);
static int pack(fb.Builder fbBuilder, StructInNestedNST object) {
static int pack(fb.Builder fbBuilder, StructInNestedNST? object) {
if (object == null) return 0;
return object.pack(fbBuilder);
}
@@ -221,12 +225,10 @@ class StructInNestedNST {
int b;
StructInNestedNST({
this.a,
this.b});
required this.a,
required this.b});
int pack(fb.Builder fbBuilder) {
assert(fbBuilder != null);
fbBuilder.putInt32(b);
fbBuilder.putInt32(a);
return fbBuilder.offset;
@@ -250,9 +252,7 @@ class _StructInNestedNSReader extends fb.StructReader<StructInNestedNS> {
}
class StructInNestedNSBuilder {
StructInNestedNSBuilder(this.fbBuilder) {
assert(fbBuilder != null);
}
StructInNestedNSBuilder(this.fbBuilder) {}
final fb.Builder fbBuilder;
@@ -269,18 +269,15 @@ class StructInNestedNSObjectBuilder extends fb.ObjectBuilder {
final int _b;
StructInNestedNSObjectBuilder({
int a,
int b,
required int a,
required int b,
})
: _a = a,
_b = b;
/// Finish building, and store into the [fbBuilder].
@override
int finish(
fb.Builder fbBuilder) {
assert(fbBuilder != null);
int finish(fb.Builder fbBuilder) {
fbBuilder.putInt32(_b);
fbBuilder.putInt32(_a);
return fbBuilder.offset;
@@ -288,7 +285,7 @@ class StructInNestedNSObjectBuilder extends fb.ObjectBuilder {
/// Convenience method to serialize to byte list.
@override
Uint8List toBytes([String fileIdentifier]) {
Uint8List toBytes([String? fileIdentifier]) {
fb.Builder fbBuilder = new fb.Builder();
int offset = finish(fbBuilder);
return fbBuilder.finish(offset, fileIdentifier);

View File

@@ -1,5 +1,5 @@
// automatically generated by the FlatBuffers compiler, do not modify
// ignore_for_file: unused_import, unused_field, unused_local_variable
// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable
library namespace_a;
@@ -20,16 +20,16 @@ class TableInFirstNS {
final fb.BufferContext _bc;
final int _bcOffset;
namespace_a_namespace_b.TableInNestedNS get fooTable => namespace_a_namespace_b.TableInNestedNS.reader.vTableGet(_bc, _bcOffset, 4, null);
EnumInNestedNS get fooEnum => new EnumInNestedNS.fromValue(const fb.Int8Reader().vTableGet(_bc, _bcOffset, 6, 0));
UnionInNestedNSTypeId get fooUnionType => new UnionInNestedNSTypeId.fromValue(const fb.Uint8Reader().vTableGet(_bc, _bcOffset, 8, 0));
dynamic get fooUnion {
namespace_a_namespace_b.TableInNestedNS? get fooTable => namespace_a_namespace_b.TableInNestedNS.reader.vTableGetNullable(_bc, _bcOffset, 4);
EnumInNestedNS get fooEnum => EnumInNestedNS.fromValue(const fb.Int8Reader().vTableGet(_bc, _bcOffset, 6, 0));
UnionInNestedNSTypeId? get fooUnionType => UnionInNestedNSTypeId._createOrNull(const fb.Uint8Reader().vTableGetNullable(_bc, _bcOffset, 8));
dynamic? get fooUnion {
switch (fooUnionType?.value) {
case 1: return TableInNestedNS.reader.vTableGet(_bc, _bcOffset, 10, null);
case 1: return TableInNestedNS.reader.vTableGetNullable(_bc, _bcOffset, 10);
default: return null;
}
}
namespace_a_namespace_b.StructInNestedNS get fooStruct => namespace_a_namespace_b.StructInNestedNS.reader.vTableGet(_bc, _bcOffset, 12, null);
namespace_a_namespace_b.StructInNestedNS? get fooStruct => namespace_a_namespace_b.StructInNestedNS.reader.vTableGetNullable(_bc, _bcOffset, 12);
@override
String toString() {
@@ -43,42 +43,36 @@ class TableInFirstNS {
fooUnion: fooUnion,
fooStruct: fooStruct?.unpack());
static int pack(fb.Builder fbBuilder, TableInFirstNST object) {
static int pack(fb.Builder fbBuilder, TableInFirstNST? object) {
if (object == null) return 0;
return object.pack(fbBuilder);
}
}
class TableInFirstNST {
namespace_a_namespace_b.TableInNestedNST fooTable;
namespace_a_namespace_b.TableInNestedNST? fooTable;
EnumInNestedNS fooEnum;
UnionInNestedNSTypeId fooUnionType;
dynamic fooUnion;
namespace_a_namespace_b.StructInNestedNST fooStruct;
UnionInNestedNSTypeId? fooUnionType;
dynamic? fooUnion;
namespace_a_namespace_b.StructInNestedNST? fooStruct;
TableInFirstNST({
this.fooTable,
this.fooEnum,
this.fooEnum = EnumInNestedNS.A,
this.fooUnionType,
this.fooUnion,
this.fooStruct});
int pack(fb.Builder fbBuilder) {
assert(fbBuilder != null);
final int fooTableOffset = fooTable?.pack(fbBuilder);
final int fooUnionOffset = fooUnion?.pack(fbBuilder);
final int? fooTableOffset = fooTable?.pack(fbBuilder);
final int? fooUnionOffset = fooUnion?.pack(fbBuilder);
fbBuilder.startTable();
if (fooTableOffset != null) {
fbBuilder.addOffset(0, fooTableOffset);
}
fbBuilder.addInt8(1, fooEnum?.value);
fbBuilder.addOffset(0, fooTableOffset);
fbBuilder.addInt8(1, fooEnum.value);
fbBuilder.addUint8(2, fooUnionType?.value);
if (fooUnionOffset != null) {
fbBuilder.addOffset(3, fooUnionOffset);
}
fbBuilder.addOffset(3, fooUnionOffset);
if (fooStruct != null) {
fbBuilder.addStruct(4, fooStruct.pack(fbBuilder));
fbBuilder.addStruct(4, fooStruct!.pack(fbBuilder));
}
return fbBuilder.endTable();
}
@@ -98,9 +92,7 @@ class _TableInFirstNSReader extends fb.TableReader<TableInFirstNS> {
}
class TableInFirstNSBuilder {
TableInFirstNSBuilder(this.fbBuilder) {
assert(fbBuilder != null);
}
TableInFirstNSBuilder(this.fbBuilder) {}
final fb.Builder fbBuilder;
@@ -108,19 +100,19 @@ class TableInFirstNSBuilder {
fbBuilder.startTable();
}
int addFooTableOffset(int offset) {
int addFooTableOffset(int? offset) {
fbBuilder.addOffset(0, offset);
return fbBuilder.offset;
}
int addFooEnum(EnumInNestedNS fooEnum) {
int addFooEnum(EnumInNestedNS? fooEnum) {
fbBuilder.addInt8(1, fooEnum?.value);
return fbBuilder.offset;
}
int addFooUnionType(UnionInNestedNSTypeId fooUnionType) {
int addFooUnionType(UnionInNestedNSTypeId? fooUnionType) {
fbBuilder.addUint8(2, fooUnionType?.value);
return fbBuilder.offset;
}
int addFooUnionOffset(int offset) {
int addFooUnionOffset(int? offset) {
fbBuilder.addOffset(3, offset);
return fbBuilder.offset;
}
@@ -135,18 +127,18 @@ class TableInFirstNSBuilder {
}
class TableInFirstNSObjectBuilder extends fb.ObjectBuilder {
final namespace_a_namespace_b.TableInNestedNSObjectBuilder _fooTable;
final EnumInNestedNS _fooEnum;
final UnionInNestedNSTypeId _fooUnionType;
final dynamic _fooUnion;
final namespace_a_namespace_b.StructInNestedNSObjectBuilder _fooStruct;
final namespace_a_namespace_b.TableInNestedNSObjectBuilder? _fooTable;
final EnumInNestedNS? _fooEnum;
final UnionInNestedNSTypeId? _fooUnionType;
final dynamic? _fooUnion;
final namespace_a_namespace_b.StructInNestedNSObjectBuilder? _fooStruct;
TableInFirstNSObjectBuilder({
namespace_a_namespace_b.TableInNestedNSObjectBuilder fooTable,
EnumInNestedNS fooEnum,
UnionInNestedNSTypeId fooUnionType,
dynamic fooUnion,
namespace_a_namespace_b.StructInNestedNSObjectBuilder fooStruct,
namespace_a_namespace_b.TableInNestedNSObjectBuilder? fooTable,
EnumInNestedNS? fooEnum,
UnionInNestedNSTypeId? fooUnionType,
dynamic? fooUnion,
namespace_a_namespace_b.StructInNestedNSObjectBuilder? fooStruct,
})
: _fooTable = fooTable,
_fooEnum = fooEnum,
@@ -156,30 +148,23 @@ class TableInFirstNSObjectBuilder extends fb.ObjectBuilder {
/// Finish building, and store into the [fbBuilder].
@override
int finish(
fb.Builder fbBuilder) {
assert(fbBuilder != null);
final int fooTableOffset = _fooTable?.getOrCreateOffset(fbBuilder);
final int fooUnionOffset = _fooUnion?.getOrCreateOffset(fbBuilder);
int finish(fb.Builder fbBuilder) {
final int? fooTableOffset = _fooTable?.getOrCreateOffset(fbBuilder);
final int? fooUnionOffset = _fooUnion?.getOrCreateOffset(fbBuilder);
fbBuilder.startTable();
if (fooTableOffset != null) {
fbBuilder.addOffset(0, fooTableOffset);
}
fbBuilder.addOffset(0, fooTableOffset);
fbBuilder.addInt8(1, _fooEnum?.value);
fbBuilder.addUint8(2, _fooUnionType?.value);
if (fooUnionOffset != null) {
fbBuilder.addOffset(3, fooUnionOffset);
}
fbBuilder.addOffset(3, fooUnionOffset);
if (_fooStruct != null) {
fbBuilder.addStruct(4, _fooStruct.finish(fbBuilder));
fbBuilder.addStruct(4, _fooStruct!.finish(fbBuilder));
}
return fbBuilder.endTable();
}
/// Convenience method to serialize to byte list.
@override
Uint8List toBytes([String fileIdentifier]) {
Uint8List toBytes([String? fileIdentifier]) {
fb.Builder fbBuilder = new fb.Builder();
int offset = finish(fbBuilder);
return fbBuilder.finish(offset, fileIdentifier);
@@ -197,7 +182,7 @@ class SecondTableInA {
final fb.BufferContext _bc;
final int _bcOffset;
namespace_c.TableInC get referToC => namespace_c.TableInC.reader.vTableGet(_bc, _bcOffset, 4, null);
namespace_c.TableInC? get referToC => namespace_c.TableInC.reader.vTableGetNullable(_bc, _bcOffset, 4);
@override
String toString() {
@@ -207,26 +192,22 @@ class SecondTableInA {
SecondTableInAT unpack() => SecondTableInAT(
referToC: referToC?.unpack());
static int pack(fb.Builder fbBuilder, SecondTableInAT object) {
static int pack(fb.Builder fbBuilder, SecondTableInAT? object) {
if (object == null) return 0;
return object.pack(fbBuilder);
}
}
class SecondTableInAT {
namespace_c.TableInCT referToC;
namespace_c.TableInCT? referToC;
SecondTableInAT({
this.referToC});
int pack(fb.Builder fbBuilder) {
assert(fbBuilder != null);
final int referToCOffset = referToC?.pack(fbBuilder);
final int? referToCOffset = referToC?.pack(fbBuilder);
fbBuilder.startTable();
if (referToCOffset != null) {
fbBuilder.addOffset(0, referToCOffset);
}
fbBuilder.addOffset(0, referToCOffset);
return fbBuilder.endTable();
}
@@ -245,9 +226,7 @@ class _SecondTableInAReader extends fb.TableReader<SecondTableInA> {
}
class SecondTableInABuilder {
SecondTableInABuilder(this.fbBuilder) {
assert(fbBuilder != null);
}
SecondTableInABuilder(this.fbBuilder) {}
final fb.Builder fbBuilder;
@@ -255,7 +234,7 @@ class SecondTableInABuilder {
fbBuilder.startTable();
}
int addReferToCOffset(int offset) {
int addReferToCOffset(int? offset) {
fbBuilder.addOffset(0, offset);
return fbBuilder.offset;
}
@@ -266,30 +245,25 @@ class SecondTableInABuilder {
}
class SecondTableInAObjectBuilder extends fb.ObjectBuilder {
final namespace_c.TableInCObjectBuilder _referToC;
final namespace_c.TableInCObjectBuilder? _referToC;
SecondTableInAObjectBuilder({
namespace_c.TableInCObjectBuilder referToC,
namespace_c.TableInCObjectBuilder? referToC,
})
: _referToC = referToC;
/// Finish building, and store into the [fbBuilder].
@override
int finish(
fb.Builder fbBuilder) {
assert(fbBuilder != null);
final int referToCOffset = _referToC?.getOrCreateOffset(fbBuilder);
int finish(fb.Builder fbBuilder) {
final int? referToCOffset = _referToC?.getOrCreateOffset(fbBuilder);
fbBuilder.startTable();
if (referToCOffset != null) {
fbBuilder.addOffset(0, referToCOffset);
}
fbBuilder.addOffset(0, referToCOffset);
return fbBuilder.endTable();
}
/// Convenience method to serialize to byte list.
@override
Uint8List toBytes([String fileIdentifier]) {
Uint8List toBytes([String? fileIdentifier]) {
fb.Builder fbBuilder = new fb.Builder();
int offset = finish(fbBuilder);
return fbBuilder.finish(offset, fileIdentifier);

View File

@@ -1,5 +1,5 @@
// automatically generated by the FlatBuffers compiler, do not modify
// ignore_for_file: unused_import, unused_field, unused_local_variable
// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable
library namespace_c;
@@ -20,8 +20,8 @@ class TableInC {
final fb.BufferContext _bc;
final int _bcOffset;
namespace_a.TableInFirstNS get referToA1 => namespace_a.TableInFirstNS.reader.vTableGet(_bc, _bcOffset, 4, null);
namespace_a.SecondTableInA get referToA2 => namespace_a.SecondTableInA.reader.vTableGet(_bc, _bcOffset, 6, null);
namespace_a.TableInFirstNS? get referToA1 => namespace_a.TableInFirstNS.reader.vTableGetNullable(_bc, _bcOffset, 4);
namespace_a.SecondTableInA? get referToA2 => namespace_a.SecondTableInA.reader.vTableGetNullable(_bc, _bcOffset, 6);
@override
String toString() {
@@ -32,32 +32,26 @@ class TableInC {
referToA1: referToA1?.unpack(),
referToA2: referToA2?.unpack());
static int pack(fb.Builder fbBuilder, TableInCT object) {
static int pack(fb.Builder fbBuilder, TableInCT? object) {
if (object == null) return 0;
return object.pack(fbBuilder);
}
}
class TableInCT {
namespace_a.TableInFirstNST referToA1;
namespace_a.SecondTableInAT referToA2;
namespace_a.TableInFirstNST? referToA1;
namespace_a.SecondTableInAT? referToA2;
TableInCT({
this.referToA1,
this.referToA2});
int pack(fb.Builder fbBuilder) {
assert(fbBuilder != null);
final int referToA1Offset = referToA1?.pack(fbBuilder);
final int referToA2Offset = referToA2?.pack(fbBuilder);
final int? referToA1Offset = referToA1?.pack(fbBuilder);
final int? referToA2Offset = referToA2?.pack(fbBuilder);
fbBuilder.startTable();
if (referToA1Offset != null) {
fbBuilder.addOffset(0, referToA1Offset);
}
if (referToA2Offset != null) {
fbBuilder.addOffset(1, referToA2Offset);
}
fbBuilder.addOffset(0, referToA1Offset);
fbBuilder.addOffset(1, referToA2Offset);
return fbBuilder.endTable();
}
@@ -76,9 +70,7 @@ class _TableInCReader extends fb.TableReader<TableInC> {
}
class TableInCBuilder {
TableInCBuilder(this.fbBuilder) {
assert(fbBuilder != null);
}
TableInCBuilder(this.fbBuilder) {}
final fb.Builder fbBuilder;
@@ -86,11 +78,11 @@ class TableInCBuilder {
fbBuilder.startTable();
}
int addReferToA1Offset(int offset) {
int addReferToA1Offset(int? offset) {
fbBuilder.addOffset(0, offset);
return fbBuilder.offset;
}
int addReferToA2Offset(int offset) {
int addReferToA2Offset(int? offset) {
fbBuilder.addOffset(1, offset);
return fbBuilder.offset;
}
@@ -101,37 +93,30 @@ class TableInCBuilder {
}
class TableInCObjectBuilder extends fb.ObjectBuilder {
final namespace_a.TableInFirstNSObjectBuilder _referToA1;
final namespace_a.SecondTableInAObjectBuilder _referToA2;
final namespace_a.TableInFirstNSObjectBuilder? _referToA1;
final namespace_a.SecondTableInAObjectBuilder? _referToA2;
TableInCObjectBuilder({
namespace_a.TableInFirstNSObjectBuilder referToA1,
namespace_a.SecondTableInAObjectBuilder referToA2,
namespace_a.TableInFirstNSObjectBuilder? referToA1,
namespace_a.SecondTableInAObjectBuilder? referToA2,
})
: _referToA1 = referToA1,
_referToA2 = referToA2;
/// Finish building, and store into the [fbBuilder].
@override
int finish(
fb.Builder fbBuilder) {
assert(fbBuilder != null);
final int referToA1Offset = _referToA1?.getOrCreateOffset(fbBuilder);
final int referToA2Offset = _referToA2?.getOrCreateOffset(fbBuilder);
int finish(fb.Builder fbBuilder) {
final int? referToA1Offset = _referToA1?.getOrCreateOffset(fbBuilder);
final int? referToA2Offset = _referToA2?.getOrCreateOffset(fbBuilder);
fbBuilder.startTable();
if (referToA1Offset != null) {
fbBuilder.addOffset(0, referToA1Offset);
}
if (referToA2Offset != null) {
fbBuilder.addOffset(1, referToA2Offset);
}
fbBuilder.addOffset(0, referToA1Offset);
fbBuilder.addOffset(1, referToA2Offset);
return fbBuilder.endTable();
}
/// Convenience method to serialize to byte list.
@override
Uint8List toBytes([String fileIdentifier]) {
Uint8List toBytes([String? fileIdentifier]) {
fb.Builder fbBuilder = new fb.Builder();
int offset = finish(fbBuilder);
return fbBuilder.finish(offset, fileIdentifier);