miltr_common/
encoding.rs

1//! Implement what components may write to the wire
2
3#[cfg(feature = "tracing")]
4use std::fmt::{self, Display};
5
6use bytes::BytesMut;
7use enum_dispatch::enum_dispatch;
8
9use super::actions::{
10    Abort, Action, Continue, Discard, Quit, QuitNc, Reject, Replycode, Skip, Tempfail,
11};
12use super::modifications::ModificationAction;
13
14use super::commands::{
15    Body, Command, Connect, Data, EndOfBody, EndOfHeader, Header, Helo, Mail, Recipient, Unknown,
16};
17use super::optneg::OptNeg;
18
19/// Write something 'to the wire'.
20#[enum_dispatch(ServerMessage)]
21#[enum_dispatch(ClientMessage)]
22#[enum_dispatch(ModificationAction)]
23#[enum_dispatch(Command)]
24#[enum_dispatch(Action)]
25#[enum_dispatch(OptNeg)]
26pub trait Writable {
27    /// Write self to the buffer
28    fn write(&self, buffer: &mut BytesMut);
29
30    /// Byte-length that would be written if [`Self::write`] is called
31    fn len(&self) -> usize;
32
33    /// The (unique) id code of this item
34    fn code(&self) -> u8;
35
36    /// Whether a call to [`Self::write`] would write something
37    fn is_empty(&self) -> bool;
38}
39
40/// Messages sent by the Server
41///
42/// This is used to decode things sent by the server and received by the client.
43#[enum_dispatch]
44#[derive(Debug)]
45pub enum ServerMessage {
46    /// Options received from the server
47    Optneg(OptNeg),
48    /// Control flow actions requested to be done by the server
49    Action,
50    /// Modifications requested by the server to be applied to the mail
51    ModificationAction,
52}
53
54#[cfg(feature = "tracing")]
55impl Display for ServerMessage {
56    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57        match self {
58            ServerMessage::Optneg(_optneg) => write!(f, "Optneg"),
59            ServerMessage::Action(action) => write!(f, "Action/{action}"),
60            ServerMessage::ModificationAction(mod_action) => {
61                write!(f, "ModificationAction/{mod_action}")
62            }
63        }
64    }
65}
66
67/// Messages sent by the Client
68///
69/// This is used to decode things sent by the client and received by the server.
70#[enum_dispatch]
71#[derive(Debug)]
72pub enum ClientMessage {
73    /// Options received from the client
74    Optneg(OptNeg),
75    /// Control flow actions requested by the client
76    Action,
77    /// SMTP commands reported by the client
78    Command,
79}
80
81#[cfg(feature = "tracing")]
82impl Display for ClientMessage {
83    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84        match self {
85            ClientMessage::Optneg(_optneg) => write!(f, "Optneg"),
86            ClientMessage::Action(action) => write!(f, "Action/{action}"),
87            ClientMessage::Command(command) => write!(f, "Command/{command}"),
88        }
89    }
90}