#![unstable]
use std::fmt;
use std::fmt::{Show, Formatter};
use command::Command;
use self::TransactionState::{Unconnected, Connected, HelloSent, MailSent, RecipientSent, DataSent};
#[deriving(PartialEq,Eq,Copy)]
pub enum TransactionState {
Unconnected,
Connected,
HelloSent,
MailSent,
RecipientSent,
DataSent,
}
impl Show for TransactionState {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.write(
match *self {
Unconnected => "Unconnected",
Connected => "Connected",
HelloSent => "HelloSent",
MailSent => "MailSent",
RecipientSent => "RecipientSent",
DataSent => "DataSent",
}.as_bytes()
)
}
}
impl TransactionState {
pub fn new() -> TransactionState {
Unconnected
}
pub fn is_allowed(&self, command: &Command) -> bool {
(*self).next_state(command).is_some()
}
pub fn next_state(&self, command: &Command) -> Option<TransactionState> {
match (*self, command) {
(Unconnected, &Command::Connect) => Some(Connected),
(Unconnected, _) => None,
(DataSent, &Command::Message) => Some(HelloSent),
(DataSent, _) => None,
(_, &Command::ExtendedHello(_)) => Some(HelloSent),
(_, &Command::Hello(_)) => Some(HelloSent),
(Connected, &Command::Reset) => Some(Connected),
(_, &Command::Reset) => Some(HelloSent),
(state, &Command::Verify(_)) => Some(state),
(state, &Command::Expand(_)) => Some(state),
(state, &Command::Help(_)) => Some(state),
(state, &Command::Noop) => Some(state),
(_, &Command::Quit) => Some(Unconnected),
(HelloSent, &Command::Mail(_, _)) => Some(MailSent),
(MailSent, &Command::Recipient(_, _)) => Some(RecipientSent),
(RecipientSent, &Command::Recipient(_, _)) => Some(RecipientSent),
(RecipientSent, &Command::Data) => Some(DataSent),
(_, _) => None,
}
}
}
#[cfg(test)]
mod test {
use command::Command;
use super::TransactionState;
#[test]
fn test_new() {
assert_eq!(TransactionState::new(), TransactionState::Unconnected);
}
#[test]
fn test_is_allowed() {
assert!(!TransactionState::Unconnected.is_allowed(&Command::Noop));
assert!(!TransactionState::DataSent.is_allowed(&Command::Noop));
assert!(TransactionState::HelloSent.is_allowed(&Command::Mail("".to_string(), None)));
assert!(!TransactionState::MailSent.is_allowed(&Command::Mail("".to_string(), None)));
}
#[test]
fn test_next_state() {
assert_eq!(TransactionState::MailSent.next_state(&Command::Noop), Some(TransactionState::MailSent));
assert_eq!(TransactionState::HelloSent.next_state(&Command::Mail("".to_string(), None)),
Some(TransactionState::MailSent));
assert_eq!(TransactionState::MailSent.next_state(&Command::Mail("".to_string(), None)), None);
}
}