server/
definitions.rs

1// SPDX-FileCopyrightText: 2023 Foundation Devices, Inc. <hello@foundation.xyz>
2// SPDX-License-Identifier: GPL-3.0-or-later
3
4use whence::WhenceExt;
5
6use crate::ServerContext;
7
8/// A message that is known to be handled by a server. This is the type returned
9/// by the server message registration helpers.
10pub type MessageDef<S> = (xous::MessageId, MessageHandler<S>);
11
12pub(crate) type MessageHandler<S> = fn(&mut S, xous::MessageEnvelope, &mut ServerContext<S>);
13
14#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
15pub struct AsyncMessageInit<T> {
16    pub cid: xous::CID,
17    pub msg_id: xous::MessageId,
18    pub msg: T,
19}
20
21impl<T> AsyncMessageInit<T>
22where
23    T: crate::BlockingArchive,
24{
25    #[inline]
26    pub fn send_blocking_archive(self, cid: xous::CID) -> whence::Result<(), crate::Error> {
27        let buf = xous_ipc::Buffer::into_buf(&self).whence()?;
28        buf.send(cid, T::ID as u32).whence()?;
29        Ok(())
30    }
31}
32
33impl<T> AsyncMessageInit<T>
34where
35    T: crate::BlockingScalar,
36{
37    #[inline]
38    pub fn send_scalar(self, cid: xous::CID) -> whence::Result<(), crate::Error> {
39        let msg_init: AsyncMessageInit<[u32; 4]> =
40            AsyncMessageInit { cid: self.cid, msg_id: self.msg_id, msg: self.msg.as_scalar() };
41        let buf = xous_ipc::Buffer::into_buf(&msg_init).whence()?;
42        buf.send(cid, T::ID as u32).whence()?;
43        Ok(())
44    }
45}
46pub trait MessageId {
47    /// unique message identifier
48    const ID: xous::MessageId;
49    /// target server name
50    const SERVER: &'static str;
51}
52
53#[derive(Debug, Clone, Copy)]
54pub(crate) struct WrongMessageTypeError;
55
56impl std::fmt::Display for WrongMessageTypeError {
57    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "wrong message type") }
58}
59
60impl std::error::Error for WrongMessageTypeError {}