1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
//! Serialize complex objects into flat byte buffers and transfer them over FFI.
//!
//! Types like `String`, `Vec<T>`, `HashMap<K, V>`, and structs containing them cannot be
//! passed directly over an FFI boundary. Their in-memory form is a small header (pointer,
//! length, capacity) into a Rust-managed heap allocation — the foreign side cannot read,
//! resize, or free that memory. `Wire<T>` solves this by serializing the value into a flat
//! byte buffer on one side and deserializing it on the other.
//!
//! # Examples
//!
//! ### Accepting a complex argument
//!
//! ```
//! use interoptopus::ffi;
//! use interoptopus::wire::Wire;
//! use std::collections::HashMap;
//!
//! #[ffi]
//! pub fn lookup(mut map: Wire<HashMap<String, String>>) -> u32 {
//! let map = map.unwire();
//! map.len() as u32
//! }
//! ```
//!
//! ### Returning a complex value
//!
//! ```
//! use interoptopus::ffi;
//! use interoptopus::wire::Wire;
//!
//! #[ffi]
//! pub fn greeting() -> Wire<String> {
//! Wire::from("hello".to_string())
//! }
//! ```
//!
//! ### Structs containing non-FFI types
//!
//! Any `#[ffi]` struct whose fields are not all `repr(C)` can be wrapped in
//! `Wire<T>`. The proc macro generates matching serialization code on both
//! sides.
//!
//! ```
//! use interoptopus::ffi;
//! use interoptopus::wire::Wire;
//!
//! #[ffi]
//! pub struct UserProfile {
//! pub name: String,
//! pub tags: Vec<String>,
//! }
//!
//! #[ffi]
//! pub fn accept_profile(mut profile: Wire<UserProfile>) {
//! let profile = profile.unwire();
//! println!("{}: {:?}", profile.name, profile.tags);
//! }
//! ```
//!
//! ### Deeply nested types
//!
//! `Wire<T>` handles arbitrarily nested structures, including `Vec`, `HashMap`,
//! and `Option` at any depth:
//!
//! ```
//! use interoptopus::ffi;
//! use interoptopus::wire::Wire;
//! use std::collections::HashMap;
//!
//! #[ffi]
//! pub struct Inner { pub score: u32 }
//!
//! #[ffi]
//! pub struct Outer {
//! pub items: HashMap<u32, Vec<Inner>>,
//! }
//!
//! #[ffi]
//! pub fn process(mut data: Wire<Outer>) -> u32 {
//! let data = data.unwire();
//! data.items.values().flatten().map(|i| i.score).sum()
//! }
//! ```
//!
//! ### Registering the helpers
//!
//! Every crate that uses `Wire<T>` must call [`builtins_wire!`](crate::builtins_wire)
//! in its inventory so the create/destroy helpers are available to the foreign side:
//!
//! ```
//! use interoptopus::ffi;
//! use interoptopus::wire::Wire;
//! use interoptopus::{builtins_wire, function};
//! use interoptopus::inventory::RustInventory;
//!
//! #[ffi]
//! pub fn greeting() -> Wire<String> {
//! Wire::from("hello".to_string())
//! }
//!
//! pub fn ffi_inventory() -> RustInventory {
//! RustInventory::new()
//! .register(function!(greeting))
//! .register(builtins_wire!())
//! .validate()
//! }
//! ```
//!
//! # Wire vs. Protobuf
//!
//! The natural alternative to `Wire<T>` for passing complex 'variably-sized' types over FFI is
//! [Protocol Buffers](https://protobuf.dev/). Protobuf works, but it comes with significant
//! friction: you need to maintain `.proto` schema files alongside your Rust types, install and
//! run an external code generator as part of your build, integrate that generator into both the Rust
//! and the foreign-language project, and keep all three in sync whenever a type changes.
//! The result is a more complex project setup with more moving parts — and you still have to
//! wire the generated types into your FFI layer by hand.
//!
//! `Wire<T>` eliminates all of that. Types are defined once in Rust with `#[ffi]`, and both
//! the serialization logic and the foreign-language deserialization code are generated
//! automatically as part of the normal interoptopus build. There are no `.proto` files, no
//! external tools, and no schema drift.
//!
//! Beyond ergonomics, `Wire<T>` is in most cases also faster. Because both sides share the
//! exact same compiled type layout, there is no field-tag overhead, no varint encoding, and
//! no dynamic dispatch — just a straight sequential read/write of the exact bytes needed.
//! In our benchmarks, `Wire<T>` usually outperformed Protobuf by roughly 20–200%
//! depending on the payload shape.
//!
//! 
//!
//! Note, in the benchmarks above, Protobuf was given a slight advantage over `Wire<T>` by not having to
//! FFI allocate. This made Protobuf's performance look slightly better, but would make it unsuitable for
//! `async` use.
//!
//! # Under the Hood
//!
//! A [`Wire<T>`] is essentially a serialized buffer that is safe to pass through
//! FFI boundaries.
//!
//! ## Rust -> Foreign
//!
//! 1. **Serialize** — [`Wire::from`] (or [`Wire::try_from`]) serializes the value into a new Rust-allocated buffer.
//! 2. **Transfer** — the `Wire<T>` is returned from an `#[ffi]` function; as a `repr(C)` struct it crosses the FFI boundary by value.
//! 3. **Deserialize** — the foreign side (e.g., C#) reads the buffer bytes and reconstructs the managed type.
//! 4. **Free** — the foreign side calls `Dispose()` or similar on the wire object, which invokes `interoptopus_wire_destroy`
//! (emitted by `builtins_wire!`) to drop the Rust-allocated buffer.
//!
//! ## Foreign -> Rust
//!
//! 1. **Allocate** — the generated `WireOf*.From(value)` helper calls `interoptopus_wire_create` (emitted by
//! `builtins_wire!`) so that Rust allocates the buffer; the foreign side never allocates directly.
//! 2. **Serialize** — the value is serialized into that Rust-allocated buffer.
//! 3. **Transfer** — the `Wire<T>` is passed into an `#[ffi]` function. Rust receives ownership.
//! 4. **Deserialize** — [`Wire::unwire`] or [`Wire::try_unwire`] reads `T` from the buffer.
//! 5. **Free** — Rust drops the `Wire<T>` when the function returns, freeing the buffer.
//!
//!
//! ## Wire format
//!
//! All values are written in **little-endian** byte order, sequentially, with no padding
//! or alignment between fields:
//!
//! | Type | Format |
//! |---|---|
//! | `u8`..`u64`, `i8`..`i64`, `f32`, `f64` | Fixed-size little-endian bytes |
//! | `usize` / `isize` | Platform-width little-endian (8 bytes on 64-bit) |
//! | `bool` | 1 byte (`0x00` = false, non-zero = true) |
//! | `String` | `u32` byte-length (LE), then UTF-8 bytes |
//! | `Vec<T>` | `u32` element count (LE), then each element serialized in order |
//! | `HashMap<K,V>` | `u32` entry count (LE), then each key followed by value |
//! | `(A, B, …)` | Each element serialized in order |
//! | User structs | Each field serialized in declaration order |
//!
//! The wire format is not self-describing, both sides must agree on the exact type
//! layout.
//!
//! **Note:** This section describes an internal implementation detail that may change
//! between versions without notice. Do not rely on it for persistent storage or
//! cross-version compatibility.
use cratebad_wire;
use crate;
use crate;
use crate;
use WireBuffer;
use PhantomData;
/// Wraps and transfers complex objects over FFI.
///
/// The backing storage uses a (ptr, size) representation that can safely cross
/// FFI boundaries.
///
/// Body of `interoptopus_wire_destroy`. Shared by [`builtins_wire!`] and
/// [`register_wire_trampolines!`].
/// Emits and registers helpers for [`Wire<T>`](crate::wire::Wire).
///
/// Backends (e.g., C#) use these functions internally so that foreign code can
/// allocate and free Rust-owned wire buffers.
///
/// # Usage
///
/// Call once in your inventory function and register the result:
///
/// ```rust
/// # use interoptopus::inventory::RustInventory;
/// # use interoptopus::builtins_wire;
/// pub fn inventory() -> RustInventory {
/// RustInventory::new()
/// .register(builtins_wire!())
/// // ... other registrations ...
/// .validate()
/// }
/// ```
///
/// # Implementation Details
///
/// This macro generates the following FFI functions:
/// - `interoptopus_wire_create` — allocates a wire buffer of a given size.
/// - `interoptopus_wire_destroy` — drops a wire buffer, freeing its memory.
///
/// Body of `interoptopus_wire_create`. Shared by `builtins_wire!` and
/// `register_wire_trampolines!`.
/// Registers wire buffer trampolines with a foreign plugin.
///
/// Defines local `extern "C"` functions (no exported symbols) that share
/// the same body logic as [`builtins_wire!`], then passes their pointers
/// to the given register callback.
///
/// # Example
///
/// ```rust,ignore
/// interoptopus::register_wire_trampolines!(|id, ptr| {
/// (plugin.register_trampoline)(id, ptr);
/// });
/// ```