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).
152 pub len: isize,
153}
154
155impl JsStr {
156 /// Allocate a string in Zig Arena and return a `JsStr`.
157 ///
158 /// Uses `js_allocator_dupe` (single C ABI call: allocate + copy).
159 /// The memory lives in Zig's Arena and is freed when the allocator is deinitialized.
160 /// Panics on OOM (the Zig side returns null on allocation failure).
161 #[inline]
162 pub fn new(s: &str) -> Self {
163 if s.is_empty() {
164 return Self::empty();
165 }
166 let ptr = unsafe { dupe_to_arena(s) };
167 Self {
168 ptr,
169 len: s.len() as isize,
170 }
171 }
172
173 /// An empty string (null pointer, zero length).
174 #[inline]
175 pub fn empty() -> Self {
176 Self {
177 ptr: std::ptr::null(),
178 len: 0,
179 }
180 }
181
182 /// Returns true if this is an empty string.
183 #[inline]
184 pub fn is_empty(&self) -> bool {
185 self.len == 0
186 }
187}
188
189// ── Async struct string field ──────────────────────────────────────
190
191/// A string field inside an async host function's C ABI return struct.
192///
193/// Must be `#[repr(C)]` — its layout is `{ ptr: *const u8, len: usize }`,
194/// matching Zig's generated extern struct.
195///
196/// ## Example
197///
198/// ```rust,ignore
199/// #[repr(C)]
200/// pub struct FetchUserResult {
201/// pub id: i64,
202/// pub name: JsStrField,
203/// }
204///
205/// #[unsafe(no_mangle)]
206/// pub unsafe extern "C" fn fetch_user(
207/// name_ptr: *const u8, name_len: usize,
208/// ) -> FetchUserResult {
209/// let name = HostStr::from_raw(name_ptr, name_len);
210/// // ... async lookup ...
211/// FetchUserResult {
212/// id: user.id,
213/// name: JsStrField::new(&user.name),
214/// }
215/// }
216/// ```
217#[repr(C)]
218#[derive(Copy, Clone, Debug)]
219pub struct JsStrField {
220 /// Pointer to the string data in Zig Arena.
221 pub ptr: *const u8,
222 /// String length in bytes.
223 pub len: usize,
224}
225
226impl JsStrField {
227 /// Allocate a string in Zig Arena and return a `JsStrField`.
228 ///
229 /// Uses `js_allocator_dupe` (single C ABI call: allocate + copy).
230 /// Panics on OOM (the Zig side returns null on allocation failure).
231 #[inline]
232 pub fn new(s: &str) -> Self {
233 if s.is_empty() {
234 return Self::empty();
235 }
236 let ptr = unsafe { dupe_to_arena(s) };
237 Self { ptr, len: s.len() }
238 }
239
240 /// An empty string field (null pointer, zero length).
241 #[inline]
242 pub fn empty() -> Self {
243 Self {
244 ptr: std::ptr::null(),
245 len: 0,
246 }
247 }
248
249 /// Returns true if this is an empty string.
250 #[inline]
251 pub fn is_empty(&self) -> bool {
252 self.len == 0
253 }
254}
255
256// ── Test stubs for C ABI functions ─────────────────────────────
257// When compiled as a static lib (e.g. for `cargo test`), the Zig runtime
258// is not available, so we provide stubs for `js_allocator_dupe` and
259// `js_allocator_alloc`. These stubs leak memory (like the old Box::leak),
260// but tests don't run long enough for this to matter.
261// Returns null on OOM to match the Zig-side C ABI contract.
262
263#[cfg(any(test, feature = "stub-allocator"))]
264#[unsafe(no_mangle)]
265#[allow(clippy::not_unsafe_ptr_arg_deref)]
266pub extern "C" fn js_allocator_dupe(src: *const u8, len: usize) -> *mut u8 {
267 let layout = std::alloc::Layout::from_size_align(len, 1)
268 .expect("Layout::from_size_align(len, 1) is infallible: align=1 is power-of-two and divides any size");
269 let ptr = unsafe { std::alloc::alloc(layout) };
270 if ptr.is_null() {
271 return std::ptr::null_mut();
272 }
273 if len > 0 {
274 unsafe {
275 std::ptr::copy_nonoverlapping(src, ptr, len);
276 }
277 }
278 ptr
279}
280
281#[cfg(any(test, feature = "stub-allocator"))]
282#[unsafe(no_mangle)]
283#[allow(clippy::not_unsafe_ptr_arg_deref)]
284pub extern "C" fn js_allocator_alloc(size: usize) -> *mut u8 {
285 if size == 0 {
286 return std::ptr::null_mut();
287 }
288 let layout = std::alloc::Layout::from_size_align(size, 1)
289 .expect("Layout::from_size_align(size, 1) is infallible: align=1 is power-of-two and divides any size");
290 let ptr = unsafe { std::alloc::alloc(layout) };
291 if ptr.is_null() {
292 std::ptr::null_mut()
293 } else {
294 ptr
295 }
296}