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

View File

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

View File

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

View File

@@ -6,37 +6,26 @@ import 'types.dart';
/// The main builder class for creation of a FlexBuffer. /// The main builder class for creation of a FlexBuffer.
class Builder { class Builder {
ByteData _buffer; ByteData _buffer;
List<_StackValue> _stack; List<_StackValue> _stack = [];
List<_StackPointer> _stackPointers; List<_StackPointer> _stackPointers = [];
int _offset; int _offset = 0;
bool _finished; bool _finished = false;
Map<String, _StackValue> _stringCache; Map<String, _StackValue> _stringCache = {};
Map<String, _StackValue> _keyCache; Map<String, _StackValue> _keyCache = {};
Map<_KeysHash, _StackValue> _keyVectorCache; Map<_KeysHash, _StackValue> _keyVectorCache = {};
Map<int, _StackValue> _indirectIntCache; Map<int, _StackValue> _indirectIntCache = {};
Map<double, _StackValue> _indirectDoubleCache; Map<double, _StackValue> _indirectDoubleCache = {};
/// Instantiate the builder if you intent to gradually build up the buffer by calling /// 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. /// 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. /// The default size of internal buffer is set to 2048. Provide a different value in order to avoid buffer copies.
Builder({int size = 2048}) { Builder({int size = 2048}) : _buffer = ByteData(size) {}
_buffer = ByteData(size);
_stack = [];
_stackPointers = [];
_offset = 0;
_finished = false;
_stringCache = {};
_keyCache = {};
_keyVectorCache = {};
_indirectIntCache = {};
_indirectDoubleCache = {};
}
/// Use this method in order to turn an object into a FlexBuffer directly. /// 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. /// 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(); final builder = Builder();
builder._add(value); builder._add(value);
final buffer = builder.finish(); final buffer = builder.finish();
@@ -45,7 +34,7 @@ class Builder {
return byteData.buffer; return byteData.buffer;
} }
void _add(Object value) { void _add(Object? value) {
if (value == null) { if (value == null) {
addNull(); addNull();
} else if (value is bool) { } else if (value is bool) {
@@ -106,7 +95,7 @@ class Builder {
void addString(String value) { void addString(String value) {
_integrityCheckOnValueAddition(); _integrityCheckOnValueAddition();
if (_stringCache.containsKey(value)) { if (_stringCache.containsKey(value)) {
_stack.add(_stringCache[value]); _stack.add(_stringCache[value]!);
return; return;
} }
final utf8String = utf8.encode(value); final utf8String = utf8.encode(value);
@@ -118,7 +107,8 @@ class Builder {
final newOffset = _newOffset(length + 1); final newOffset = _newOffset(length + 1);
_pushBuffer(utf8String); _pushBuffer(utf8String);
_offset = newOffset; _offset = newOffset;
final stackValue = _StackValue.WithOffset(stringOffset, ValueType.String, bitWidth); final stackValue =
_StackValue.WithOffset(stringOffset, ValueType.String, bitWidth);
_stack.add(stackValue); _stack.add(stackValue);
_stringCache[value] = stackValue; _stringCache[value] = stackValue;
} }
@@ -129,7 +119,7 @@ class Builder {
void addKey(String value) { void addKey(String value) {
_integrityCheckOnKeyAddition(); _integrityCheckOnKeyAddition();
if (_keyCache.containsKey(value)) { if (_keyCache.containsKey(value)) {
_stack.add(_keyCache[value]); _stack.add(_keyCache[value]!);
return; return;
} }
final utf8String = utf8.encode(value); final utf8String = utf8.encode(value);
@@ -138,7 +128,8 @@ class Builder {
final newOffset = _newOffset(length + 1); final newOffset = _newOffset(length + 1);
_pushBuffer(utf8String); _pushBuffer(utf8String);
_offset = newOffset; _offset = newOffset;
final stackValue = _StackValue.WithOffset(keyOffset, ValueType.Key, BitWidth.width8); final stackValue =
_StackValue.WithOffset(keyOffset, ValueType.Key, BitWidth.width8);
_stack.add(stackValue); _stack.add(stackValue);
_keyCache[value] = stackValue; _keyCache[value] = stackValue;
} }
@@ -156,7 +147,8 @@ class Builder {
final newOffset = _newOffset(length); final newOffset = _newOffset(length);
_pushBuffer(value.asUint8List()); _pushBuffer(value.asUint8List());
_offset = newOffset; _offset = newOffset;
final stackValue = _StackValue.WithOffset(blobOffset, ValueType.Blob, bitWidth); final stackValue =
_StackValue.WithOffset(blobOffset, ValueType.Blob, bitWidth);
_stack.add(stackValue); _stack.add(stackValue);
} }
@@ -169,7 +161,7 @@ class Builder {
void addIntIndirectly(int value, {bool cache = false}) { void addIntIndirectly(int value, {bool cache = false}) {
_integrityCheckOnValueAddition(); _integrityCheckOnValueAddition();
if (_indirectIntCache.containsKey(value)) { if (_indirectIntCache.containsKey(value)) {
_stack.add(_indirectIntCache[value]); _stack.add(_indirectIntCache[value]!);
return; return;
} }
final stackValue = _StackValue.WithInt(value); final stackValue = _StackValue.WithInt(value);
@@ -177,7 +169,8 @@ class Builder {
final newOffset = _newOffset(byteWidth); final newOffset = _newOffset(byteWidth);
final valueOffset = _offset; final valueOffset = _offset;
_pushBuffer(stackValue.asU8List(stackValue.width)); _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); _stack.add(stackOffset);
_offset = newOffset; _offset = newOffset;
if (cache) { if (cache) {
@@ -193,7 +186,7 @@ class Builder {
void addDoubleIndirectly(double value, {bool cache = false}) { void addDoubleIndirectly(double value, {bool cache = false}) {
_integrityCheckOnValueAddition(); _integrityCheckOnValueAddition();
if (cache && _indirectDoubleCache.containsKey(value)) { if (cache && _indirectDoubleCache.containsKey(value)) {
_stack.add(_indirectDoubleCache[value]); _stack.add(_indirectDoubleCache[value]!);
return; return;
} }
final stackValue = _StackValue.WithDouble(value); final stackValue = _StackValue.WithDouble(value);
@@ -201,7 +194,8 @@ class Builder {
final newOffset = _newOffset(byteWidth); final newOffset = _newOffset(byteWidth);
final valueOffset = _offset; final valueOffset = _offset;
_pushBuffer(stackValue.asU8List(stackValue.width)); _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); _stack.add(stackOffset);
_offset = newOffset; _offset = newOffset;
if (cache) { if (cache) {
@@ -258,8 +252,10 @@ class Builder {
tmp._offset = _offset; tmp._offset = _offset;
tmp._stack = List.from(_stack); tmp._stack = List.from(_stack);
tmp._stackPointers = List.from(_stackPointers); tmp._stackPointers = List.from(_stackPointers);
tmp._buffer.buffer.asUint8List().setAll(0, _buffer.buffer.asUint8List(0, _offset)); tmp._buffer.buffer
for (var i = 0; i < tmp._stackPointers.length; i++){ .asUint8List()
.setAll(0, _buffer.buffer.asUint8List(0, _offset));
for (var i = 0; i < tmp._stackPointers.length; i++) {
tmp.end(); tmp.end();
} }
final buffer = tmp.finish(); final buffer = tmp.finish();
@@ -267,14 +263,15 @@ class Builder {
bd.buffer.asUint8List().setAll(0, buffer); bd.buffer.asUint8List().setAll(0, buffer);
return bd.buffer; return bd.buffer;
} }
void _integrityCheckOnValueAddition() { void _integrityCheckOnValueAddition() {
if (_finished) { if (_finished) {
throw StateError('Adding values after finish is prohibited'); throw StateError('Adding values after finish is prohibited');
} }
if (_stackPointers.isNotEmpty && _stackPointers.last.isVector == false) { if (_stackPointers.isNotEmpty && _stackPointers.last.isVector == false) {
if (_stack.last.type != ValueType.Key) { 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() { void _finish() {
if (_stack.length != 1) { 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 value = _stack[0];
final byteWidth = _align(value.elementWidth(_offset, 0)); final byteWidth = _align(value.elementWidth(_offset, 0));
@@ -299,8 +297,9 @@ class Builder {
_writeUInt(byteWidth, 1); _writeUInt(byteWidth, 1);
_finished = true; _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 bitWidth = BitWidthUtil.uwidth(vecLength);
var prefixElements = 1; var prefixElements = 1;
if (keys != null) { if (keys != null) {
@@ -327,7 +326,9 @@ class Builder {
} }
} }
final byteWidth = _align(bitWidth); 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) { if (keys != null) {
_writeStackValue(keys, byteWidth); _writeStackValue(keys, byteWidth);
_writeUInt(1 << keys.width.index, byteWidth); _writeUInt(1 << keys.width.index, byteWidth);
@@ -348,7 +349,8 @@ class Builder {
return _StackValue.WithOffset(vecOffset, ValueType.Map, bitWidth); return _StackValue.WithOffset(vecOffset, ValueType.Map, bitWidth);
} }
if (typed) { 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, vType, bitWidth);
} }
return _StackValue.WithOffset(vecOffset, ValueType.Vector, bitWidth); return _StackValue.WithOffset(vecOffset, ValueType.Vector, bitWidth);
@@ -363,12 +365,13 @@ class Builder {
void _sortKeysAndEndMap(_StackPointer pointer) { void _sortKeysAndEndMap(_StackPointer pointer) {
if (((_stack.length - pointer.stackPosition) & 1) == 1) { 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; var sorted = true;
for (var i = pointer.stackPosition; i < _stack.length - 2; i += 2) { 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; sorted = false;
break; break;
} }
@@ -394,12 +397,12 @@ class Builder {
} }
_endMap(pointer); _endMap(pointer);
} }
void _endMap(_StackPointer pointer) { void _endMap(_StackPointer pointer) {
final vecLength = (_stack.length - pointer.stackPosition) >> 1; final vecLength = (_stack.length - pointer.stackPosition) >> 1;
final offsets = <int>[]; final offsets = <int>[];
for (var i = pointer.stackPosition; i < _stack.length; i += 2) { for (var i = pointer.stackPosition; i < _stack.length; i += 2) {
offsets.add(_stack[i].offset); offsets.add(_stack[i].offset!);
} }
final keysHash = _KeysHash(offsets); final keysHash = _KeysHash(offsets);
var keysStackValue; var keysStackValue;
@@ -409,21 +412,23 @@ class Builder {
keysStackValue = _createVector(pointer.stackPosition, vecLength, 2); keysStackValue = _createVector(pointer.stackPosition, vecLength, 2);
_keyVectorCache[keysHash] = keysStackValue; _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.removeRange(pointer.stackPosition, _stack.length);
_stack.add(vec); _stack.add(vec);
} }
bool _shouldFlip(_StackValue v1, _StackValue v2) { bool _shouldFlip(_StackValue v1, _StackValue v2) {
if (v1.type != ValueType.Key || v2.type != ValueType.Key) { 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 c1, c2;
var index = 0; var index = 0;
do { do {
c1 = _buffer.getUint8(v1.offset + index); c1 = _buffer.getUint8(v1.offset! + index);
c2 = _buffer.getUint8(v2.offset + index); c2 = _buffer.getUint8(v2.offset! + index);
if (c2 < c1) return true; if (c2 < c1) return true;
if (c1 < c2) return false; if (c1 < c2) return false;
index += 1; index += 1;
@@ -440,11 +445,12 @@ class Builder {
void _writeStackValue(_StackValue value, int byteWidth) { void _writeStackValue(_StackValue value, int byteWidth) {
final newOffset = _newOffset(byteWidth); final newOffset = _newOffset(byteWidth);
if (value.isOffset) { if (value.isOffset) {
final relativeOffset = _offset - value.offset; final relativeOffset = _offset - value.offset!;
if (byteWidth == 8 || relativeOffset < (1 << (byteWidth * 8))) { if (byteWidth == 8 || relativeOffset < (1 << (byteWidth * 8))) {
_writeUInt(relativeOffset, byteWidth); _writeUInt(relativeOffset, byteWidth);
} else { } 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 { } else {
_pushBuffer(value.asU8List(BitWidthUtil.fromByteWidth(byteWidth))); _pushBuffer(value.asU8List(BitWidthUtil.fromByteWidth(byteWidth)));
@@ -467,16 +473,13 @@ class Builder {
} }
if (prevSize < size) { if (prevSize < size) {
final newBuf = ByteData(size); final newBuf = ByteData(size);
newBuf.buffer newBuf.buffer.asUint8List().setAll(0, _buffer.buffer.asUint8List());
.asUint8List()
.setAll(0, _buffer.buffer.asUint8List());
} }
return newOffset; return newOffset;
} }
void _pushInt(int value, BitWidth width) { void _pushInt(int value, BitWidth width) {
switch (width) { switch (width) {
case BitWidth.width8: case BitWidth.width8:
_buffer.setInt8(_offset, value); _buffer.setInt8(_offset, value);
break; break;
@@ -494,7 +497,6 @@ class Builder {
void _pushUInt(int value, BitWidth width) { void _pushUInt(int value, BitWidth width) {
switch (width) { switch (width) {
case BitWidth.width8: case BitWidth.width8:
_buffer.setUint8(_offset, value); _buffer.setUint8(_offset, value);
break; break;
@@ -516,37 +518,39 @@ class Builder {
} }
class _StackValue { class _StackValue {
Object _value; late Object _value;
int _offset; int? _offset;
ValueType _type; ValueType _type;
BitWidth _width; BitWidth _width;
_StackValue.WithNull() {
_type = ValueType.Null; _StackValue.WithNull()
_width = BitWidth.width8; : _type = ValueType.Null,
} _width = BitWidth.width8 {}
_StackValue.WithInt(int value) {
_type = value != null ? ValueType.Int : ValueType.Null; _StackValue.WithInt(int value)
_width = BitWidthUtil.width(value); : _type = ValueType.Int,
_value = value; _width = BitWidthUtil.width(value),
} _value = value {}
_StackValue.WithBool(bool value) {
_type = value != null ? ValueType.Bool : ValueType.Null; _StackValue.WithBool(bool value)
_width = BitWidth.width8; : _type = ValueType.Bool,
_value = value; _width = BitWidth.width8,
} _value = value {}
_StackValue.WithDouble(double value) {
_type = value != null ? ValueType.Float : ValueType.Null; _StackValue.WithDouble(double value)
_width = BitWidthUtil.width(value); : _type = ValueType.Float,
_value = value; _width = BitWidthUtil.width(value),
} _value = value {}
_StackValue.WithOffset(int value, ValueType type, BitWidth width) {
_offset = value; _StackValue.WithOffset(int value, ValueType type, BitWidth width)
_type = type; : _offset = value,
_width = width; _type = type,
} _width = width {}
BitWidth storedWidth({BitWidth width = BitWidth.width8}) { 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}) { int storedPackedType({BitWidth width = BitWidth.width8}) {
@@ -555,16 +559,18 @@ class _StackValue {
BitWidth elementWidth(int size, int index) { BitWidth elementWidth(int size, int index) {
if (ValueTypeUtils.isInline(_type)) return _width; 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 width = 1 << i;
final offsetLoc = size + BitWidthUtil.paddingSize(size, width) + index * width; final offsetLoc =
final offset = offsetLoc - _offset; size + BitWidthUtil.paddingSize(size, width) + index * width;
final bitWidth = BitWidthUtil.uwidth(offset); final bitWidth = BitWidthUtil.uwidth(offset);
if (1 << bitWidth.index == width) { if (1 << bitWidth.index == width) {
return bitWidth; 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) { List<int> asU8List(BitWidth width) {
@@ -572,30 +578,30 @@ class _StackValue {
if (_type == ValueType.Float) { if (_type == ValueType.Float) {
if (width == BitWidth.width32) { if (width == BitWidth.width32) {
final result = ByteData(4); final result = ByteData(4);
result.setFloat32(0, _value, Endian.little); result.setFloat32(0, _value as double, Endian.little);
return result.buffer.asUint8List(); return result.buffer.asUint8List();
} else { } else {
final result = ByteData(8); final result = ByteData(8);
result.setFloat64(0, _value, Endian.little); result.setFloat64(0, _value as double, Endian.little);
return result.buffer.asUint8List(); return result.buffer.asUint8List();
} }
} else { } else {
switch(width) { switch (width) {
case BitWidth.width8: case BitWidth.width8:
final result = ByteData(1); final result = ByteData(1);
result.setInt8(0, _value); result.setInt8(0, _value as int);
return result.buffer.asUint8List(); return result.buffer.asUint8List();
case BitWidth.width16: case BitWidth.width16:
final result = ByteData(2); final result = ByteData(2);
result.setInt16(0, _value, Endian.little); result.setInt16(0, _value as int, Endian.little);
return result.buffer.asUint8List(); return result.buffer.asUint8List();
case BitWidth.width32: case BitWidth.width32:
final result = ByteData(4); final result = ByteData(4);
result.setInt32(0, _value, Endian.little); result.setInt32(0, _value as int, Endian.little);
return result.buffer.asUint8List(); return result.buffer.asUint8List();
case BitWidth.width64: case BitWidth.width64:
final result = ByteData(8); final result = ByteData(8);
result.setInt64(0, _value, Endian.little); result.setInt64(0, _value as int, Endian.little);
return result.buffer.asUint8List(); return result.buffer.asUint8List();
} }
} }
@@ -607,11 +613,12 @@ class _StackValue {
} }
if (_type == ValueType.Bool) { if (_type == ValueType.Bool) {
final result = ByteData(1); final result = ByteData(1);
result.setInt8(0, _value ? 1 : 0); result.setInt8(0, _value as bool ? 1 : 0);
return result.buffer.asUint8List(); 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 { ValueType get type {
@@ -625,7 +632,8 @@ class _StackValue {
bool get isOffset { bool get isOffset {
return !ValueTypeUtils.isInline(_type); return !ValueTypeUtils.isInline(_type);
} }
int get offset => _offset;
int? get offset => _offset;
bool get isFloat32 { bool get isFloat32 {
return _type == ValueType.Float && _width == BitWidth.width32; return _type == ValueType.Float && _width == BitWidth.width32;

View File

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

View File

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

View File

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

View File

@@ -58,18 +58,18 @@ void main() {
{ {
var flx = Builder(); var flx = Builder();
flx.addString('hello 😱'); 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() var flx = Builder()
..startVector() ..startVector()
..addInt(1) ..addInt(1)
..addInt(2) ..addInt(2)
..end() ..end();
;
expect(flx.finish(), [1, 2, 2, 64, 1]); expect(flx.finish(), [1, 2, 2, 64, 1]);
} }
{ {
@@ -77,8 +77,7 @@ void main() {
..startVector() ..startVector()
..addInt(-1) ..addInt(-1)
..addInt(256) ..addInt(256)
..end() ..end();
;
expect(flx.finish(), [255, 255, 0, 1, 4, 65, 1]); expect(flx.finish(), [255, 255, 0, 1, 4, 65, 1]);
} }
{ {
@@ -86,8 +85,7 @@ void main() {
..startVector() ..startVector()
..addInt(-45) ..addInt(-45)
..addInt(256000) ..addInt(256000)
..end() ..end();
;
expect(flx.finish(), [211, 255, 255, 255, 0, 232, 3, 0, 8, 66, 1]); expect(flx.finish(), [211, 255, 255, 255, 0, 232, 3, 0, 8, 66, 1]);
} }
{ {
@@ -95,9 +93,28 @@ void main() {
..startVector() ..startVector()
..addDouble(1.1) ..addDouble(1.1)
..addDouble(-256) ..addDouble(-256)
..end() ..end();
; expect(flx.finish(), [
expect(flx.finish(), [154, 153, 153, 153, 153, 153, 241, 63, 0, 0, 0, 0, 0, 0, 112, 192, 16, 75, 1]); 154,
153,
153,
153,
153,
153,
241,
63,
0,
0,
0,
0,
0,
0,
112,
192,
16,
75,
1
]);
} }
{ {
var flx = Builder() var flx = Builder()
@@ -105,8 +122,7 @@ void main() {
..addInt(1) ..addInt(1)
..addInt(2) ..addInt(2)
..addInt(4) ..addInt(4)
..end() ..end();
;
expect(flx.finish(), [1, 2, 4, 3, 76, 1]); expect(flx.finish(), [1, 2, 4, 3, 76, 1]);
} }
{ {
@@ -115,19 +131,17 @@ void main() {
..addInt(-1) ..addInt(-1)
..addInt(256) ..addInt(256)
..addInt(4) ..addInt(4)
..end() ..end();
;
expect(flx.finish(), [255, 255, 0, 1, 4, 0, 6, 77, 1]); expect(flx.finish(), [255, 255, 0, 1, 4, 0, 6, 77, 1]);
} }
{ {
var flx = Builder() var flx = Builder()
..startVector() ..startVector()
..startVector() ..startVector()
..addInt(61) ..addInt(61)
..end()
..addInt(64)
..end() ..end()
; ..addInt(64)
..end();
expect(flx.finish(), [1, 61, 2, 2, 64, 44, 4, 4, 40, 1]); expect(flx.finish(), [1, 61, 2, 2, 64, 44, 4, 4, 40, 1]);
} }
{ {
@@ -136,9 +150,31 @@ void main() {
..addString('foo') ..addString('foo')
..addString('bar') ..addString('bar')
..addString('baz') ..addString('baz')
..end() ..end();
; expect(flx.finish(), [
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]); 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() var flx = Builder()
@@ -149,9 +185,34 @@ void main() {
..addString('foo') ..addString('foo')
..addString('bar') ..addString('bar')
..addString('baz') ..addString('baz')
..end() ..end();
; expect(flx.finish(), [
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]); 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() var flx = Builder()
@@ -159,8 +220,7 @@ void main() {
..addBool(true) ..addBool(true)
..addBool(false) ..addBool(false)
..addBool(true) ..addBool(true)
..end() ..end();
;
expect(flx.finish(), [3, 1, 0, 1, 3, 144, 1]); expect(flx.finish(), [3, 1, 0, 1, 3, 144, 1]);
} }
{ {
@@ -171,29 +231,83 @@ void main() {
..addInt(-5) ..addInt(-5)
..addDouble(1.3) ..addDouble(1.3)
..addBool(true) ..addBool(true)
..end() ..end();
;
expect(flx.finish(), [ expect(flx.finish(), [
3, 102, 111, 111, 0, 0, 0, 0, 3,
5, 0, 0, 0, 0, 0, 0, 0, 102,
15, 0, 0, 0, 0, 0, 0, 0, 111,
1, 0, 0, 0, 0, 0, 0, 0, 111,
251, 255, 255, 255, 255, 255, 255, 255, 0,
205, 204, 204, 204, 204, 204, 244, 63, 0,
1, 0, 0, 0, 0, 0, 0, 0, 0,
20, 4, 4, 15, 104, 45, 43, 1]); 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() var flx = Builder()
..startMap() ..startMap()
..addKey('a') ..addKey('a')
..addInt(12) ..addInt(12)
..end() ..end();
;
expect(flx.finish(), [97, 0, 1, 3, 1, 1, 1, 12, 4, 2, 36, 1]); expect(flx.finish(), [97, 0, 1, 3, 1, 1, 1, 12, 4, 2, 36, 1]);
} }
{ {
@@ -203,105 +317,270 @@ void main() {
..addInt(12) ..addInt(12)
..addKey('') ..addKey('')
..addInt(45) ..addInt(45)
..end() ..end();
; expect(
expect(flx.finish(), [97, 0, 0, 2, 2, 5, 2, 1, 2, 45, 12, 4, 4, 4, 36, 1]); flx.finish(), [97, 0, 0, 2, 2, 5, 2, 1, 2, 45, 12, 4, 4, 4, 36, 1]);
} }
{ {
var flx = Builder() var flx = Builder()
..startVector() ..startVector()
..startMap() ..startMap()
..addKey('something') ..addKey('something')
..addInt(12) ..addInt(12)
..end()
..startMap()
..addKey('something')
..addInt(45)
..end()
..end() ..end()
; ..startMap()
expect(flx.finish(), [115, 111, 109, 101, 116, 104, 105, 110, 103, 0, ..addKey('something')
1, 11, 1, 1, 1, 12, 4, 6, 1, 1, 45, 4, 2, 8, 4, 36, 36, 4, 40, 1]); ..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() var flx = Builder()..addBlob(Uint8List.fromList([1, 2, 3]).buffer);
..addBlob(Uint8List.fromList([1, 2, 3]).buffer)
;
expect(flx.finish(), [3, 1, 2, 3, 3, 100, 1]); expect(flx.finish(), [3, 1, 2, 3, 3, 100, 1]);
} }
}); });
test('build from object', (){ test('build from object', () {
expect(Builder.buildFromObject(Uint8List.fromList([1, 2, 3]).buffer).asUint8List(), [3, 1, 2, 3, 3, 100, 1]); 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(null).asUint8List(), [0, 0, 1]);
expect(Builder.buildFromObject(true).asUint8List(), [1, 104, 1]); expect(Builder.buildFromObject(true).asUint8List(), [1, 104, 1]);
expect(Builder.buildFromObject(false).asUint8List(), [0, 104, 1]); expect(Builder.buildFromObject(false).asUint8List(), [0, 104, 1]);
expect(Builder.buildFromObject(25).asUint8List(), [25, 4, 1]); expect(Builder.buildFromObject(25).asUint8List(), [25, 4, 1]);
expect(Builder.buildFromObject(-250).asUint8List(), [6, 255, 5, 2]); expect(Builder.buildFromObject(-250).asUint8List(), [6, 255, 5, 2]);
expect(Builder.buildFromObject(-2.50).asUint8List(), [0, 0, 32, 192, 14, 4]); expect(
expect(Builder.buildFromObject('Maxim').asUint8List(), [5, 77, 97, 120, 105, 109, 0, 6, 20, 1]); Builder.buildFromObject(-2.50).asUint8List(), [0, 0, 32, 192, 14, 4]);
expect(Builder.buildFromObject([1, 3.3, 'max', true, null, false]).asUint8List(), [ expect(Builder.buildFromObject('Maxim').asUint8List(),
3, 109, 97, 120, 0, 0, 0, 0, [5, 77, 97, 120, 105, 109, 0, 6, 20, 1]);
6, 0, 0, 0, 0, 0, 0, 0, expect(
1, 0, 0, 0, 0, 0, 0, 0, Builder.buildFromObject([1, 3.3, 'max', true, null, false])
102, 102, 102, 102, 102, 102, 10, 64, .asUint8List(),
31, 0, 0, 0, 0, 0, 0, 0, [
1, 0, 0, 0, 0, 0, 0, 0, 3,
0, 0, 0, 0, 0, 0, 0, 0, 109,
0, 0, 0, 0, 0, 0, 0, 0, 97,
4, 15, 20, 104, 0, 104, 54, 43, 1 120,
]); 0,
expect(Builder.buildFromObject([{'something':12}, {'something': 45}]).asUint8List(), [ 0,
115, 111, 109, 101, 116, 104, 105, 110, 103, 0, 0,
1, 11, 1, 1, 1, 12, 4, 6, 1, 1, 45, 4, 2, 8, 4, 36, 36, 4, 40, 1 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', (){ test('add double indirectly', () {
var flx = Builder() var flx = Builder()..addDoubleIndirectly(0.1);
..addDoubleIndirectly(0.1)
;
expect(flx.finish(), [154, 153, 153, 153, 153, 153, 185, 63, 8, 35, 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() var flx = Builder()
..startVector() ..startVector()
..addDoubleIndirectly(0.1, cache: true) ..addDoubleIndirectly(0.1, cache: true)
..addDoubleIndirectly(0.1, cache: true) ..addDoubleIndirectly(0.1, cache: true)
..addDoubleIndirectly(0.1, cache: true) ..addDoubleIndirectly(0.1, cache: true)
..addDoubleIndirectly(0.1, cache: true) ..addDoubleIndirectly(0.1, cache: true)
..end() ..end();
; expect(flx.finish(), [
expect(flx.finish(), [154, 153, 153, 153, 153, 153, 185, 63, 154,
4, 9, 10, 11, 12, 35, 35, 35, 35, 8, 40, 1]); 153,
153,
153,
153,
153,
185,
63,
4,
9,
10,
11,
12,
35,
35,
35,
35,
8,
40,
1
]);
}); });
test('add int indirectly', (){ test('add int indirectly', () {
var flx = Builder() var flx = Builder()..addIntIndirectly(2345234523452345);
..addIntIndirectly(2345234523452345)
;
expect(flx.finish(), [185, 115, 175, 118, 250, 84, 8, 0, 8, 27, 1]); 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() var flx = Builder()
..startVector() ..startVector()
..addIntIndirectly(2345234523452345, cache: true) ..addIntIndirectly(2345234523452345, cache: true)
..addIntIndirectly(2345234523452345, cache: true) ..addIntIndirectly(2345234523452345, cache: true)
..addIntIndirectly(2345234523452345, cache: true) ..addIntIndirectly(2345234523452345, cache: true)
..addIntIndirectly(2345234523452345, cache: true) ..addIntIndirectly(2345234523452345, cache: true)
..end() ..end();
; expect(flx.finish(), [
expect(flx.finish(), [185, 115, 175, 118, 250, 84, 8, 0, 185,
4, 9, 10, 11, 12, 27, 27, 27, 27, 8, 40, 1]); 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(); var flx = Builder();
flx.startVector(); flx.startVector();
flx.addInt(12); flx.addInt(12);
@@ -312,4 +591,3 @@ void main() {
expect(flx.snapshot().asUint8List(), [12, 24, 45, 3, 76, 1]); 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); expect(ValueTypeUtils.isFixedTypedVector(ValueType.VectorInt), isFalse);
}); });
test('to typed vector', () { test('to typed vector', () {
expect(ValueTypeUtils.toTypedVector(ValueType.Int,0), equals(ValueType.VectorInt)); expect(ValueTypeUtils.toTypedVector(ValueType.Int, 0),
expect(ValueTypeUtils.toTypedVector(ValueType.UInt,0), equals(ValueType.VectorUInt)); equals(ValueType.VectorInt));
expect(ValueTypeUtils.toTypedVector(ValueType.Bool,0), equals(ValueType.VectorBool)); expect(ValueTypeUtils.toTypedVector(ValueType.UInt, 0),
expect(ValueTypeUtils.toTypedVector(ValueType.Float,0), equals(ValueType.VectorFloat)); equals(ValueType.VectorUInt));
expect(ValueTypeUtils.toTypedVector(ValueType.Key,0), equals(ValueType.VectorKey)); expect(ValueTypeUtils.toTypedVector(ValueType.Bool, 0),
expect(ValueTypeUtils.toTypedVector(ValueType.String,0), equals(ValueType.VectorString)); 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.Int, 2),
expect(ValueTypeUtils.toTypedVector(ValueType.UInt,2), equals(ValueType.VectorUInt2)); equals(ValueType.VectorInt2));
expect(ValueTypeUtils.toTypedVector(ValueType.Float,2), equals(ValueType.VectorFloat2)); 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.Int, 3),
expect(ValueTypeUtils.toTypedVector(ValueType.UInt,3), equals(ValueType.VectorUInt3)); equals(ValueType.VectorInt3));
expect(ValueTypeUtils.toTypedVector(ValueType.Float,3), equals(ValueType.VectorFloat3)); 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.Int, 4),
expect(ValueTypeUtils.toTypedVector(ValueType.UInt,4), equals(ValueType.VectorUInt4)); equals(ValueType.VectorInt4));
expect(ValueTypeUtils.toTypedVector(ValueType.Float,4), equals(ValueType.VectorFloat4)); expect(ValueTypeUtils.toTypedVector(ValueType.UInt, 4),
equals(ValueType.VectorUInt4));
expect(ValueTypeUtils.toTypedVector(ValueType.Float, 4),
equals(ValueType.VectorFloat4));
}); });
test('typed vector element type', () { test('typed vector element type', () {
expect(ValueTypeUtils.typedVectorElementType(ValueType.VectorInt), equals(ValueType.Int)); expect(ValueTypeUtils.typedVectorElementType(ValueType.VectorInt),
expect(ValueTypeUtils.typedVectorElementType(ValueType.VectorUInt), equals(ValueType.UInt)); equals(ValueType.Int));
expect(ValueTypeUtils.typedVectorElementType(ValueType.VectorFloat), equals(ValueType.Float)); expect(ValueTypeUtils.typedVectorElementType(ValueType.VectorUInt),
expect(ValueTypeUtils.typedVectorElementType(ValueType.VectorString), equals(ValueType.String)); equals(ValueType.UInt));
expect(ValueTypeUtils.typedVectorElementType(ValueType.VectorKey), equals(ValueType.Key)); expect(ValueTypeUtils.typedVectorElementType(ValueType.VectorFloat),
expect(ValueTypeUtils.typedVectorElementType(ValueType.VectorBool), equals(ValueType.Bool)); 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', () { test('fixed typed vector element type', () {
expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorInt2), equals(ValueType.Int)); expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorInt2),
expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorInt3), equals(ValueType.Int)); equals(ValueType.Int));
expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorInt4), 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.VectorUInt2),
expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorUInt3), equals(ValueType.UInt)); equals(ValueType.UInt));
expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorUInt4), 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.VectorFloat2),
expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorFloat3), equals(ValueType.Float)); equals(ValueType.Float));
expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorFloat4), 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', () { test('fixed typed vector element size', () {
expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorInt2), equals(2)); expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorInt2),
expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorInt3), equals(3)); equals(2));
expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorInt4), equals(4)); 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.VectorUInt2),
expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorUInt3), equals(3)); equals(2));
expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorUInt4), equals(4)); 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.VectorFloat2),
expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorFloat3), equals(3)); equals(2));
expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorFloat4), equals(4)); expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorFloat3),
equals(3));
expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorFloat4),
equals(4));
}); });
test('packed type', () { test('packed type', () {
expect(ValueTypeUtils.packedType(ValueType.Null, BitWidth.width8), equals(0)); expect(
expect(ValueTypeUtils.packedType(ValueType.Null, BitWidth.width16), equals(1)); ValueTypeUtils.packedType(ValueType.Null, BitWidth.width8), equals(0));
expect(ValueTypeUtils.packedType(ValueType.Null, BitWidth.width32), equals(2)); expect(
expect(ValueTypeUtils.packedType(ValueType.Null, BitWidth.width64), equals(3)); 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(
expect(ValueTypeUtils.packedType(ValueType.Int, BitWidth.width16), equals(5)); ValueTypeUtils.packedType(ValueType.Int, BitWidth.width8), equals(4));
expect(ValueTypeUtils.packedType(ValueType.Int, BitWidth.width32), equals(6)); expect(
expect(ValueTypeUtils.packedType(ValueType.Int, BitWidth.width64), equals(7)); 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', () { test('bit width', () {
expect(BitWidthUtil.width(0), BitWidth.width8); expect(BitWidthUtil.width(0), BitWidth.width8);

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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