1
//! Host function wrappers for WASM scripts.
2
//!
3
//! These functions are safe to call from within the Nomisync WASM runtime.
4
//! The WASM environment guarantees:
5
//! - Host functions are always linked
6
//! - Memory access is bounds-checked (traps on OOB)
7
//! - No undefined behavior, only traps on errors
8

            
9
// The runtime registers these under the `env` wasm import module
10
// (see `compiler::context::register_script_imports`). Recent Rust
11
// toolchains no longer default the import module, so the attribute is
12
// required — without it the symbols link as undefined.
13
#[link(wasm_import_module = "env")]
14
unsafe extern "C" {
15
    fn get_input_offset() -> u32;
16
    fn get_output_offset() -> u32;
17
    fn get_strings_offset() -> u32;
18
    fn generate_uuid(out_ptr: u32);
19
    fn write_string(ptr: u32, len: u32) -> u32;
20
    fn log(level: u32, msg_ptr: u32, msg_len: u32);
21
    fn get_timestamp() -> i64;
22
}
23

            
24
#[must_use]
25
pub fn input_offset() -> u32 {
26
    unsafe { get_input_offset() }
27
}
28

            
29
#[must_use]
30
pub fn output_offset() -> u32 {
31
    unsafe { get_output_offset() }
32
}
33

            
34
#[must_use]
35
pub fn strings_offset() -> u32 {
36
    unsafe { get_strings_offset() }
37
}
38

            
39
#[must_use]
40
pub fn new_uuid() -> [u8; 16] {
41
    let mut uuid = [0u8; 16];
42
    unsafe { generate_uuid(uuid.as_mut_ptr() as u32) };
43
    uuid
44
}
45

            
46
#[must_use]
47
pub fn write_output_string(s: &str) -> u32 {
48
    unsafe { write_string(s.as_ptr() as u32, s.len() as u32) }
49
}
50

            
51
#[must_use]
52
pub fn timestamp() -> i64 {
53
    unsafe { get_timestamp() }
54
}
55

            
56
#[repr(u32)]
57
#[derive(Debug, Clone, Copy)]
58
pub enum LogLevel {
59
    Debug = 0,
60
    Info = 1,
61
    Warn = 2,
62
    Error = 3,
63
}
64

            
65
pub fn log_message(level: LogLevel, msg: &str) {
66
    unsafe { log(level as u32, msg.as_ptr() as u32, msg.len() as u32) }
67
}
68

            
69
pub fn log_debug(msg: &str) {
70
    log_message(LogLevel::Debug, msg);
71
}
72

            
73
pub fn log_info(msg: &str) {
74
    log_message(LogLevel::Info, msg);
75
}
76

            
77
pub fn log_warn(msg: &str) {
78
    log_message(LogLevel::Warn, msg);
79
}
80

            
81
pub fn log_error(msg: &str) {
82
    log_message(LogLevel::Error, msg);
83
}