Crate enough_ffi

Crate enough_ffi 

Source
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 Arc internally
  • 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§

FfiCancellationSource
FFI-safe cancellation source.
FfiCancellationToken
FFI-safe cancellation token.
FfiCancellationTokenView
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.