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
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
use std::borrow::Borrow;
use std::io;

use bytes::BytesMut;
use dencode::{Encoder, FramedWrite, IterSinkExt};

use crate::wire_format::WireFormat;
use crate::{Sbp, SbpMessage};
use crate::{BUFLEN, MAX_PAYLOAD_LEN, PREAMBLE};

/// Serialize the given message into the IO stream.
///
/// # Example
///
/// ```
/// use sbp::messages::logging::MsgLog;
///
/// fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let text = String::from("hello");
///     let msg = MsgLog {
///         sender_id: Some(1),
///         level: 1,
///         text: text.clone().into(),
///     };
///     let mut writer = Vec::new();
///     sbp::to_writer(&mut writer, &msg)?;
///     assert_eq!(
///         &writer[sbp::HEADER_LEN + 1..writer.len() - sbp::CRC_LEN],
///         text.as_bytes()
///     );
///     Ok(())
/// }
/// ```
pub fn to_writer<W, M>(mut writer: W, msg: &M) -> Result<(), Error>
where
    W: io::Write,
    M: SbpMessage,
{
    let mut buf = BytesMut::with_capacity(BUFLEN);
    to_buffer(&mut buf, msg)?;
    writer.write_all(&buf)?;
    Ok(())
}

/// Serialize the given message as a byte vector.
///
/// # Example
///
/// ```
/// use sbp::messages::logging::MsgLog;
///
/// fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let text = String::from("hello");
///     let msg = MsgLog {
///         sender_id: Some(1),
///         level: 1,
///         text: text.clone().into(),
///     };
///     let bytes = sbp::to_vec(&msg)?;
///     assert_eq!(
///         &bytes[sbp::HEADER_LEN + 1..bytes.len() - sbp::CRC_LEN],
///         text.as_bytes()
///     );
///     Ok(())
/// }
/// ```
pub fn to_vec<M: SbpMessage>(msg: &M) -> Result<Vec<u8>, Error> {
    let mut buf = BytesMut::with_capacity(BUFLEN);
    to_buffer(&mut buf, msg)?;
    Ok(buf.to_vec())
}

pub fn to_buffer<M: SbpMessage>(buf: &mut BytesMut, msg: &M) -> Result<(), WriteFrameError> {
    let sender_id = msg.sender_id().ok_or(WriteFrameError::NoSenderId)?;
    let payload_len = msg.len();
    if payload_len > MAX_PAYLOAD_LEN {
        return Err(WriteFrameError::TooLarge);
    }

    let old_buf = buf.split();

    PREAMBLE.write(buf);
    msg.message_type().write(buf);
    sender_id.write(buf);
    (payload_len as u8).write(buf);
    msg.write(buf);
    let crc = crc16::State::<crc16::XMODEM>::calculate(&buf[1..]);
    crc.write(buf);

    buf.unsplit(old_buf);

    Ok(())
}

/// All errors that can occur while writing messages.
#[derive(Debug)]
pub enum Error {
    WriteFrameError(WriteFrameError),
    IoError(io::Error),
}

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Error::WriteFrameError(e) => e.fmt(f),
            Error::IoError(e) => e.fmt(f),
        }
    }
}

impl std::error::Error for Error {}

impl From<WriteFrameError> for Error {
    fn from(e: WriteFrameError) -> Self {
        Error::WriteFrameError(e)
    }
}

impl From<io::Error> for Error {
    fn from(e: io::Error) -> Self {
        Error::IoError(e)
    }
}

#[derive(Debug, Clone)]
pub enum WriteFrameError {
    TooLarge,
    NoSenderId,
}

impl std::fmt::Display for WriteFrameError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            WriteFrameError::TooLarge => write!(f, "message is too large to fit into a frame"),
            WriteFrameError::NoSenderId => write!(f, "no sender id present in the message"),
        }
    }
}

impl std::error::Error for WriteFrameError {}

/// Writes [Sbp] messages into a writer.
#[derive(Debug)]
pub struct SbpEncoder<W>(FramedWrite<W, SbpEncoderInner>);

impl<W: io::Write> SbpEncoder<W> {
    /// Creates a new SbpEncoder.
    pub fn new(writer: W) -> SbpEncoder<W> {
        Self(FramedWrite::new(writer, SbpEncoderInner))
    }

    /// Send a message to the underlying writer. If sending multiple messages at once
    /// consider using [SbpEncoder::send_all] which buffers the writing.
    pub fn send(&mut self, message: &Sbp) -> Result<(), Error> {
        self.0.send(message)
    }

    /// Sends an iterator of messages to the underlying writer.
    pub fn send_all<I>(&mut self, messages: I) -> Result<(), Error>
    where
        I: IntoIterator<Item = Sbp>,
    {
        self.0.send_all(messages.into_iter().map(Result::Ok))
    }
}

#[derive(Debug)]
struct SbpEncoderInner;

impl<T> Encoder<T> for SbpEncoderInner
where
    T: Borrow<Sbp>,
{
    type Error = Error;

    fn encode(&mut self, msg: T, dst: &mut BytesMut) -> Result<(), Self::Error> {
        if let Err(err) = to_buffer(dst, msg.borrow()) {
            log::error!("error serializing message: {}", err);
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_to_vec() {
        let msg = crate::messages::system::MsgStartup {
            sender_id: Some(250),
            cause: 1,
            startup_type: 45,
            reserved: 0,
        };
        let frame = to_vec(&msg).unwrap();
        let expected_frame = b"\x55\x00\xFF\xFA\x00\x04\x01\x2D\x00\x00\xBC\x73";
        assert_eq!(frame, expected_frame);
    }

    #[test]
    fn test_to_writer() {
        let msg = crate::messages::system::MsgStartup {
            sender_id: Some(250),
            cause: 1,
            startup_type: 45,
            reserved: 0,
        };
        let mut writer = Vec::new();
        to_writer(&mut writer, &msg).unwrap();
        let expected_frame = b"\x55\x00\xFF\xFA\x00\x04\x01\x2D\x00\x00\xBC\x73";
        assert_eq!(writer, expected_frame);
    }
}