enough-ffi
FFI helpers for the enough cooperative cancellation trait.
This crate provides C-compatible functions and types for bridging cancellation across language boundaries. Use it to integrate Rust libraries with C#/.NET, Python, Node.js, and other languages that can call C APIs.
Safety Model
This crate uses Arc-based reference counting internally to prevent use-after-free:
- Sources and tokens share state through
Arc - Destroying a source while tokens exist is safe - tokens remain valid
- Tokens that outlive their source will never become cancelled (no one can call cancel)
- Each token must be explicitly destroyed when no longer needed
Quick Start
C FFI Functions
// Source management
void* ;
void ;
bool ;
void ;
// Token management
void* ;
void* ;
bool ;
void ;
Rust FFI Functions
When writing Rust FFI functions that receive a token pointer:
use FfiCancellationToken;
use Stop;
pub extern "C"
C# Integration
public class CancellationHandle : IDisposable
{
[DllImport("mylib")] static extern IntPtr enough_cancellation_create();
[DllImport("mylib")] static extern void enough_cancellation_cancel(IntPtr source);
[DllImport("mylib")] static extern void enough_cancellation_destroy(IntPtr source);
[DllImport("mylib")] static extern IntPtr enough_token_create(IntPtr source);
[DllImport("mylib")] static extern void enough_token_destroy(IntPtr token);
private IntPtr _source, _token;
private CancellationTokenRegistration _registration;
public CancellationHandle(CancellationToken ct)
{
_source = enough_cancellation_create();
_token = enough_token_create(_source);
_registration = ct.Register(() => enough_cancellation_cancel(_source));
}
public IntPtr TokenHandle => _token;
public void Dispose()
{
_registration.Dispose();
enough_token_destroy(_token);
enough_cancellation_destroy(_source);
}
}
Node.js Integration
import ffi from 'ffi-napi';
const lib = ffi.;
Types
| Type | Description |
|---|---|
FfiCancellationSource |
Owns cancellation state, can trigger cancellation |
FfiCancellationToken |
Holds reference to state, can check cancellation |
FfiCancellationTokenView |
Non-owning view for Rust FFI functions |
License
Licensed under either of Apache License, Version 2.0 or MIT license at your option.