hakuban 0.7.2

Data-object sharing library
Documentation
#![allow(clippy::not_unsafe_ptr_arg_deref)]

use futures::{FutureExt, SinkExt, StreamExt};
use log::{error, trace};
use wasm_bindgen::prelude::*;

use super::{WasmFutureReturningNothing, WasmFutureReturningPointer, WasmLocalExchange};
use crate::{exchange::RemoteExchange, message::Message};

//TODO: check if all of this is leaking horribly

#[wasm_bindgen]
pub fn hakuban_remote_exchange_new(
	local_exchange_pointer: *mut WasmLocalExchange, upstream: bool, diff_produce: bool, diff_request: bool,
) -> *mut RemoteExchange {
	trace!("Constructing remote exchange");
	let local_exchange = unsafe { local_exchange_pointer.as_mut().unwrap() };
	Box::into_raw(Box::new(RemoteExchange::new(&local_exchange.local_exchange, upstream, Some(diff_produce), Some(diff_request))))
}

#[wasm_bindgen]
pub fn hakuban_remote_exchange_drop(remote_exchange_pointer: *mut RemoteExchange) {
	let remote_exchange = unsafe { Box::from_raw(remote_exchange_pointer) };
	trace!("Dropping remote exchange");
	drop(remote_exchange);
}

#[wasm_bindgen]
pub fn hakuban_remote_exchange_next_message_to_network(remote_exchange_pointer: *mut RemoteExchange) -> *mut WasmFutureReturningPointer {
	let remote_exchange = unsafe { remote_exchange_pointer.as_mut().unwrap() };
	Box::into_raw(Box::new(WasmFutureReturningPointer::new(
		remote_exchange.next().map(|item| item.map(|message| Box::into_raw(Box::new(message)) as *mut u8).into()),
	)))
}

#[wasm_bindgen]
pub fn hakuban_message_take(message_pointer: *mut Message) -> Box<[u8]> {
	let message = unsafe { message_pointer.as_mut().unwrap() };
	//TODO: is  this released by js properly?
	message.serialize().unwrap().into_boxed_slice()
}


#[wasm_bindgen]
pub fn hakuban_remote_exchange_send_message_from_network(
	remote_exchange_pointer: *mut RemoteExchange, message_data: Box<[u8]>,
) -> *mut WasmFutureReturningNothing {
	let remote_exchange = unsafe { remote_exchange_pointer.as_mut().unwrap() };
	let message: Message = Message::deserialize(&message_data).unwrap();
	Box::into_raw(Box::new(WasmFutureReturningNothing::new(remote_exchange.send(message).map(|result| {
		if let Err(error) = &result {
			error!("Hakuban message processing error: {}", error);
		};
		result.into()
	}))))
}