wasm_merge_sys/lib.rs
1//! Native build of `wasm-merge`.
2//!
3//! This crate builds the C++ code for `wasm-merge` from Binaryen
4//! and provides minimal Rust bindings.
5//!
6//! Most users will probably want higher-level APIs built on top of this.
7
8use std::ffi::CString;
9use std::os::raw::{c_char, c_int};
10
11unsafe extern "C" {
12 /// The wasm-merge main function.
13 ///
14 /// This is the C wrapper around the actual wasm-merge implementation
15 /// that handles exceptions and provides a C-compatible interface.
16 ///
17 /// # Arguments
18 ///
19 /// * `argc` - The number of command-line arguments
20 /// * `argv` - Pointer to an array of C strings representing the arguments
21 ///
22 /// # Returns
23 ///
24 /// The exit code of the wasm-merge tool (0 for success, non-zero for error)
25 ///
26 /// # Safety
27 ///
28 /// This function is unsafe because it:
29 /// - Takes raw pointers to C strings
30 /// - May call exit() or abort() on fatal errors
31 /// - Assumes argv is valid for argc elements
32 fn wasm_merge_main(argc: c_int, argv: *const *const c_char) -> c_int;
33}
34
35/// Run wasm-merge with the given command-line arguments.
36///
37/// This is a safe wrapper around the C `wasm_merge_main` function.
38///
39/// # Arguments
40///
41/// * `args` - A slice of string arguments (should include the program name as args[0])
42///
43/// # Returns
44///
45/// The exit code of wasm-merge (0 for success, non-zero for error)
46///
47/// # Example
48///
49/// ```no_run
50/// use wasm_merge_sys::run_wasm_merge;
51///
52/// let args = vec![
53/// "wasm-merge".to_string(),
54/// "module1.wasm".to_string(),
55/// "module1".to_string(),
56/// "module2.wasm".to_string(),
57/// "module2".to_string(),
58/// "-o".to_string(),
59/// "output.wasm".to_string(),
60/// ];
61///
62/// let exit_code = run_wasm_merge(&args);
63/// assert_eq!(exit_code, 0);
64/// ```
65pub fn run_wasm_merge(args: &[String]) -> i32 {
66 // Convert Rust strings to C strings
67 let c_strings: Vec<CString> = args
68 .iter()
69 .map(|arg| CString::new(arg.as_str()).expect("CString conversion failed"))
70 .collect();
71
72 // Create array of pointers to C strings
73 let c_args: Vec<*const c_char> = c_strings.iter().map(|s| s.as_ptr()).collect();
74
75 unsafe { wasm_merge_main(c_args.len() as c_int, c_args.as_ptr()) }
76}
77
78/// Just here so that cxx-build becomes willing to manage the set of include
79/// directories from this crate for downstream crates to include from.
80#[cxx::bridge]
81mod dummy {}