# Custom Types

Sometimes you need to expose types from external crates that you don't own. You can't add `#[data]` to a type defined in another crate, but you can teach BoltFFI how to convert it to and from an FFI-compatible representation. This lets you use types from crates like `chrono` or `rust_decimal` in your exported API, under a name you declare.

The conversion happens automatically at the FFI boundary. Your Rust code uses the original type, consumers see either a primitive or a record, and BoltFFI handles the conversion in both directions.

## The custom\_type! Macro

The `custom_type!` macro defines a conversion between an external type and an FFI-compatible representation. BoltFFI uses this mapping whenever the type appears in function signatures, struct fields, or return values.

```rust
use boltffi::custom_type;
use chrono::{DateTime, Utc};

custom_type! {
    pub UtcDateTime,
    remote = DateTime<Utc>,
    repr = i64,
    into_ffi = |value: &DateTime<Utc>| value.timestamp_millis(),
    try_from_ffi = |millis: i64| {
        DateTime::from_timestamp_millis(millis).ok_or(boltffi::CustomTypeConversionError)
    },
}
```

The macro takes these parameters:

- **name** - The name the generated bindings use for the type. The macro defines it as an alias of the remote type (`pub type UtcDateTime = DateTime<Utc>;`), so values are still the remote type. It must be unique within your crate and cannot be a builtin name such as `Duration`.
- **remote** - The external type you're wrapping. This is what your Rust code uses.
- **repr** - The FFI-compatible representation. Must be a type BoltFFI already knows how to transfer: primitives, `String`, `Vec<T>`, or types marked with `#[data]`.
- **into\_ffi** - A closure that converts from the remote type to the repr. Takes a reference to the remote type.
- **try\_from\_ffi** - A closure that converts from the repr back to the remote type. Returns `Result<Remote, Error>`.
- **error** - (optional) The error type returned by `try_from_ffi`. Defaults to `CustomTypeConversionError`.

Signatures can name the type by its declared name or by the remote type:

```rust
#[export]
pub struct EventLog {
    events: Mutex<Vec<UtcDateTime>>,
}

#[export]
impl EventLog {
    pub fn last_seen(&self) -> Option<UtcDateTime> {
        self.events.lock().unwrap().last().copied()
    }

    pub fn record(&self, at: DateTime<Utc>) {
        self.events.lock().unwrap().push(at);
    }
}
```

Consumers see the representation (`i64` here) in the generated bindings. The conversion is transparent.

The remote type, or a `type` alias of either name, works once `boltffi generate`, `boltffi build` or `boltffi pack` has run for the crate. Before that, a plain `cargo build` accepts only the declared name.

## The CustomFfiConvertible Trait

For types you define yourself, you can implement the `CustomFfiConvertible` trait directly and mark the impl with `#[custom_ffi]`. This gives you access to the full type system and works for types that need complex conversion logic.

```rust
use boltffi::{custom_ffi, CustomFfiConvertible};

pub struct UserId(i64);

#[custom_ffi]
impl CustomFfiConvertible for UserId {
    type FfiRepr = i64;
    type Error = boltffi::CustomTypeConversionError;
    
    fn into_ffi(&self) -> Self::FfiRepr {
        self.0
    }
    
    fn try_from_ffi(repr: Self::FfiRepr) -> Result<Self, Self::Error> {
        if repr > 0 {
            Ok(UserId(repr))
        } else {
            Err(boltffi::CustomTypeConversionError)
        }
    }
}
```

The `#[custom_ffi]` attribute generates the wire encoding implementations automatically. The trait requires:

- **FfiRepr** - The FFI-compatible representation type.
- **Error** - The error type for failed conversions.
- **into\_ffi** - Converts from the custom type to the repr.
- **try\_from\_ffi** - Converts from the repr to the custom type.

Note: Due to Rust's orphan rule, you cannot implement `CustomFfiConvertible` for types from external crates. Use the `custom_type!` macro for those.

## Choosing an Approach

Use `custom_type!` when:

- The type is from an external crate (chrono, rust\_decimal, geo, etc.)
- The conversion is straightforward (parse/format, extract field)

Use `#[custom_ffi]` when:

- The type is defined in your crate
- You want the type to implement `WireEncode`/`WireDecode` directly
- You need validation logic in `try_from_ffi`

## Representation Types

The representation type must be something BoltFFI can transfer across the FFI boundary:

| Remote Type             | Good Repr                        | Why                   |
| ----------------------- | -------------------------------- | --------------------- |
| `chrono::DateTime<Utc>` | `i64`                            | Unix timestamp millis |
| `std::net::IpAddr`      | `String`                         | Standard text form    |
| `rust_decimal::Decimal` | `String`                         | Avoid floating point  |
| `geo::Point`            | `GeoPoint` (your `#[data]` type) | Structured data       |

For structured data, define a record type:

```rust
#[data]
#[derive(Clone, Copy)]
pub struct GeoPoint {
    pub lat: f64,
    pub lng: f64,
}

custom_type! {
    pub GeoPointWrapper,
    remote = geo::Point,
    repr = GeoPoint,
    into_ffi = |point| GeoPoint { lat: point.y(), lng: point.x() },
    try_from_ffi = |gp| Ok(geo::Point::new(gp.lng, gp.lat)),
}
```

## Containers

Custom types work inside containers. With `UtcDateTime` declared, you can use `Vec<UtcDateTime>`, `Option<UtcDateTime>`, and `Result<UtcDateTime, E>` in your API. BoltFFI applies the conversion to each element automatically.

```rust
#[export]
impl EventLog {
    pub fn between(&self, from: UtcDateTime, to: UtcDateTime) -> Vec<UtcDateTime> {
        self.events
            .lock()
            .unwrap()
            .iter()
            .filter(|at| (from..to).contains(at))
            .copied()
            .collect()
    }
}
```

The generated bindings show a list of `i64` for the result. Each value is converted from a `DateTime<Utc>` after your code returns.

## Conversion Errors

When `try_from_ffi` returns an error, BoltFFI panics with a message identifying the custom type. This is intentional: invalid data crossing the FFI boundary indicates a bug in the consumer's code. If you need to handle invalid input gracefully, validate at the API level:

```rust
#[export]
pub struct UserService {
    users: HashMap<uuid::Uuid, User>,
}

#[export]
impl UserService {
    pub fn get_user(&self, id: String) -> Result<Option<User>, ValidationError> {
        let uuid = uuid::Uuid::parse_str(&id)
            .map_err(|_| ValidationError::InvalidUuid)?;
        Ok(self.users.get(&uuid).cloned())
    }
}
```

## C representations

The C target supports custom types in synchronous functions, records, enums, and collections. It generates a package-prefixed alias for the declared representation. A string-backed `Email` in a package named `demo` uses `DemoEmailView` for input and `DemoEmail` for output. Returned values are released with `demo_email_free`.

```c
DemoEmailView input = {"ali@example.com", 15};
DemoEmail email = demo_echo_email(input);
fwrite(email.ptr, 1, email.len, stdout);
demo_email_free(&email);
```

This example uses the [demo library's Email type](https://github.com/boltffi/boltffi/tree/main/examples/demo/src/custom_types). A scalar-backed custom type is an alias for that scalar and needs no cleanup. See [memory management](/docs/c.md#memory-management) for borrowed views and returned owners.
