Expand description
§enough-ffi
FFI helpers for exposing cancellation across language boundaries.
This crate provides C-compatible functions and types for use with C#/.NET, Python, Node.js, and other languages that can call C APIs.
§Safety Model
This crate uses reference counting internally to prevent use-after-free:
- Sources and tokens use
Arcinternally - Destroying a source while tokens exist is safe - tokens remain valid but can never become cancelled (since no one can call cancel anymore)
- Each token must be explicitly destroyed when no longer needed
§C# Integration Example
// P/Invoke declarations
[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 bool enough_token_is_cancelled(IntPtr token);
[DllImport("mylib")]
static extern void enough_token_destroy(IntPtr token);
// Usage with CancellationToken
public static byte[] Decode(byte[] data, CancellationToken ct)
{
var source = enough_cancellation_create();
var token = enough_token_create(source);
try
{
using var registration = ct.Register(() =>
enough_cancellation_cancel(source));
return NativeMethods.decode(data, token);
}
finally
{
enough_token_destroy(token);
enough_cancellation_destroy(source);
}
}§Rust FFI Functions
use enough_ffi::{enough_token_create, enough_token_destroy, FfiCancellationToken};
use enough::Stop;
#[no_mangle]
pub extern "C" fn decode(
data: *const u8,
len: usize,
token: *const FfiCancellationToken,
) -> i32 {
let stop = unsafe { FfiCancellationToken::from_ptr(token) };
// Use stop with any library that accepts impl Stop
if stop.should_stop() {
return -1; // Cancelled
}
0
}Structs§
- FfiCancellation
Source - FFI-safe cancellation source.
- FfiCancellation
Token - FFI-safe cancellation token.
- FfiCancellation
Token View - A non-owning view of a cancellation token.
Functions§
- enough_
cancellation_ ⚠cancel - Cancel a cancellation source.
- enough_
cancellation_ create - Create a new cancellation source.
- enough_
cancellation_ ⚠destroy - Destroy a cancellation source.
- enough_
cancellation_ ⚠is_ cancelled - Check if a cancellation source is cancelled.
- enough_
token_ ⚠create - Create a token from a cancellation source.
- enough_
token_ create_ never - Create a “never cancelled” token.
- enough_
token_ ⚠destroy - Destroy a token.
- enough_
token_ ⚠is_ cancelled - Check if a token is cancelled.