-
Notifications
You must be signed in to change notification settings - Fork 49
/
lib.rs
executable file
·58 lines (47 loc) · 1.59 KB
/
lib.rs
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
//! An example of what using `wee_alloc` as the global allocator in a
//! `#![no_std]` crate targeting `wasm32-unknown-unknown` looks like!
// First, some boilerplate and set up //////////////////////////////////////////
// We aren't using the standard library.
#![no_std]
// Replacing the allocator and using the `alloc` crate are still unstable.
#![feature(core_intrinsics, lang_items, alloc_error_handler)]
extern crate alloc;
extern crate wee_alloc;
// Use `wee_alloc` as the global allocator.
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
// Need to provide a tiny `panic` implementation for `#![no_std]`.
// This translates into an `unreachable` instruction that will
// raise a `trap` the WebAssembly execution if we panic at runtime.
#[panic_handler]
#[no_mangle]
pub fn panic(_info: &::core::panic::PanicInfo) -> ! {
unsafe {
::core::intrinsics::abort();
}
}
// Need to provide an allocation error handler which just aborts
// the execution with trap.
#[alloc_error_handler]
#[no_mangle]
pub extern "C" fn oom(_: ::core::alloc::Layout) -> ! {
unsafe {
::core::intrinsics::abort();
}
}
// Needed for non-wasm targets.
#[lang = "eh_personality"]
#[no_mangle]
pub extern "C" fn eh_personality() {}
// Now, use the allocator via `alloc` types! ///////////////////////////////////
use alloc::boxed::Box;
// Box a `u8`!
#[no_mangle]
pub extern "C" fn hello() -> *mut u8 {
Box::into_raw(Box::new(42))
}
// Free a `Box<u8>` that we allocated earlier!
#[no_mangle]
pub unsafe extern "C" fn goodbye(ptr: *mut u8) {
let _ = Box::from_raw(ptr);
}