use core::num::NonZeroU32;
use minicbor::{Decode, Decoder};
use oc_wasm_safe::Address;
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct BasicKeySignal {
pub keyboard: Address,
pub character: Option<char>,
pub keycode: Option<NonZeroU32>,
}
impl<'buffer> From<&KeySignal<'buffer>> for BasicKeySignal {
fn from(source: &KeySignal<'buffer>) -> Self {
Self {
keyboard: source.keyboard,
character: source.character,
keycode: source.keycode,
}
}
}
#[derive(Clone, Debug, Decode, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[cbor(array)]
pub struct KeySignal<'buffer> {
#[b(0)]
pub keyboard: Address,
#[b(1)]
#[cbor(decode_with = "KeySignal::decode_character")]
pub character: Option<char>,
#[b(2)]
#[cbor(decode_with = "KeySignal::decode_keycode")]
pub keycode: Option<NonZeroU32>,
#[b(3)]
pub player: Option<&'buffer str>,
}
impl<'buffer> KeySignal<'buffer> {
pub const KEY_DOWN: &'static str = "key_down";
pub const KEY_UP: &'static str = "key_up";
fn decode_character<Context>(
d: &mut Decoder<'buffer>,
_: &mut Context,
) -> Result<Option<char>, minicbor::decode::Error> {
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
let character = d.f64()? as u32;
if character == 0 {
Ok(None)
} else {
Ok(char::from_u32(character))
}
}
fn decode_keycode<Context>(
d: &mut Decoder<'buffer>,
_: &mut Context,
) -> Result<Option<NonZeroU32>, minicbor::decode::Error> {
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
let keycode = d.f64()? as u32;
Ok(NonZeroU32::new(keycode))
}
#[must_use]
pub fn to_basic(&self) -> BasicKeySignal {
BasicKeySignal::from(self)
}
}
#[derive(Clone, Debug, Decode, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[cbor(array)]
pub struct ClipboardSignal<'buffer> {
#[b(0)]
pub keyboard: Address,
#[b(1)]
pub text: &'buffer str,
#[b(2)]
pub player: Option<&'buffer str>,
}
impl ClipboardSignal<'_> {
pub const SIGNAL: &'static str = "clipboard";
}