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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
//! polyplug guest library — Rust bindings for guest-side (plugin developer) use.
//!
//! This crate provides the ABI types, allocator hookup, and registration
//! helpers that plugin authors need to implement a polyplug contract.
//!
//! # Quick Start
//!
//! With `polyplugc`-generated glue, a plugin author writes a trait impl plus
//! one exported factory per plugin. The generated `create_instance` calls the
//! factory for every instance the host creates and carries the returned
//! implementation (plus the [`HostContext`]) in `GuestContractInstance.data`:
//!
//! ```rust,ignore
//! // In Cargo.toml: crate-type = ["cdylib"]
//! use polyplug_guest::HostContext;
//!
//! #[path = "../generated/guest/mod.rs"]
//! mod generated;
//! use generated::contracts::MyContractGuestContract;
//!
//! struct Plugin {
//! /// Host handle for this runtime — use it for alloc_string / log / peers.
//! host: HostContext,
//! }
//!
//! impl MyContractGuestContract for Plugin {
//! fn my_fn(&self, input: u32) -> Result<u32, polyplug_guest::GuestError> {
//! self.host.log(polyplug_abi::types::LogLevel::Info, "guest.my_plugin", "called");
//! Ok(input + 1)
//! }
//! }
//!
//! /// Factory the generated `create_instance` glue calls for every instance.
//! /// The symbol name is fixed: `polyplug_create_<plugin_name>`.
//! #[unsafe(no_mangle)]
//! pub fn polyplug_create_my_plugin(host: HostContext) -> Box<dyn MyContractGuestContract> {
//! Box::new(Plugin { host })
//! }
//!
//! /// ABI version sentinel — exported by the plugin crate itself.
//! #[unsafe(no_mangle)]
//! pub extern "C" fn polyplug_abi_version() -> u32 { polyplug_abi::POLYPLUG_ABI_VERSION }
//! ```
//!
//! `polyplug_init` itself is generated (`generated/guest/init.rs`): it only
//! registers the static interface tables. No implementation or host pointer is
//! ever stored in process-wide state.
//!
//! # Status
//! Scaffold only. Full implementation is code-generated by `polyplugc`.
//!
//! # Host access — instance flow, no statics
//! This crate holds NO process-wide state. The host [`HostApi`] pointer flows
//! from `create_instance` (where the host passes it) into a [`HostContext`]
//! that the generated glue hands to the author factory and stores in the
//! per-instance payload carried by `GuestContractInstance.data`. Every host
//! call (allocation, logging, peer dispatch) is therefore routed to the exact
//! `Runtime` that owns the in-flight call — multiple runtimes sharing one
//! plugin dylib in the same process stay fully isolated.
use ;
/// Per-instance handle to the host runtime that created a plugin instance.
///
/// Captured by the generated `create_instance` glue from the `HostApi`
/// pointer the host passes in, handed to the author factory
/// (`polyplug_create_<plugin>`), and stored in the instance payload. All
/// guest→host operations (allocation, logging, peer-caller resolution) go
/// through a `HostContext` — there is no process-wide host storage.
// SAFETY: HostContext wraps a host interface pointer provided by the host runtime.
// The interface is immutable and valid for the plugin's lifetime. Multiple threads may read
// from the same interface concurrently — the host ensures thread-safe access to interface data.
unsafe
// SAFETY: The host interface is read-only memory owned by the runtime. Multiple threads may
// access the same interface concurrently without synchronization. The host runtime guarantees
// the interface remains valid and unchanged for the plugin's lifetime.
unsafe
// ─── Helper Functions ─────────────────────────────────────────────────────────
/// Create an AbiError panic response.
// ─── Helper Types ─────────────────────────────────────────────────────────────
/// Wrapper for a function pointer stored in a static vtable array.
///
/// Raw `*const ()` does not implement `Sync`, but function pointers in a
/// `static` array are effectively `'static` and immutable.
/// Wrap each function pointer in `FnPtr` when building your vtable's
/// `functions` array.
///
/// # Example
/// ```rust,ignore
/// // Out-param ABI: native dispatch fns return void and write their AbiError
/// // through the trailing out_err pointer.
/// extern "C" fn my_fn(
/// _instance: GuestContractInstance,
/// args: *const (),
/// out: *mut (),
/// out_err: *mut AbiError,
/// ) {
/// if !out_err.is_null() { unsafe { out_err.write(AbiError::ok()) }; }
/// }
/// static MY_FNS: [FnPtr; 1] = [FnPtr(my_fn as *const ())];
/// ```
);
// SAFETY: FnPtr wraps a 'static function pointer. Function pointers are safe
// to share across threads — the function itself handles its own synchronization.
unsafe
// SAFETY: Function pointers are inherently Sync — multiple threads may call
// the same function concurrently. The data is read-only 'static memory.
unsafe
/// Error returned from guest-side plugin trait methods.
///
/// Produced by generated ABI wrappers when an ABI call returns a non-zero code.
/// Plugin developers return `Result<T, GuestError>` from their trait implementations.
// ─── String Helpers ───────────────────────────────────────────────────────────
/// Convert a `StringView` to a `&str` borrowing for the view's lifetime.
///
/// A null or zero-length view decodes to `Ok("")`. A non-null view whose bytes
/// are NOT valid UTF-8 returns `Err(GuestError)` — the helper never silently
/// substitutes `""` for a readable-but-invalid view. (A panic is not an option:
/// these helpers run inside `extern "C"` guest dispatch, where unwinding across
/// the C ABI boundary is undefined behaviour, so the error is surfaced as a
/// `Result` instead.)
///
/// # Safety
/// - `sv.ptr` must either be null or point to `sv.len` initialized bytes that
/// stay valid and immutable for the entire lifetime `'a` of the borrow.
///
/// The returned `&'a str` is tied to the borrow of `sv`, so it cannot outlive
/// the `StringView` it was derived from. This is `unsafe` because the validity
/// and lifetime of `sv.ptr` cannot be checked here.
///
/// # Example
/// ```rust
/// use polyplug_abi::StringView;
/// use polyplug_guest::to_str;
///
/// let sv = StringView { ptr: b"hello".as_ptr(), len: 5 };
/// // SAFETY: `sv` borrows a live byte slice for the duration of this call.
/// let s: &str = unsafe { to_str(&sv) }.expect("valid UTF-8");
/// assert_eq!(s, "hello");
/// ```
pub unsafe
/// Check if a `StringView` starts with the given prefix.
///
/// # Safety
/// Same contract as [`to_str`]: `sv` must point to valid, live UTF-8 bytes for
/// the duration of the call.
///
/// # Example
/// ```rust
/// use polyplug_abi::StringView;
/// use polyplug_guest::starts_with;
///
/// let sv = StringView { ptr: b"hello world".as_ptr(), len: 11 };
/// // SAFETY: `sv` borrows a live byte slice for the duration of this call.
/// assert!(unsafe { starts_with(&sv, "hello") }.expect("valid UTF-8"));
/// assert!(!unsafe { starts_with(&sv, "world") }.expect("valid UTF-8"));
/// ```
///
/// Returns `Err(GuestError)` if the view's bytes are not valid UTF-8 (it decodes
/// via [`to_str`], which validates).
pub unsafe
/// Check if a `StringView` ends with the given suffix.
///
/// # Safety
/// Same contract as [`to_str`]: `sv` must point to valid, live UTF-8 bytes for
/// the duration of the call.
///
/// # Example
/// ```rust
/// use polyplug_abi::StringView;
/// use polyplug_guest::ends_with;
///
/// let sv = StringView { ptr: b"hello world".as_ptr(), len: 11 };
/// // SAFETY: `sv` borrows a live byte slice for the duration of this call.
/// assert!(unsafe { ends_with(&sv, "world") }.expect("valid UTF-8"));
/// assert!(!unsafe { ends_with(&sv, "hello") }.expect("valid UTF-8"));
/// ```
///
/// Returns `Err(GuestError)` if the view's bytes are not valid UTF-8 (it decodes
/// via [`to_str`], which validates).
pub unsafe
/// Strip a prefix from a `StringView` if present.
///
/// Returns the remaining string slice if the prefix was present,
/// otherwise returns the original string. The returned slice borrows for the
/// lifetime of `sv`. Returns `Err(GuestError)` if the view's bytes are not
/// valid UTF-8 (it decodes via [`to_str`], which validates).
///
/// # Safety
/// Same contract as [`to_str`]: `sv` must point to valid, live UTF-8 bytes for
/// the lifetime `'a` of the borrow.
///
/// # Example
/// ```rust
/// use polyplug_abi::StringView;
/// use polyplug_guest::strip_prefix;
///
/// let sv = StringView { ptr: b"hello world".as_ptr(), len: 11 };
/// // SAFETY: `sv` borrows a live byte slice for the duration of this call.
/// assert_eq!(unsafe { strip_prefix(&sv, "hello ") }.expect("valid UTF-8"), "world");
/// assert_eq!(unsafe { strip_prefix(&sv, "goodbye") }.expect("valid UTF-8"), "hello world");
/// ```
pub unsafe
/// Split a `StringView` by a literal delimiter, keeping empty segments.
///
/// Returns a vector of string slices borrowing for the lifetime of `sv`. A
/// null or empty view returns an empty vector; an empty delimiter returns the
/// whole string as a single element. Leading, trailing, and consecutive
/// delimiters produce empty strings in the output. Returns `Err(GuestError)`
/// if the view's bytes are not valid UTF-8 (it decodes via [`to_str`], which
/// validates).
///
/// # Safety
/// Same contract as [`to_str`]: `sv` must point to valid, live UTF-8 bytes for
/// the lifetime `'a` of the borrow.
///
/// # Example
/// ```rust
/// use polyplug_abi::StringView;
/// use polyplug_guest::split;
///
/// let sv = StringView { ptr: b"a,b,c".as_ptr(), len: 5 };
/// // SAFETY: `sv` borrows a live byte slice for the duration of this call.
/// let parts: Vec<&str> = unsafe { split(&sv, ",") }.expect("valid UTF-8");
/// assert_eq!(parts, vec!["a", "b", "c"]);
/// ```
pub unsafe