1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
//if we don't mark pub function as unsafe when it has unsafe sections, clippy will complain
//if we put an unsafe block inside an unsafe function, clippy will complain too
//we'd rather have every unsafe block explicit, so disabling warning that function is not unsafe
#![allow(clippy::not_unsafe_ptr_arg_deref)]

use wasm_bindgen::prelude::*;

use crate::LocalNode;


#[wasm_bindgen]
#[derive(Copy, Clone)]
#[repr(u8)]
pub enum FFIError {
	None = 0,
	InvalidString = 1,
	InvalidJSON = 2,
	InvalidURL = 3,
	ObjectNotFound = 4,
}


#[repr(C)]
#[wasm_bindgen]
pub struct FFILocalNodeNewResult {
	pub error: FFIError,
	pub local_node: *mut LocalNode,
}

//TODO: capacity, limit
#[no_mangle]
pub extern "C" fn hakuban_local_node_new(name_c: *const i8) -> FFILocalNodeNewResult {
	let name_str: &str = match unsafe { std::ffi::CStr::from_ptr(name_c).to_str() } {
		Ok(string) => string,
		Err(_error) => {
			return FFILocalNodeNewResult { error: FFIError::InvalidString, local_node: std::ptr::null_mut() };
		}
	};
	FFILocalNodeNewResult { error: FFIError::None, local_node: Box::into_raw(Box::new(LocalNode::builder().with_name(name_str).build())) }
}

#[no_mangle]
pub extern "C" fn hakuban_local_node_drop(local_node: *mut LocalNode) {
	drop(unsafe { Box::from_raw(local_node) });
}