Advertisement
Guest User

wasm_greeter.rs

a guest
Dec 11th, 2019
161
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.42 KB | None | 0 0
  1. //Based on https://github.com/wasmerio/php-ext-wasm/blob/master/examples/greet.rs
  2. //Javascript that uses this: https://pastebin.com/Pz9ZMgEm
  3.  
  4. #![no_std]
  5.  
  6. use core::panic::PanicInfo;
  7.  
  8. //RLS complains about this being a "duplicate lang item",
  9. //perhaps because my RLS is stable and I'm compiling with nightly?
  10. #[panic_handler]
  11. fn panic(_info: &PanicInfo) -> ! {
  12.     loop {}
  13. }
  14.  
  15. const SIZE: usize=20;
  16. static mut IN_BUF : [u8;SIZE]=[0;SIZE];
  17. static mut OUT_BUF: [u8;SIZE]=[0;SIZE];
  18.  
  19. #[no_mangle]
  20. pub fn get_input_ptr() -> *const u8 {
  21.     unsafe {IN_BUF}.as_ptr()
  22. }
  23.  
  24. #[no_mangle]
  25. pub fn greet(input_ptr: *const u8) -> *const u8 {
  26.     //input_ptr and get_input_ptr() should both point to IN_BUF,
  27.     //so why does only the first version work properly?
  28.     //JS logs "Hello, ใƒ†ใ‚นใƒˆ!"
  29.     let input: &[u8]=unsafe {core::slice::from_raw_parts(input_ptr,SIZE)};
  30.  
  31.     //JS logs "Hello, "
  32.     // let input: &[u8]=unsafe {core::slice::from_raw_parts(get_input_ptr(),SIZE)};
  33.  
  34.     //JS logs "Hello, !"
  35.     // let input: &[u8]=unsafe {&IN_BUF};
  36.  
  37.     let output: &mut [u8]=unsafe {&mut OUT_BUF};
  38.  
  39.     b"Hello, ".iter()
  40.         .chain(input.iter().take_while(|&&chr| chr!=0))
  41.         .chain(b"!\0")
  42.         .enumerate().for_each(|(i,&chr)| {
  43.             let elem=unsafe {output.get_unchecked_mut(i)};
  44.             *elem=chr;
  45.         });
  46.  
  47.     output.as_ptr()
  48.  
  49.     //JS logs input instead?!
  50.     // unsafe {OUT_BUF}.as_ptr()
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement