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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#![doc(hidden)]
use std::mem;
pub use crate::ffi::*;
pub use lazy_static::lazy_static;
pub use crate::handler::DefaultHandler;
pub fn new_leak_vec_ptr<T: Clone>(fill: T, length: i32) -> *mut T {
into_leak_vec_ptr(vec![fill; length as usize]).0
}
pub fn into_leak_vec_ptr<T: Clone>(mut v: Vec<T>) -> (*mut T, i32) {
v.shrink_to_fit();
assert!(v.len() == v.capacity());
let ptr = v.as_mut_ptr();
let len = v.len() as i32;
mem::forget(v);
(ptr, len)
}
pub unsafe fn vec_from_leak_ptr<T>(ptr: *mut T, len: i32) -> Vec<T> {
Vec::from_raw_parts(ptr, len as usize, len as usize)
}
pub fn from_vec_to_array<T, const N: usize>(v: Vec<T>) -> [T; N] {
core::convert::TryInto::try_into(v)
.unwrap_or_else(|v: Vec<T>| panic!("Expected a Vec of length {} but it was {}", N, v.len()))
}
pub fn new_leak_box_ptr<T>(t: T) -> *mut T {
let x: Box<T> = Box::new(t);
Box::into_raw(x)
}
pub unsafe fn box_from_leak_ptr<T>(ptr: *mut T) -> Box<T> {
Box::from_raw(ptr)
}
pub fn slice_from_byte_buffer<T: bytemuck::Pod>(buffer: Vec<u8>) -> Box<[T]> {
let buf = Box::leak(buffer.into_boxed_slice());
match bytemuck::try_cast_slice_mut(buf) {
Ok(buf) => unsafe { Box::from_raw(buf) },
Err(err) => {
unsafe { core::ptr::drop_in_place(buf) }
panic!("cast error: {}", err);
}
}
}
#[repr(C)]
#[cfg(not(wasm))]
pub struct WireSyncReturnStruct {
pub ptr: *mut u8,
pub len: i32,
pub success: bool,
}
#[cfg(wasm)]
pub type WireSyncReturnStruct = wasm_bindgen::JsValue;
pub struct WireSyncReturnData(pub(crate) Vec<u8>);
impl From<Vec<u8>> for WireSyncReturnData {
fn from(data: Vec<u8>) -> Self {
WireSyncReturnData(data)
}
}
impl From<bool> for WireSyncReturnData {
fn from(data: bool) -> Self {
if data { 1_u8 } else { 0_u8 }.into()
}
}
impl From<String> for WireSyncReturnData {
fn from(data: String) -> Self {
data.as_bytes().to_vec().into()
}
}
macro_rules! primitive_to_sync_return {
($($t:ty),+) => {
$(impl From<$t> for WireSyncReturnData {
fn from(data: $t) -> Self {
data.to_be_bytes().to_vec().into()
}
})*
}
}
primitive_to_sync_return!(u8, i8, u16, i16, u32, i32, u64, i64, f32, f64);