adaptor.dart 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import 'dart:ffi';
  2. // ignore: import_of_legacy_library_into_null_safe
  3. import 'package:isolates/isolates.dart';
  4. // ignore: import_of_legacy_library_into_null_safe
  5. import 'package:isolates/ports.dart';
  6. import 'package:ffi/ffi.dart';
  7. import 'package:flowy_protobuf/model/grpc.pb.dart';
  8. import 'package:flutter/services.dart';
  9. import 'dart:async';
  10. import 'dart:typed_data';
  11. import 'package:flowy_sdk/ffi/ffi.dart' as ffi;
  12. enum FFIExceptionType {
  13. RequestPacketIsEmpty,
  14. InvalidResponseLength,
  15. ResponsePacketIsInvalid,
  16. }
  17. class FFIAdaptorException implements Exception {
  18. FFIExceptionType type;
  19. FFIAdaptorException(this.type);
  20. }
  21. class FFIAdaptor {
  22. static Completer<Uint8List> asyncRequest(RequestPacket request) {
  23. Uint8List bytes = request.writeToBuffer();
  24. assert(bytes.isEmpty == false);
  25. if (bytes.isEmpty) {
  26. throw FFIAdaptorException(FFIExceptionType.RequestPacketIsEmpty);
  27. }
  28. final Pointer<Uint8> input = calloc.allocate<Uint8>(bytes.length);
  29. final list = input.asTypedList(bytes.length);
  30. list.setAll(0, bytes);
  31. final completer = Completer<Uint8List>();
  32. final port = singleCompletePort(completer);
  33. ffi.async_command(port.nativePort, input, bytes.length);
  34. calloc.free(input);
  35. return completer;
  36. }
  37. }