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/// Return type for sync host functions that return a string.
118///
119/// Memory is allocated in Zig's Arena via `js_allocator_dupe` (single call:
120/// allocate + copy).  The Zig side receives ptr+len with zero-copy slicing.
121///
122/// Must be `#[repr(C)]` to match Zig's `extern struct { ptr, len }`.
123#[repr(C)]
124pub struct JsStr {
125    /// Pointer to the string data in Zig Arena.
126    pub ptr: *const u8,
127    /// String length (non-negative for success).
128    pub len: isize,
129}
130
131impl JsStr {
132    /// Allocate a string in Zig Arena and return a `JsStr`.
133    ///
134    /// Uses `js_allocator_dupe` (single C ABI call: allocate + copy).
135    /// The memory lives in Zig's Arena and is freed when the allocator is deinitialized.
136    /// Panics on OOM (the Zig side returns null on allocation failure).
137    #[inline]
138    pub fn new(s: &str) -> Self {
139        if s.is_empty() {
140            return Self::empty();
141        }
142        // Declared here to keep the extern block local (isolated from user code).
143        // NOTE: return type is *mut u8 (not Option<*mut u8>) because Rust does NOT
144        // guarantee null-pointer optimization for Option<*mut u8> — it would be
145        // 16 bytes instead of 8, causing an ABI mismatch with Zig's ?[*]u8.
146        unsafe extern "C" {
147            fn js_allocator_dupe(src: *const u8, len: usize) -> *mut u8;
148        }
149        let ptr = unsafe { js_allocator_dupe(s.as_ptr(), s.len()) };
150        assert!(
151            !ptr.is_null(),
152            "js_allocator_dupe returned null: Zig arena OOM"
153        );
154        Self {
155            ptr,
156            len: s.len() as isize,
157        }
158    }
159
160    /// An empty string (null pointer, zero length).
161    #[inline]
162    pub fn empty() -> Self {
163        Self {
164            ptr: std::ptr::null(),
165            len: 0,
166        }
167    }
168
169    /// Returns true if this is an empty string.
170    #[inline]
171    pub fn is_empty(&self) -> bool {
172        self.len == 0
173    }
174}
175
176// ── Async struct string field ──────────────────────────────────────
177
178/// A string field inside an async host function's C ABI return struct.
179///
180/// Must be `#[repr(C)]` — its layout is `{ ptr: *const u8, len: usize }`,
181/// matching Zig's generated extern struct.
182///
183/// ## Example
184///
185/// ```rust,ignore
186/// #[repr(C)]
187/// pub struct FetchUserResult {
188///     pub id: i64,
189///     pub name: JsStrField,
190/// }
191///
192/// #[unsafe(no_mangle)]
193/// pub unsafe extern "C" fn fetch_user(
194///     name_ptr: *const u8, name_len: usize,
195/// ) -> FetchUserResult {
196///     let name = HostStr::from_raw(name_ptr, name_len);
197///     // ... async lookup ...
198///     FetchUserResult {
199///         id: user.id,
200///         name: JsStrField::new(&user.name),
201///     }
202/// }
203/// ```
204#[repr(C)]
205#[derive(Copy, Clone, Debug)]
206pub struct JsStrField {
207    /// Pointer to the string data in Zig Arena.
208    pub ptr: *const u8,
209    /// String length in bytes.
210    pub len: usize,
211}
212
213impl JsStrField {
214    /// Allocate a string in Zig Arena and return a `JsStrField`.
215    ///
216    /// Uses `js_allocator_dupe` (single C ABI call: allocate + copy).
217    /// Panics on OOM (the Zig side returns null on allocation failure).
218    #[inline]
219    pub fn new(s: &str) -> Self {
220        if s.is_empty() {
221            return Self::empty();
222        }
223        // NOTE: *mut u8 (not Option<*mut u8>) — see JsStr::new for ABI rationale.
224        unsafe extern "C" {
225            fn js_allocator_dupe(src: *const u8, len: usize) -> *mut u8;
226        }
227        let ptr = unsafe { js_allocator_dupe(s.as_ptr(), s.len()) };
228        assert!(
229            !ptr.is_null(),
230            "js_allocator_dupe returned null: Zig arena OOM"
231        );
232        Self { ptr, len: s.len() }
233    }
234
235    /// An empty string field (null pointer, zero length).
236    #[inline]
237    pub fn empty() -> Self {
238        Self {
239            ptr: std::ptr::null(),
240            len: 0,
241        }
242    }
243
244    /// Returns true if this is an empty string.
245    #[inline]
246    pub fn is_empty(&self) -> bool {
247        self.len == 0
248    }
249}
250
251// ── Test stubs for C ABI functions ─────────────────────────────
252// When compiled as a static lib (e.g. for `cargo test`), the Zig runtime
253// is not available, so we provide stubs for `js_allocator_dupe` and
254// `js_allocator_alloc`. These stubs leak memory (like the old Box::leak),
255// but tests don't run long enough for this to matter.
256// Returns null on OOM to match the Zig-side C ABI contract.
257
258#[cfg(any(test, feature = "stub-allocator"))]
259#[unsafe(no_mangle)]
260#[allow(clippy::not_unsafe_ptr_arg_deref)]
261pub extern "C" fn js_allocator_dupe(src: *const u8, len: usize) -> *mut u8 {
262    let layout = std::alloc::Layout::from_size_align(len, 1).unwrap();
263    let ptr = unsafe { std::alloc::alloc(layout) };
264    if ptr.is_null() {
265        return std::ptr::null_mut();
266    }
267    if len > 0 {
268        unsafe {
269            std::ptr::copy_nonoverlapping(src, ptr, len);
270        }
271    }
272    ptr
273}
274
275#[cfg(any(test, feature = "stub-allocator"))]
276#[unsafe(no_mangle)]
277#[allow(clippy::not_unsafe_ptr_arg_deref)]
278pub extern "C" fn js_allocator_alloc(size: usize) -> *mut u8 {
279    if size == 0 {
280        return std::ptr::null_mut();
281    }
282    let layout = std::alloc::Layout::from_size_align(size, 1).unwrap();
283    let ptr = unsafe { std::alloc::alloc(layout) };
284    if ptr.is_null() {
285        std::ptr::null_mut()
286    } else {
287        ptr
288    }
289}
290
291// ── StrRet helper (used by macro-generated safe wrappers) ──────────
292
293/// Internal helper to convert a `JsStr` to `Result<String, String>`,
294/// respecting the sign-bit error convention.
295///
296/// - `len >= 0` → success, bytes at `ptr[0..len]`
297/// - `len < 0`  → error, bytes at `ptr[0..|len|]`
298///
299/// # Safety
300///
301/// `ptr` must be valid for reads up to `len.abs()` bytes.
302#[doc(hidden)]
303pub unsafe fn js_str_to_result(ptr: *const u8, len: isize) -> Result<String, String> {
304    if len < 0 {
305        let err_len = (-len) as usize;
306        let err_msg = if err_len > 0 && !ptr.is_null() {
307            let slice = unsafe { std::slice::from_raw_parts(ptr, err_len) };
308            String::from_utf8_lossy(slice).into_owned()
309        } else {
310            "unknown error".to_string()
311        };
312        return Err(err_msg);
313    }
314    if ptr.is_null() || len == 0 {
315        return Ok(String::new());
316    }
317    let slice = unsafe { std::slice::from_raw_parts(ptr, len as usize) };
318    Ok(String::from_utf8_lossy(slice).into_owned())
319}