adaptor.dart 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import 'dart:convert';
  2. import 'dart:ffi';
  3. // ignore: import_of_legacy_library_into_null_safe
  4. import 'package:isolates/isolates.dart';
  5. // ignore: import_of_legacy_library_into_null_safe
  6. import 'package:isolates/ports.dart';
  7. import 'package:ffi/ffi.dart';
  8. // ignore: unused_import
  9. import 'package:flutter/services.dart';
  10. import 'dart:async';
  11. import 'dart:typed_data';
  12. import 'package:flowy_sdk/ffi/ffi.dart' as ffi;
  13. enum FFIExceptionType {
  14. RequestPacketIsEmpty,
  15. InvalidResponseLength,
  16. ResponsePacketIsInvalid,
  17. }
  18. class FFIAdaptorException implements Exception {
  19. FFIExceptionType type;
  20. FFIAdaptorException(this.type);
  21. }
  22. class FFICommand {
  23. final String event;
  24. final Uint8List payload;
  25. FFICommand(this.event, this.payload);
  26. Map<String, dynamic> toJson() => {
  27. 'event': event,
  28. 'payload': payload,
  29. };
  30. }
  31. class FFIAdaptor {
  32. static Completer<Uint8List> asyncRequest() {
  33. // final command = FFICommand(
  34. // "AuthCheck", Uint8List.fromList(utf8.encode("this is payload")));
  35. final command = FFICommand("AuthCheck", Uint8List(0));
  36. Uint8List bytes = Uint8List.fromList(utf8.encode(jsonEncode(command)));
  37. assert(bytes.isEmpty == false);
  38. if (bytes.isEmpty) {
  39. throw FFIAdaptorException(FFIExceptionType.RequestPacketIsEmpty);
  40. }
  41. final Pointer<Uint8> input = calloc.allocate<Uint8>(bytes.length);
  42. final list = input.asTypedList(bytes.length);
  43. list.setAll(0, bytes);
  44. final completer = Completer<Uint8List>();
  45. final port = singleCompletePort(completer);
  46. ffi.async_command(port.nativePort, input, bytes.length);
  47. calloc.free(input);
  48. return completer;
  49. }
  50. }