/
state.rs
44 lines (39 loc) · 1008 Bytes
/
state.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
#[cfg(target_arch = "wasm32")] use alloc::prelude::Box;
#[cfg(target_arch = "wasm32")] use core::mem;
#[cfg(not(target_arch = "wasm32"))] use std::mem;
#[repr(C)]
pub struct State {
value: i32,
edit_count: u32,
}
#[no_mangle]
pub extern fn create(value: i32) -> *mut State {
let state = Box::new(State {
value,
edit_count: 0,
});
Box::into_raw(state)
}
#[no_mangle]
pub extern fn set(handle: *mut State, value: i32) -> u32 {
let mut state = unsafe { Box::from_raw(handle) };
state.value = value;
state.edit_count += 1;
let count = state.edit_count;
mem::forget(state);
count
}
#[no_mangle]
pub extern fn increment(handle: *mut State, offset: i32) -> u32 {
let mut state = unsafe { Box::from_raw(handle) };
state.value += offset;
state.edit_count += 1;
let count = state.edit_count;
mem::forget(state);
count
}
#[no_mangle]
pub extern fn unwrap(handle: *mut State) -> i32 {
let state = unsafe { Box::from_raw(handle) };
state.value
}