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
use crate::encode::{EncodeError, EncodeResult, Encoder};
use crate::message::Message;
use crate::value::Type;
use bytes::BytesMut;
use cfg_if::cfg_if;
#[cfg(target_family = "unix")]
use std::os::unix::io::RawFd;

impl Encoder {
    /// Encode a `Message` object to a byte array.
    pub fn message(&mut self, message: &Message) -> EncodeResult<()> {
        let is_le = message.header.is_le;
        // Encode the body in another buffer
        let mut encoder = Encoder::new();
        let mut body_signature = String::new();
        for v in &message.body {
            v.to_signature_string(&mut body_signature, 0, 0, 0)?;
            encoder.value(v, is_le)?;
        }

        cfg_if! {
            if #[cfg(target_family = "unix")] {
                self.fds = encoder.fds;
            }
        }

        let body = encoder.buf;
        let body_length = body.len() as u32;
        if body_length == 0 {
            if body_signature.is_empty() {
                self.message_header(&message.header, None)?;
            } else {
                let body_signature = Type::from_string_to_signature(&body_signature)?;
                return Err(EncodeError::BodyLengthZero(body_signature));
            }
        } else if body_signature.is_empty() {
            return Err(EncodeError::BodySignatureMissing(body_length));
        } else {
            let body_signature = Type::from_string_to_signature(&body_signature)?;
            let body = Some((body_length, body_signature));
            self.message_header(&message.header, body)?;
        }

        // Append the body.
        self.algin(8);
        self.buf.extend(body);

        Ok(())
    }
}

impl Message {
    pub fn encode(&self) -> EncodeResult<BytesMut> {
        let mut encoder = Encoder::new();
        encoder.message(self)?;
        Ok(encoder.buf)
    }

    #[cfg(target_family = "unix")]
    pub fn encode_with_fds(&self) -> EncodeResult<(BytesMut, Vec<RawFd>)> {
        let mut encoder = Encoder::new();
        encoder.message(self)?;
        let result = (encoder.buf, encoder.fds);
        Ok(result)
    }
}