wasmedge_wasi_helper/
lib.rs

1pub mod wasmedge_wasi_helper {
2
3    #[no_mangle]
4    pub fn _initialize() {
5        extern "C" {
6            fn __wasm_call_ctors();
7        }
8        static mut INITED: bool = false;
9        if unsafe { INITED } {
10            return;
11        }
12        unsafe { __wasm_call_ctors() };
13        unsafe { INITED = true };
14    }
15
16    pub fn get_bytes_from_caller() -> Result<Vec<u8>, &'static str> {
17        // Get data path from the caller
18        let path = match std::env::var("WASMEDGE_DATA_TO_CALLEE") {
19            Err(_) => Err("No data found from caller. Please check the WASMEDGE_DATA_TO_CALLEE is set"),
20            Ok(val) => Ok(val),
21        };
22
23        // Read the data from the given path.
24        match std::fs::read(&path.unwrap()) {
25            Err(err) => {
26                eprintln!("Failed to open file. Due to: {:?}", err);
27                return Err("Cannot retrieve data from caller");
28            },
29            Ok(buf) => Ok(buf),
30        }
31    }
32
33    pub fn get_string_from_caller() -> Result<String, &'static str> {
34        // Get data path from the caller
35        let path = match std::env::var("WASMEDGE_DATA_TO_CALLEE") {
36            Err(_) => Err("No data found from caller. Please check the WASMEDGE_DATA_TO_CALLEE is set"),
37            Ok(val) => Ok(val),
38        };
39
40        // Read the data from the given path.
41        match std::fs::read(&path.unwrap()) {
42            Err(err) => {
43                eprintln!("Failed to open file. Due to: {:?}", err);
44                return Err("Cannot retrieve data from caller");
45            },
46            Ok(buf) => Ok(String::from_utf8_lossy(&buf).to_string()),
47        }
48    }
49
50    pub fn send_string_to_caller(s: &str) -> std::io::Result<()> {
51        // Get data path from the caller
52        let path = match std::env::var("WASMEDGE_DATA_FROM_CALLEE") {
53            Err(_) => Err("Cannot find path from caller. Please check the WASMEDGE_DATA_FROM_CALLEE is set"),
54            Ok(val) => Ok(val),
55        };
56
57        // Read the data from the given path.
58        std::fs::write(&path.unwrap(), s)?;
59        Ok(())
60    }
61
62    pub fn send_bytes_to_caller(bytes: &Vec<u8>) -> std::io::Result<()> {
63        // Get data path from the caller
64        let path = match std::env::var("WASMEDGE_DATA_FROM_CALLEE") {
65            Err(_) => Err("Cannot find path from caller. Please check the WASMEDGE_DATA_FROM_CALLEE is set"),
66            Ok(val) => Ok(val),
67        };
68
69        // Read the data from the given path.
70        std::fs::write(&path.unwrap(), bytes)?;
71        Ok(())
72    }
73}