Skip to main content

js2rust_bridge/
sdk.rs

1//! Safe SDK for writing host functions.
2//!
3//! These types encapsulate C ABI pointer conversion and Zig Arena memory allocation,
4//! so host function implementations can be safe Rust with zero raw pointer manipulation.
5//!
6//! ## Quick reference
7//!
8//! | Type           | Direction  | C ABI signature               | Safe Rust type    |
9//! |----------------|------------|-------------------------------|-------------------|
10//! | [`HostStr`]    | Zig → Rust | `ptr: *const u8, len: usize`  | `&str`            |
11//! | [`JsStr`]      | Rust → Zig | `-> JsStr` (ptr+len repr C)   | `String` / `&str` |
12//! | [`JsStrField`] | Rust → Zig | struct field (ptr+len pair)   | `String` / `&str` |
13//!
14//! ## Example: sync string function
15//!
16//! ```rust,ignore
17//! use js2rust_bridge::sdk::{HostStr, JsStr};
18//!
19//! #[unsafe(no_mangle)]
20//! pub unsafe extern "C" fn host_concat(
21//!     s1_ptr: *const u8, s1_len: usize,
22//!     s2_ptr: *const u8, s2_len: usize,
23//! ) -> JsStr {
24//!     let s1 = HostStr::from_raw(s1_ptr, s1_len);
25//!     let s2 = HostStr::from_raw(s2_ptr, s2_len);
26//!     JsStr::new(&format!("{}{}", &s1, &s2))
27//! }
28//! ```
29//!
30//! ## Example: async struct return with string field
31//!
32//! ```rust,ignore
33//! use js2rust_bridge::sdk::{HostStr, JsStrField};
34//!
35//! #[repr(C)]
36//! pub struct MyResult {
37//!     pub id: i64,
38//!     pub name: JsStrField,
39//! }
40//!
41//! #[unsafe(no_mangle)]
42//! pub unsafe extern "C" fn fetch_user(
43//!     name_ptr: *const u8, name_len: usize,
44//! ) -> MyResult {
45//!     let name = HostStr::from_raw(name_ptr, name_len);
46//!     let user = runtime().block_on(lookup_user(&name));
47//!     MyResult {
48//!         id: user.id,
49//!         name: JsStrField::new(&user.name),
50//!     }
51//! }
52//! ```
53
54use std::ops::Deref;
55
56// ── String parameter from Zig Arena ────────────────────────────────
57
58/// A string parameter received from Zig via C ABI (ptr+len pair).
59///
60/// Construct with [`HostStr::from_raw(ptr, len)`](Self::from_raw) inside your
61/// `extern "C"` function.  Once constructed, use `&self` directly — it
62/// implements [`Deref<Target = str>`](Deref).
63///
64/// The underlying memory is owned by Zig's Arena — do not store the
65/// reference beyond the function call.
66pub struct HostStr<'a>(&'a str);
67
68impl<'a> HostStr<'a> {
69    /// Create a `HostStr` from a C ABI ptr+len pair.
70    ///
71    /// # Safety
72    ///
73    /// `ptr` must be non-null for `len > 0` and point to valid UTF-8
74    /// residing in Zig's Arena.  This is always true when called from a
75    /// correctly generated C ABI wrapper.
76    #[inline]
77    pub unsafe fn from_raw(ptr: *const u8, len: usize) -> Self {
78        if len == 0 || ptr.is_null() {
79            return Self("");
80        }
81        // SAFETY: caller guarantees ptr points to valid UTF-8 in Zig Arena.
82        let slice = unsafe { std::slice::from_raw_parts(ptr, len) };
83        let s = std::str::from_utf8(slice).unwrap_or("");
84        Self(s)
85    }
86}
87
88impl<'a> Deref for HostStr<'a> {
89    type Target = str;
90    #[inline]
91    fn deref(&self) -> &str {
92        self.0
93    }
94}
95
96impl<'a> AsRef<str> for HostStr<'a> {
97    #[inline]
98    fn as_ref(&self) -> &str {
99        self.0
100    }
101}
102
103impl<'a> std::fmt::Display for HostStr<'a> {
104    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
105        self.0.fmt(f)
106    }
107}
108
109impl std::fmt::Debug for HostStr<'_> {
110    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
111        self.0.fmt(f)
112    }
113}
114
115// ── String return — allocated in Zig Arena ─────────────────────────
116
117/// Allocate a string in Zig Arena via `js_allocator_dupe`.
118///
119/// Internal helper shared by `JsStr::new()` and `JsStrField::new()`.
120/// Returns a null pointer on OOM (the Zig side returns null on allocation failure).
121///
122/// # Safety
123///
124/// The returned pointer must be used in accordance with Zig Arena lifetime rules.
125unsafe fn dupe_to_arena(s: &str) -> *mut u8 {
126    // Declared here to keep the extern block local (isolated from user code).
127    // NOTE: return type is *mut u8 (not Option<*mut u8>) because Rust does NOT
128    // guarantee null-pointer optimization for Option<*mut u8> — it would be
129    // 16 bytes instead of 8, causing an ABI mismatch with Zig's ?[*]u8.
130    unsafe extern "C" {
131        fn js_allocator_dupe(src: *const u8, len: usize) -> *mut u8;
132    }
133    let ptr = unsafe { js_allocator_dupe(s.as_ptr(), s.len()) };
134    assert!(
135        !ptr.is_null(),
136        "js_allocator_dupe returned null: Zig arena OOM"
137    );
138    ptr
139}
140
141/// Return type for sync host functions that return a string.
142///
143/// Memory is allocated in Zig's Arena via `js_allocator_dupe` (single call:
144/// allocate + copy).  The Zig side receives ptr+len with zero-copy slicing.
145///
146/// Must be `#[repr(C)]` to match Zig's `extern struct { ptr, len }`.
147#[repr(C)]
148pub struct JsStr {
149    /// Pointer to the string data in Zig Arena.
150    pub ptr: *const u8,
151    /// String length (non-negative for success, negative = error message;
152    /// `isize` matches Zig's `extern struct` ABI for StrRet where the sign
153    /// bit distinguishes data from error).
154    pub len: isize,
155}
156
157impl JsStr {
158    /// Allocate a string in Zig Arena and return a `JsStr`.
159    ///
160    /// Uses `js_allocator_dupe` (single C ABI call: allocate + copy).
161    /// The memory lives in Zig's Arena and is freed when the allocator is deinitialized.
162    /// Panics on OOM (the Zig side returns null on allocation failure).
163    #[inline]
164    pub fn new(s: &str) -> Self {
165        if s.is_empty() {
166            return Self::empty();
167        }
168        let ptr = unsafe { dupe_to_arena(s) };
169        Self {
170            ptr,
171            len: s.len() as isize,
172        }
173    }
174
175    /// An empty string (null pointer, zero length).
176    #[inline]
177    pub fn empty() -> Self {
178        Self {
179            ptr: std::ptr::null(),
180            len: 0,
181        }
182    }
183
184    /// Returns true if this is an empty string.
185    #[inline]
186    pub fn is_empty(&self) -> bool {
187        self.len == 0
188    }
189}
190
191// ── Async struct string field ──────────────────────────────────────
192
193/// A string field inside an async host function's C ABI return struct.
194///
195/// Must be `#[repr(C)]` — its layout is `{ ptr: *const u8, len: usize }`,
196/// matching Zig's generated extern struct.
197///
198/// ## Example
199///
200/// ```rust,ignore
201/// #[repr(C)]
202/// pub struct FetchUserResult {
203///     pub id: i64,
204///     pub name: JsStrField,
205/// }
206///
207/// #[unsafe(no_mangle)]
208/// pub unsafe extern "C" fn fetch_user(
209///     name_ptr: *const u8, name_len: usize,
210/// ) -> FetchUserResult {
211///     let name = HostStr::from_raw(name_ptr, name_len);
212///     // ... async lookup ...
213///     FetchUserResult {
214///         id: user.id,
215///         name: JsStrField::new(&user.name),
216///     }
217/// }
218/// ```
219#[repr(C)]
220#[derive(Copy, Clone, Debug)]
221pub struct JsStrField {
222    /// Pointer to the string data in Zig Arena.
223    pub ptr: *const u8,
224    /// String length in bytes (`usize` — struct fields never carry error state,
225    /// unlike `JsStr.len` which uses `isize` for the sign-bit error convention).
226    pub len: usize,
227}
228
229impl JsStrField {
230    /// Allocate a string in Zig Arena and return a `JsStrField`.
231    ///
232    /// Uses `js_allocator_dupe` (single C ABI call: allocate + copy).
233    /// Panics on OOM (the Zig side returns null on allocation failure).
234    #[inline]
235    pub fn new(s: &str) -> Self {
236        if s.is_empty() {
237            return Self::empty();
238        }
239        let ptr = unsafe { dupe_to_arena(s) };
240        Self { ptr, len: s.len() }
241    }
242
243    /// An empty string field (null pointer, zero length).
244    #[inline]
245    pub fn empty() -> Self {
246        Self {
247            ptr: std::ptr::null(),
248            len: 0,
249        }
250    }
251
252    /// Returns true if this is an empty string.
253    #[inline]
254    pub fn is_empty(&self) -> bool {
255        self.len == 0
256    }
257}
258
259// ── Test stubs for C ABI functions ─────────────────────────────
260// When compiled as a static lib (e.g. for `cargo test`), the Zig runtime
261// is not available, so we provide stubs for `js_allocator_dupe` and
262// `js_allocator_alloc`. These stubs leak memory (like the old Box::leak),
263// but tests don't run long enough for this to matter.
264// Returns null on OOM to match the Zig-side C ABI contract.
265
266#[cfg(any(test, feature = "stub-allocator"))]
267#[unsafe(no_mangle)]
268#[allow(clippy::not_unsafe_ptr_arg_deref)]
269pub extern "C" fn js_allocator_dupe(src: *const u8, len: usize) -> *mut u8 {
270    let layout = std::alloc::Layout::from_size_align(len, 1)
271        .expect("Layout::from_size_align(len, 1) is infallible: align=1 is power-of-two and divides any size");
272    let ptr = unsafe { std::alloc::alloc(layout) };
273    if ptr.is_null() {
274        return std::ptr::null_mut();
275    }
276    if len > 0 {
277        unsafe {
278            std::ptr::copy_nonoverlapping(src, ptr, len);
279        }
280    }
281    ptr
282}
283
284#[cfg(any(test, feature = "stub-allocator"))]
285#[unsafe(no_mangle)]
286#[allow(clippy::not_unsafe_ptr_arg_deref)]
287pub extern "C" fn js_allocator_alloc(size: usize) -> *mut u8 {
288    if size == 0 {
289        return std::ptr::null_mut();
290    }
291    let layout = std::alloc::Layout::from_size_align(size, 1)
292        .expect("Layout::from_size_align(size, 1) is infallible: align=1 is power-of-two and divides any size");
293    let ptr = unsafe { std::alloc::alloc(layout) };
294    if ptr.is_null() {
295        std::ptr::null_mut()
296    } else {
297        ptr
298    }
299}