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