Denio Mariz
Denio Mariz

Reputation: 1195

Dart Hive TypeAdapter rational for write() method

I am trying to understand the rational behind using writeByte(3) in the write method in Hive TypeAdapter.

Please consider the class:

@HiveType()
class Person{
  @HiveField(0)
  String name;

  @HiveField(1)
  int age;
}

In the TypeAdapter below It is easy to understand the read method, since it is just reads sequentially each field.

However, I'm trying to figure out why the same mechanism does not apply to the write, instead of using ..writeByte(...) just before each field. And, what is the meaning of the first ..writeByte(2)?

class PersonAdapter extends TypeAdapter<Person> {
  @override
  Person read(BinaryReader reader) {
    var numOfFields = reader.readByte();
    var fields = <int, dynamic>{
      for (var i = 0; i < numOfFields; i++) reader.readByte(): reader.read(),
    };
    return Trips()
      ..name = fields[0] as String
      ..age = fields[1] as int;
  }

  @override
  void write(BinaryWriter writer, Person obj) {
    writer
      ..writeByte(2)           // Why this here? (sometimes I see writeByte(3) !! )
      ..writeByte(0)
      ..write(obj.name)
      ..writeByte(1)
      ..write(obj.age);
  }
}

Thanks for any clarification.

Upvotes: 0

Views: 329

Answers (2)

Sıdıka &#214;ZCAN
Sıdıka &#214;ZCAN

Reputation: 1

writeByte(2) tells you how many data to print, for example if you have three data writeByte(3).

Upvotes: 0

julemand101
julemand101

Reputation: 31219

I know nothing about Hive but if you take a look at the builder which create this write method you can see the following:

  String buildWrite() {
    var code = StringBuffer();
    code.writeln('writer');
    code.writeln('..writeByte(${getters.length})');
    for (var field in getters) {
      var value = _convertIterable(field.type, 'obj.${field.name}');
      code.writeln('''
      ..writeByte(${field.index})
      ..write($value)''');
    }
    code.writeln(';');

    return code.toString();
  }

https://github.com/hivedb/hive/blob/59ad5403593283233d922f62f76832c64fa33a3b/hive_generator/lib/src/class_builder.dart#L122

So based on this we can conclude the first writeByte is the length of getters. The next one is the index of the first getter (0) following by the value and next getter (1) with value and so on.

This makes sense since the protocol properly needs to know how many fields it can expect to get.

Upvotes: 1

Related Questions