isolateEntryPoint method

void isolateEntryPoint(
  1. SendPort sendPort
)

Implementation

void isolateEntryPoint(SendPort sendPort) async {
  void onSend(dynamic data) {
    try {
      // On the helper isolate listen to requests and respond to them.
      if (data is _EncodeRequest) {
        final Pointer<Char> result = _bindings.blurHashForPixels(
          data.componentX,
          data.componentY,
          data.width,
          data.height,
          data.pixelsPointer,
          data.rowStride,
        );
        final String resultString = result.cast<Utf8>().toDartString();
        final _EncodeResponse response =
            _EncodeResponse(data.id, resultString);
        sendPort.send(response);
        return;
      } else if (data is _DecodeRequest) {
        final Pointer<Uint8> result = _bindings.decode(data.blurHashPointer,
            data.width, data.height, data.punch, data.channels);
        final Uint8List resultImage = result.asTypedList(
          data.width * data.height * data.channels,
          // preffer way but works only from dart 3.1.0, and requre to change generated bindings
          // finalizer: _bindings.freePixelArrayPtr.cast(),
        );
        final _DecodeResponse response = _DecodeResponse(
          data.id,
          // copy image data to prevent 'use after free' error
          Uint8List.fromList(resultImage),
        );
        // free c side memory
        _bindings.freePixelArray(result);
        sendPort.send(response);
        return;
      } else if (data is _DecodeToArrayRequest) {
        final int result = _bindings.decodeToArray(
            data.blurHashPointer,
            data.width,
            data.height,
            data.punch,
            data.channels,
            data.pixelArray);
        data.free();
        final _DecodeToArrayResponse response =
            _DecodeToArrayResponse(data.id, result);
        sendPort.send(response);
        return;
      }
      throw BlurhashFFIException(
          'EXCEPTION: Unsupported message type: ${data.runtimeType}',
          null,
          null);
    } catch (e) {
      final stackTrace = StackTrace.current;
      throw BlurhashFFIException(
          'ERORR: ${Isolate.current.debugName}', stackTrace, e);
    }
  }

  final ReceivePort helperReceivePort = ReceivePort()..listen(onSend);

  // Send the port to the main isolate on which we can receive requests.
  sendPort.send(helperReceivePort.sendPort);
}