stringLikeBcsType function

BcsType<String, dynamic> stringLikeBcsType({
  1. required String name,
  2. required Uint8List toBytes(
    1. String
    ),
  3. required String fromBytes(
    1. Uint8List
    ),
  4. int? serializedSize(
    1. dynamic, {
    2. BcsWriterOptions? options,
    })?,
  5. void validate(
    1. String
    )?,
})

Implementation

BcsType<String, dynamic> stringLikeBcsType({
  required String name,
  required Uint8List Function(String) toBytes,
  required String Function(Uint8List) fromBytes,
  int? Function(dynamic, {BcsWriterOptions? options})? serializedSize,
  void Function(String)? validate,
}) {
  return BcsType<String, dynamic>(
    name: name,
    read: (reader) {
      final length = reader.readULEB();
      final bytes = reader.readBytes(length);
      return fromBytes(bytes);
    },
    write: (value, writer) {
      final bytes = toBytes(value);
      writer.writeULEB(bytes.length);
      for (final byte in bytes) {
        writer.write8(byte);
      }
    },
    serialize: (value, {BcsWriterOptions? options}) {
      final bytes = toBytes(value);
      final size = ulebEncode(bytes.length);
      final result = Uint8List(size.length + bytes.length);
      result.setRange(0, size.length, size);
      result.setRange(size.length, result.length, bytes);
      return result;
    },
    serializedSize: serializedSize,
    validate: (value) {
      if (value is! String) {
        throw ArgumentError("Invalid $name value: $value. Expected string");
      }
      validate?.call(value);
    },
  );
}