Created
January 16, 2015 15:34
-
-
Save tilpner/e4bb5c551ba0b63ab8dd to your computer and use it in GitHub Desktop.
Part of message.rs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[derive(Show, PartialEq, Eq, Hash, Clone)] | |
pub struct Message { | |
pub prefix: Option<String>, | |
pub command: String, | |
pub content: Vec<String>, | |
pub suffix: Option<String> | |
} | |
impl Message { | |
pub fn new(prefix: Option<String>, command: String, content: Vec<String>, suffix: Option<String>) -> Message { | |
Message { | |
prefix: prefix, | |
command: command, | |
content: content, | |
suffix: suffix | |
} | |
} | |
pub fn parse(i: &str) -> Option<Message> { | |
info!("Attempting to parse message: {}", i); | |
let len = i.len(); | |
let mut s = i; | |
let prefix = if len >= 1 && s.char_at(0) == ':' { | |
s.find(' ').map(|i| { | |
let p = s.slice_chars(1, i).to_owned(); | |
s = &s[i + 1..]; | |
p | |
}) | |
} else { None }; | |
let command = s.find(' ').map(|i| { | |
let p = s.slice_chars(0, i).to_owned(); | |
s = &s[i..]; | |
p | |
}).and_then(|c| c.parse()); | |
// TODO: Parse last non-suffix argument as suffix if no suffix | |
// with colon is available. | |
let mut content = Vec::with_capacity(15); | |
let mut suffix = None; | |
while s.len() > 0 { | |
if s.char_at(0) == ':' { | |
suffix = Some(s.slice_from(1).to_owned()); | |
break | |
} | |
s.find(' ').map(|i| { | |
if i > 0 { | |
content.push(s.slice_chars(0, i).to_owned()); | |
s = &s[i..]; | |
} | |
}); | |
if s.char_at(0) == ' ' { s = &s[1..] }; | |
} | |
command.map(move |c| Message::new(prefix, c, content, suffix)) | |
} | |
pub fn format(&self) -> String { | |
let mut s = String::with_capacity(512); | |
if let Some(ref p) = self.prefix { | |
s.push(':'); | |
s.push_str(&p[]); | |
s.push(' '); | |
} | |
s.push_str(&self.command[]); | |
s.push(' '); | |
for part in self.content.iter() { | |
s.push_str(&part[]); | |
s.push(' '); | |
} | |
if let Some(ref p) = self.suffix { | |
s.push(':'); | |
s.push_str(&p[]); | |
} | |
s | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment