Gen7ScriptsRs/pkmn_lib_interface/src/utils.rs

83 lines
2.1 KiB
Rust
Executable File

use alloc::alloc::alloc;
use core::alloc::Layout;
#[cfg(not(feature = "mock_data"))]
use core::panic::PanicInfo;
#[cfg(feature = "mock_data")]
use cstr_core::CStr;
use cstr_core::{c_char, CString};
#[cfg(not(feature = "mock_data"))]
#[cfg(not(feature = "mock_data"))]
extern "wasm" {
fn _print(s: *const u8);
fn _error(message: *const u8, file: *const u8, line: u32, position: u32);
}
#[cfg(not(feature = "mock_data"))]
pub fn print_raw(s: CString) {
unsafe {
_print(s.as_ptr());
}
}
#[cfg(feature = "mock_data")]
pub fn print_raw(s: CString) {
unsafe {
println!("{}", s.into_string().unwrap());
}
}
#[macro_export]
macro_rules! println { ($($args:tt)*) => { pkmn_lib_interface::utils::print_raw(alloc::format!($($args)*).as_bytes()); } }
#[macro_export]
#[cfg(debug_assertions)]
macro_rules! dbg { ($($args:tt)*) => { pkmn_lib_interface::utils::print_raw(alloc::format!($($args)*).as_bytes()); } }
#[macro_export]
#[cfg(not(debug_assertions))]
macro_rules! dbg {
($($args:tt)*) => {{}};
}
#[panic_handler]
#[no_mangle]
#[cfg(not(feature = "mock_data"))]
#[cfg(not(test))]
pub fn begin_panic_handler(panic_info: &PanicInfo<'_>) -> ! {
let msg = CString::new(panic_info.message().unwrap().as_str().unwrap()).unwrap();
let mut line = 0;
let mut position = 0;
let mut file = CString::default();
if let Some(s) = panic_info.location() {
line = s.line();
position = s.column();
file = CString::new(s.file()).unwrap();
}
unsafe {
_error(msg.as_ptr(), file.as_ptr(), line, position);
}
loop {}
}
#[alloc_error_handler]
#[no_mangle]
#[cfg(not(feature = "mock_data"))]
#[cfg(not(test))]
fn allocation_error_handler(layout: core::alloc::Layout) -> ! {
panic!("memory allocation of {} bytes failed", layout.size())
}
#[no_mangle]
#[cfg(not(feature = "mock_data"))]
unsafe extern "wasm" fn allocate_mem(len: u32, align: u32) -> *mut u8 {
alloc(Layout::from_size_align(len as usize, align as usize).unwrap())
}
#[no_mangle]
#[cfg(not(feature = "mock_data"))]
unsafe extern "wasm" fn dealloc_cstring(ptr: *mut c_char) {
CString::from_raw(ptr);
}