use crate::{
irc::{IrcMessage, MessageError, TagIndices},
MaybeOwnedIndex,
};
pub trait Validator {
fn parse_tags(&self) -> TagIndices;
fn expect_command(&self, cmd: &str) -> Result<(), MessageError>;
fn expect_nick(&self) -> Result<MaybeOwnedIndex, MessageError>;
fn expect_arg(&self, nth: usize) -> Result<&str, MessageError>;
fn expect_arg_index(&self, nth: usize) -> Result<MaybeOwnedIndex, MessageError>;
fn expect_data(&self) -> Result<&str, MessageError>;
fn expect_data_index(&self) -> Result<MaybeOwnedIndex, MessageError>;
}
impl<'a> Validator for IrcMessage<'a> {
fn parse_tags(&self) -> TagIndices {
self.tags
.and_then(|index| TagIndices::build_indices(&self.raw[index]).ok())
.unwrap_or_default()
}
fn expect_command(&self, cmd: &str) -> Result<(), MessageError> {
if self.get_command() != cmd {
return Err(MessageError::InvalidCommand {
expected: cmd.to_string(),
got: self.get_command().to_string(),
});
}
Ok(())
}
fn expect_nick(&self) -> Result<MaybeOwnedIndex, MessageError> {
self.prefix
.and_then(|p| p.nick_index())
.ok_or(MessageError::ExpectedNick)
}
fn expect_arg(&self, nth: usize) -> Result<&str, MessageError> {
self.nth_arg(nth)
.ok_or(MessageError::ExpectedArg { pos: nth })
}
fn expect_arg_index(&self, nth: usize) -> Result<MaybeOwnedIndex, MessageError> {
self.nth_arg_index(nth)
.ok_or(MessageError::ExpectedArg { pos: nth })
}
fn expect_data(&self) -> Result<&str, MessageError> {
self.expect_data_index().map(|index| &self.raw[index])
}
fn expect_data_index(&self) -> Result<MaybeOwnedIndex, MessageError> {
self.data.ok_or(MessageError::ExpectedData)
}
}