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
use proc_macro::{TokenStream};

use quote::quote;
use syn::ItemFn;

#[proc_macro_attribute]
pub fn entrypoint(_attr: TokenStream, mut item: TokenStream) -> TokenStream {
	let input: ItemFn = syn::parse(item.clone()).unwrap();
	let name = input.sig.ident;

	let gen = quote! {
		#[no_mangle]
		pub extern "C" fn mexFunction(nlhs: ::std::os::raw::c_int, lhs: *mut *mut ::rustmex::mxArray,
						nrhs: ::std::os::raw::c_int, rhs: *const *const ::rustmex::mxArray) {
			let rhslice = unsafe { ::std::slice::from_raw_parts(rhs as *const &::rustmex::mxArray, nrhs as usize) };
			let lhslice = unsafe { ::std::slice::from_raw_parts_mut(lhs as *mut Option<&mut ::rustmex::mxArray>, nlhs as usize) };

			// SAFETY: Transmuting to an MxArray is safe, since both it and
			// NonNull are repr(transparent).
			//
			// Also NOTE that transmute does nothing if Lhs is from before
			// v0.1.3, since where then doing transmute<T, T>.
			let lhslice_owned = unsafe { ::std::mem::transmute(lhslice) };

			match #name(lhslice_owned, rhslice) {
				Ok(_) => return,
				Err(e) => ::rustmex::message::error(&e)
			}
		}
	};
	let entrypoint: TokenStream = gen.into();
	item.extend(entrypoint);
	item
}