Made a whole lot of linting changes to improve code.

Small API changes:
  1. Message::into_string -> Message:to_string
  2. NetStream::UnsecuredTcpStream -> NetStream::Unsecured
  3. NetStream::SslTcpStream -> NetStream::Ssl
This commit is contained in:
Aaron Weiss 2016-03-17 21:35:35 -04:00
parent 90d9f0568a
commit e4495940fc
12 changed files with 389 additions and 355 deletions

View file

@ -16,7 +16,7 @@ fn main() {
let server = server.clone();
let _ = spawn(move || {
for msg in server.iter() {
print!("{}", msg.unwrap().into_string());
print!("{}", msg.unwrap().to_string());
}
}).join(); // You might not want to join here for actual multi-threading.
}

View file

@ -15,7 +15,7 @@ fn main() {
server.identify().unwrap();
for message in server.iter() {
let message = message.unwrap(); // We'll just panic if there's an error.
print!("{}", message.into_string());
print!("{}", message.to_string());
match message.command {
Command::PRIVMSG(ref target, ref msg) => if msg.contains("pickles") {
server.send_privmsg(target, "Hi!").unwrap();

View file

@ -16,7 +16,7 @@ fn main() {
server.identify().unwrap();
for message in server.iter() {
let message = message.unwrap(); // We'll just panic if there's an error.
print!("{}", message.into_string());
print!("{}", message.to_string());
match message.command {
Command::PRIVMSG(ref target, ref msg) => if msg.contains("pickles") {
server.send_privmsg(target, "Hi!").unwrap();

View file

@ -17,7 +17,7 @@ fn main() {
let server2 = server.clone();
// Let's set up a loop that just prints the messages.
spawn(move || {
server2.iter().map(|m| print!("{}", m.unwrap().into_string())).count();
server2.iter().map(|m| print!("{}", m.unwrap().to_string())).count();
});
loop {
server.send_privmsg("#vana", "TWEET TWEET").unwrap();

View file

@ -77,8 +77,8 @@ impl NetConnection {
/// connects to the specified server and returns a reader-writer pair.
fn connect_internal(host: &str, port: u16) -> Result<NetReadWritePair> {
let socket = try!(TcpStream::connect(&format!("{}:{}", host, port)[..]));
Ok((BufReader::new(NetStream::UnsecuredTcpStream(try!(socket.try_clone()))),
BufWriter::new(NetStream::UnsecuredTcpStream(socket))))
Ok((BufReader::new(NetStream::Unsecured(try!(socket.try_clone()))),
BufWriter::new(NetStream::Unsecured(socket))))
}
/// Creates a thread-safe TCP connection to the specified server over SSL.
@ -94,8 +94,8 @@ impl NetConnection {
let socket = try!(TcpStream::connect(&format!("{}:{}", host, port)[..]));
let ssl = try!(ssl_to_io(SslContext::new(SslMethod::Tlsv1)));
let ssl_socket = try!(ssl_to_io(SslStream::connect_generic(&ssl, socket)));
Ok((BufReader::new(NetStream::SslTcpStream(try!(ssl_socket.try_clone()))),
BufWriter::new(NetStream::SslTcpStream(ssl_socket))))
Ok((BufReader::new(NetStream::Ssl(try!(ssl_socket.try_clone()))),
BufWriter::new(NetStream::Ssl(ssl_socket))))
}
/// Panics because SSL support is not compiled in.
@ -148,10 +148,10 @@ impl Connection for NetConnection {
}
fn reconnect(&self) -> Result<()> {
let use_ssl = match self.reader.lock().unwrap().get_ref() {
&NetStream::UnsecuredTcpStream(_) => false,
let use_ssl = match *self.reader.lock().unwrap().get_ref() {
NetStream::Unsecured(_) => false,
#[cfg(feature = "ssl")]
&NetStream::SslTcpStream(_) => true,
NetStream::Ssl(_) => true,
};
let host = self.host.lock().unwrap();
let port = self.port.lock().unwrap();
@ -279,7 +279,7 @@ mod imp {
match encoding.decode(&buf, DecoderTrap::Replace) {
_ if buf.is_empty() => Err(Error::new(ErrorKind::Other, "EOF")),
Ok(data) => Ok(data),
Err(data) => return Err(Error::new(ErrorKind::InvalidInput,
Err(data) => Err(Error::new(ErrorKind::InvalidInput,
&format!("Failed to decode {} as {}.", data, encoding.name())[..]
))
}
@ -301,37 +301,37 @@ mod imp {
/// An abstraction over different networked streams.
pub enum NetStream {
/// An unsecured TcpStream.
UnsecuredTcpStream(TcpStream),
Unsecured(TcpStream),
/// An SSL-secured TcpStream.
/// This is only available when compiled with SSL support.
#[cfg(feature = "ssl")]
SslTcpStream(SslStream<TcpStream>),
Ssl(SslStream<TcpStream>),
}
impl Read for NetStream {
fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
match self {
&mut NetStream::UnsecuredTcpStream(ref mut stream) => stream.read(buf),
match *self {
NetStream::Unsecured(ref mut stream) => stream.read(buf),
#[cfg(feature = "ssl")]
&mut NetStream::SslTcpStream(ref mut stream) => stream.read(buf),
NetStream::Ssl(ref mut stream) => stream.read(buf),
}
}
}
impl Write for NetStream {
fn write(&mut self, buf: &[u8]) -> Result<usize> {
match self {
&mut NetStream::UnsecuredTcpStream(ref mut stream) => stream.write(buf),
match *self {
NetStream::Unsecured(ref mut stream) => stream.write(buf),
#[cfg(feature = "ssl")]
&mut NetStream::SslTcpStream(ref mut stream) => stream.write(buf),
NetStream::Ssl(ref mut stream) => stream.write(buf),
}
}
fn flush(&mut self) -> Result<()> {
match self {
&mut NetStream::UnsecuredTcpStream(ref mut stream) => stream.flush(),
match *self {
NetStream::Unsecured(ref mut stream) => stream.flush(),
#[cfg(feature = "ssl")]
&mut NetStream::SslTcpStream(ref mut stream) => stream.flush(),
NetStream::Ssl(ref mut stream) => stream.flush(),
}
}
}
@ -345,12 +345,12 @@ mod test {
#[cfg(feature = "encode")]
fn send_to<C: Connection, M: Into<Message>>(conn: &C, msg: M, encoding: &str) -> Result<()> {
conn.send(&msg.into().into_string(), encoding)
conn.send(&msg.into().to_string(), encoding)
}
#[cfg(not(feature = "encode"))]
fn send_to<C: Connection, M: Into<Message>>(conn: &C, msg: M) -> Result<()> {
conn.send(&msg.into().into_string())
conn.send(&msg.into().to_string())
}

View file

@ -177,7 +177,7 @@ pub enum Command {
fn stringify(cmd: &str, args: Vec<&str>, suffix: Option<&str>) -> String {
let args = args.join(" ");
let sp = if args.len() > 0 { " " } else { "" };
let sp = if args.is_empty() { "" } else { " " };
match suffix {
Some(suffix) => format!("{}{}{} :{}", cmd, sp, args, suffix),
None => format!("{}{}{}", cmd, sp, args),
@ -428,7 +428,7 @@ impl Command {
Ok(if let "PASS" = cmd {
match suffix {
Some(suffix) => {
if args.len() != 0 { return Err(invalid_input()) }
if !args.is_empty() { return Err(invalid_input()) }
Command::PASS(suffix.to_owned())
},
None => {
@ -439,7 +439,7 @@ impl Command {
} else if let "NICK" = cmd {
match suffix {
Some(suffix) => {
if args.len() != 0 { return Err(invalid_input()) }
if !args.is_empty() { return Err(invalid_input()) }
Command::NICK(suffix.to_owned())
},
None => {
@ -500,7 +500,7 @@ impl Command {
}
}
} else if let "QUIT" = cmd {
if args.len() != 0 { return Err(invalid_input()) }
if !args.is_empty() { return Err(invalid_input()) }
match suffix {
Some(suffix) => Command::QUIT(Some(suffix.to_owned())),
None => Command::QUIT(None)
@ -518,7 +518,7 @@ impl Command {
}
} else if let "JOIN" = cmd {
match suffix {
Some(suffix) => if args.len() == 0 {
Some(suffix) => if args.is_empty() {
Command::JOIN(suffix.to_owned(), None, None)
} else if args.len() == 1 {
Command::JOIN(args[0].to_owned(), Some(suffix.to_owned()), None)
@ -540,7 +540,7 @@ impl Command {
}
} else if let "PART" = cmd {
match suffix {
Some(suffix) => if args.len() == 0 {
Some(suffix) => if args.is_empty() {
Command::PART(suffix.to_owned(), None)
} else if args.len() == 1 {
Command::PART(args[0].to_owned(), Some(suffix.to_owned()))
@ -557,7 +557,7 @@ impl Command {
}
} else if let "TOPIC" = cmd {
match suffix {
Some(suffix) => if args.len() == 0 {
Some(suffix) => if args.is_empty() {
Command::TOPIC(suffix.to_owned(), None)
} else if args.len() == 1 {
Command::TOPIC(args[0].to_owned(), Some(suffix.to_owned()))
@ -574,14 +574,14 @@ impl Command {
}
} else if let "NAMES" = cmd {
match suffix {
Some(suffix) => if args.len() == 0 {
Some(suffix) => if args.is_empty() {
Command::NAMES(Some(suffix.to_owned()), None)
} else if args.len() == 1 {
Command::NAMES(Some(args[0].to_owned()), Some(suffix.to_owned()))
} else {
return Err(invalid_input())
},
None => if args.len() == 0 {
None => if args.is_empty() {
Command::NAMES(None, None)
} else if args.len() == 1 {
Command::NAMES(Some(args[0].to_owned()), None)
@ -593,14 +593,14 @@ impl Command {
}
} else if let "LIST" = cmd {
match suffix {
Some(suffix) => if args.len() == 0 {
Some(suffix) => if args.is_empty() {
Command::LIST(Some(suffix.to_owned()), None)
} else if args.len() == 1 {
Command::LIST(Some(args[0].to_owned()), Some(suffix.to_owned()))
} else {
return Err(invalid_input())
},
None => if args.len() == 0 {
None => if args.is_empty() {
Command::LIST(None, None)
} else if args.len() == 1 {
Command::LIST(Some(args[0].to_owned()), None)
@ -649,21 +649,21 @@ impl Command {
None => return Err(invalid_input())
}
} else if let "MOTD" = cmd {
if args.len() != 0 { return Err(invalid_input()) }
if !args.is_empty() { return Err(invalid_input()) }
match suffix {
Some(suffix) => Command::MOTD(Some(suffix.to_owned())),
None => Command::MOTD(None)
}
} else if let "LUSERS" = cmd {
match suffix {
Some(suffix) => if args.len() == 0 {
Some(suffix) => if args.is_empty() {
Command::LUSERS(Some(suffix.to_owned()), None)
} else if args.len() == 1 {
Command::LUSERS(Some(args[0].to_owned()), Some(suffix.to_owned()))
} else {
return Err(invalid_input())
},
None => if args.len() == 0 {
None => if args.is_empty() {
Command::LUSERS(None, None)
} else if args.len() == 1 {
Command::LUSERS(Some(args[0].to_owned()), None)
@ -674,21 +674,21 @@ impl Command {
}
}
} else if let "VERSION" = cmd {
if args.len() != 0 { return Err(invalid_input()) }
if !args.is_empty() { return Err(invalid_input()) }
match suffix {
Some(suffix) => Command::VERSION(Some(suffix.to_owned())),
None => Command::VERSION(None)
}
} else if let "STATS" = cmd {
match suffix {
Some(suffix) => if args.len() == 0 {
Some(suffix) => if args.is_empty() {
Command::STATS(Some(suffix.to_owned()), None)
} else if args.len() == 1 {
Command::STATS(Some(args[0].to_owned()), Some(suffix.to_owned()))
} else {
return Err(invalid_input())
},
None => if args.len() == 0 {
None => if args.is_empty() {
Command::STATS(None, None)
} else if args.len() == 1 {
Command::STATS(Some(args[0].to_owned()), None)
@ -700,21 +700,21 @@ impl Command {
}
} else if let "LINKS" = cmd {
match suffix {
Some(suffix) => if args.len() == 0 {
Some(suffix) => if args.is_empty() {
Command::LINKS(None, Some(suffix.to_owned()))
} else if args.len() == 1 {
Command::LINKS(Some(args[0].to_owned()), Some(suffix.to_owned()))
} else {
return Err(invalid_input())
},
None => if args.len() == 0 {
None => if args.is_empty() {
Command::LINKS(None, None)
} else {
return Err(invalid_input())
}
}
} else if let "TIME" = cmd {
if args.len() != 0 { return Err(invalid_input()) }
if !args.is_empty() { return Err(invalid_input()) }
match suffix {
Some(suffix) => Command::TIME(Some(suffix.to_owned())),
None => Command::TIME(None)
@ -731,33 +731,33 @@ impl Command {
}
}
} else if let "TRACE" = cmd {
if args.len() != 0 { return Err(invalid_input()) }
if !args.is_empty() { return Err(invalid_input()) }
match suffix {
Some(suffix) => Command::TRACE(Some(suffix.to_owned())),
None => Command::TRACE(None)
}
} else if let "ADMIN" = cmd {
if args.len() != 0 { return Err(invalid_input()) }
if !args.is_empty() { return Err(invalid_input()) }
match suffix {
Some(suffix) => Command::ADMIN(Some(suffix.to_owned())),
None => Command::ADMIN(None)
}
} else if let "INFO" = cmd {
if args.len() != 0 { return Err(invalid_input()) }
if !args.is_empty() { return Err(invalid_input()) }
match suffix {
Some(suffix) => Command::INFO(Some(suffix.to_owned())),
None => Command::INFO(None)
}
} else if let "SERVLIST" = cmd {
match suffix {
Some(suffix) => if args.len() == 0 {
Some(suffix) => if args.is_empty() {
Command::SERVLIST(Some(suffix.to_owned()), None)
} else if args.len() == 1 {
Command::SERVLIST(Some(args[0].to_owned()), Some(suffix.to_owned()))
} else {
return Err(invalid_input())
},
None => if args.len() == 0 {
None => if args.is_empty() {
Command::SERVLIST(None, None)
} else if args.len() == 1 {
Command::SERVLIST(Some(args[0].to_owned()), None)
@ -780,14 +780,14 @@ impl Command {
}
} else if let "WHO" = cmd {
match suffix {
Some(suffix) => if args.len() == 0 {
Some(suffix) => if args.is_empty() {
Command::WHO(Some(suffix.to_owned()), None)
} else if args.len() == 1 {
Command::WHO(Some(args[0].to_owned()), Some(&suffix[..] == "o"))
} else {
return Err(invalid_input())
},
None => if args.len() == 0 {
None => if args.is_empty() {
Command::WHO(None, None)
} else if args.len() == 1 {
Command::WHO(Some(args[0].to_owned()), None)
@ -799,7 +799,7 @@ impl Command {
}
} else if let "WHOIS" = cmd {
match suffix {
Some(suffix) => if args.len() == 0 {
Some(suffix) => if args.is_empty() {
Command::WHOIS(None, suffix.to_owned())
} else if args.len() == 1 {
Command::WHOIS(Some(args[0].to_owned()), suffix.to_owned())
@ -816,7 +816,7 @@ impl Command {
}
} else if let "WHOWAS" = cmd {
match suffix {
Some(suffix) => if args.len() == 0 {
Some(suffix) => if args.is_empty() {
Command::WHOWAS(suffix.to_owned(), None, None)
} else if args.len() == 1 {
Command::WHOWAS(args[0].to_owned(), None, Some(suffix.to_owned()))
@ -850,7 +850,7 @@ impl Command {
}
} else if let "PING" = cmd {
match suffix {
Some(suffix) => if args.len() == 0 {
Some(suffix) => if args.is_empty() {
Command::PING(suffix.to_owned(), None)
} else if args.len() == 1 {
Command::PING(args[0].to_owned(), Some(suffix.to_owned()))
@ -867,7 +867,7 @@ impl Command {
}
} else if let "PONG" = cmd {
match suffix {
Some(suffix) => if args.len() == 0 {
Some(suffix) => if args.is_empty() {
Command::PONG(suffix.to_owned(), None)
} else if args.len() == 1 {
Command::PONG(args[0].to_owned(), Some(suffix.to_owned()))
@ -884,7 +884,7 @@ impl Command {
}
} else if let "ERROR" = cmd {
match suffix {
Some(suffix) => if args.len() == 0 {
Some(suffix) => if args.is_empty() {
Command::ERROR(suffix.to_owned())
} else {
return Err(invalid_input())
@ -893,7 +893,7 @@ impl Command {
}
} else if let "AWAY" = cmd {
match suffix {
Some(suffix) => if args.len() == 0 {
Some(suffix) => if args.is_empty() {
Command::AWAY(Some(suffix.to_owned()))
} else {
return Err(invalid_input())
@ -901,26 +901,26 @@ impl Command {
None => return Err(invalid_input())
}
} else if let "REHASH" = cmd {
if args.len() == 0 {
if args.is_empty() {
Command::REHASH
} else {
return Err(invalid_input())
}
} else if let "DIE" = cmd {
if args.len() == 0 {
if args.is_empty() {
Command::DIE
} else {
return Err(invalid_input())
}
} else if let "RESTART" = cmd {
if args.len() == 0 {
if args.is_empty() {
Command::RESTART
} else {
return Err(invalid_input())
}
} else if let "SUMMON" = cmd {
match suffix {
Some(suffix) => if args.len() == 0 {
Some(suffix) => if args.is_empty() {
Command::SUMMON(suffix.to_owned(), None, None)
} else if args.len() == 1 {
Command::SUMMON(args[0].to_owned(), Some(suffix.to_owned()), None)
@ -944,7 +944,7 @@ impl Command {
} else if let "USERS" = cmd {
match suffix {
Some(suffix) => {
if args.len() != 0 { return Err(invalid_input()) }
if !args.is_empty() { return Err(invalid_input()) }
Command::USERS(Some(suffix.to_owned()))
},
None => {
@ -955,7 +955,7 @@ impl Command {
} else if let "WALLOPS" = cmd {
match suffix {
Some(suffix) => {
if args.len() != 0 { return Err(invalid_input()) }
if !args.is_empty() { return Err(invalid_input()) }
Command::WALLOPS(suffix.to_owned())
},
None => {
@ -1039,7 +1039,7 @@ impl Command {
} else if let "NICKSERV" = cmd {
match suffix {
Some(suffix) => {
if args.len() != 0 { return Err(invalid_input()) }
if !args.is_empty() { return Err(invalid_input()) }
Command::NICKSERV(suffix.to_owned())
},
None => {
@ -1050,7 +1050,7 @@ impl Command {
} else if let "CHANSERV" = cmd {
match suffix {
Some(suffix) => {
if args.len() != 0 { return Err(invalid_input()) }
if !args.is_empty() { return Err(invalid_input()) }
Command::CHANSERV(suffix.to_owned())
},
None => {
@ -1061,7 +1061,7 @@ impl Command {
} else if let "OPERSERV" = cmd {
match suffix {
Some(suffix) => {
if args.len() != 0 { return Err(invalid_input()) }
if !args.is_empty() { return Err(invalid_input()) }
Command::OPERSERV(suffix.to_owned())
},
None => {
@ -1072,7 +1072,7 @@ impl Command {
} else if let "BOTSERV" = cmd {
match suffix {
Some(suffix) => {
if args.len() != 0 { return Err(invalid_input()) }
if !args.is_empty() { return Err(invalid_input()) }
Command::BOTSERV(suffix.to_owned())
},
None => {
@ -1083,7 +1083,7 @@ impl Command {
} else if let "HOSTSERV" = cmd {
match suffix {
Some(suffix) => {
if args.len() != 0 { return Err(invalid_input()) }
if !args.is_empty() { return Err(invalid_input()) }
Command::HOSTSERV(suffix.to_owned())
},
None => {
@ -1094,7 +1094,7 @@ impl Command {
} else if let "MEMOSERV" = cmd {
match suffix {
Some(suffix) => {
if args.len() != 0 { return Err(invalid_input()) }
if !args.is_empty() { return Err(invalid_input()) }
Command::MEMOSERV(suffix.to_owned())
},
None => {
@ -1145,7 +1145,7 @@ impl Command {
}
} else if let "AUTHENTICATE" = cmd {
match suffix {
Some(suffix) => if args.len() == 0 {
Some(suffix) => if args.is_empty() {
Command::AUTHENTICATE(suffix.to_owned())
} else {
return Err(invalid_input())
@ -1158,7 +1158,7 @@ impl Command {
}
} else if let "ACCOUNT" = cmd {
match suffix {
Some(suffix) => if args.len() == 0 {
Some(suffix) => if args.is_empty() {
Command::ACCOUNT(suffix.to_owned())
} else {
return Err(invalid_input())
@ -1206,7 +1206,7 @@ impl Command {
}
} else if let "BATCH" = cmd {
match suffix {
Some(suffix) => if args.len() == 0 {
Some(suffix) => if args.is_empty() {
Command::BATCH(suffix.to_owned(), None, None)
} else if args.len() == 1 {
Command::BATCH(args[0].to_owned(), Some(
@ -1288,15 +1288,15 @@ pub enum CapSubCommand {
impl CapSubCommand {
/// Gets the string that corresponds to this subcommand.
pub fn to_str(&self) -> &str {
match self {
&CapSubCommand::LS => "LS",
&CapSubCommand::LIST => "LIST",
&CapSubCommand::REQ => "REQ",
&CapSubCommand::ACK => "ACK",
&CapSubCommand::NAK => "NAK",
&CapSubCommand::END => "END",
&CapSubCommand::NEW => "NEW",
&CapSubCommand::DEL => "DEL",
match *self {
CapSubCommand::LS => "LS",
CapSubCommand::LIST => "LIST",
CapSubCommand::REQ => "REQ",
CapSubCommand::ACK => "ACK",
CapSubCommand::NAK => "NAK",
CapSubCommand::END => "END",
CapSubCommand::NEW => "NEW",
CapSubCommand::DEL => "DEL",
}
}
}
@ -1335,11 +1335,11 @@ pub enum MetadataSubCommand {
impl MetadataSubCommand {
/// Gets the string that corresponds to this subcommand.
pub fn to_str(&self) -> &str {
match self {
&MetadataSubCommand::GET => "GET",
&MetadataSubCommand::LIST => "LIST",
&MetadataSubCommand::SET => "SET",
&MetadataSubCommand::CLEAR => "CLEAR",
match *self {
MetadataSubCommand::GET => "GET",
MetadataSubCommand::LIST => "LIST",
MetadataSubCommand::SET => "SET",
MetadataSubCommand::CLEAR => "CLEAR",
}
}
}
@ -1371,10 +1371,10 @@ pub enum BatchSubCommand {
impl BatchSubCommand {
/// Gets the string that corresponds to this subcommand.
pub fn to_str(&self) -> &str {
match self {
&BatchSubCommand::NETSPLIT => "NETSPLIT",
&BatchSubCommand::NETJOIN => "NETJOIN",
&BatchSubCommand::CUSTOM(ref s) => &s,
match *self {
BatchSubCommand::NETSPLIT => "NETSPLIT",
BatchSubCommand::NETJOIN => "NETJOIN",
BatchSubCommand::CUSTOM(ref s) => &s,
}
}
}

View file

@ -75,7 +75,7 @@ impl Config {
/// Determines whether or not the nickname provided is the owner of the bot.
pub fn is_owner(&self, nickname: &str) -> bool {
self.owners.as_ref().map(|o| o.contains(&nickname.to_string())).unwrap()
self.owners.as_ref().map(|o| o.contains(&nickname.to_owned())).unwrap()
}
/// Gets the nickname specified in the configuration.
@ -87,26 +87,26 @@ impl Config {
/// Gets the bot's nickserv password specified in the configuration.
/// This defaults to an empty string when not specified.
pub fn nick_password(&self) -> &str {
self.nick_password.as_ref().map(|s| &s[..]).unwrap_or("")
self.nick_password.as_ref().map_or("", |s| &s[..])
}
/// Gets the alternate nicknames specified in the configuration.
/// This defaults to an empty vector when not specified.
pub fn alternate_nicknames(&self) -> Vec<&str> {
self.alt_nicks.as_ref().map(|v| v.iter().map(|s| &s[..]).collect()).unwrap_or(vec![])
self.alt_nicks.as_ref().map_or(vec![], |v| v.iter().map(|s| &s[..]).collect())
}
/// Gets the username specified in the configuration.
/// This defaults to the user's nickname when not specified.
pub fn username(&self) -> &str {
self.username.as_ref().map(|s| &s[..]).unwrap_or(self.nickname())
self.username.as_ref().map_or(self.nickname(), |s| &s[..])
}
/// Gets the real name specified in the configuration.
/// This defaults to the user's nickname when not specified.
pub fn real_name(&self) -> &str {
self.realname.as_ref().map(|s| &s[..]).unwrap_or(self.nickname())
self.realname.as_ref().map_or(self.nickname(), |s| &s[..])
}
/// Gets the address of the server specified in the configuration.
@ -118,7 +118,7 @@ impl Config {
/// Gets the port of the server specified in the configuration.
/// This defaults to 6667 (or 6697 if use_ssl is specified as true) when not specified.
pub fn port(&self) -> u16 {
self.port.as_ref().map(|p| *p).unwrap_or(if self.use_ssl() {
self.port.as_ref().cloned().unwrap_or(if self.use_ssl() {
6697
} else {
6667
@ -128,62 +128,62 @@ impl Config {
/// Gets the server password specified in the configuration.
/// This defaults to a blank string when not specified.
pub fn password(&self) -> &str {
self.password.as_ref().map(|s| &s[..]).unwrap_or("")
self.password.as_ref().map_or("", |s| &s[..])
}
/// Gets whether or not to use SSL with this connection.
/// This defaults to false when not specified.
pub fn use_ssl(&self) -> bool {
self.use_ssl.as_ref().map(|u| *u).unwrap_or(false)
self.use_ssl.as_ref().cloned().unwrap_or(false)
}
/// Gets the encoding to use for this connection. This requires the encode feature to work.
/// This defaults to UTF-8 when not specified.
pub fn encoding(&self) -> &str {
self.encoding.as_ref().map(|s| &s[..]).unwrap_or("UTF-8")
self.encoding.as_ref().map_or("UTF-8", |s| &s[..])
}
/// Gets the channels to join upon connection.
/// This defaults to an empty vector if it's not specified.
pub fn channels(&self) -> Vec<&str> {
self.channels.as_ref().map(|v| v.iter().map(|s| &s[..]).collect()).unwrap_or(vec![])
self.channels.as_ref().map_or(vec![], |v| v.iter().map(|s| &s[..]).collect())
}
/// Gets the user modes to set on connect specified in the configuration.
/// This defaults to an empty string when not specified.
pub fn umodes(&self) -> &str {
self.umodes.as_ref().map(|s| &s[..]).unwrap_or("")
self.umodes.as_ref().map_or("", |s| &s[..])
}
/// Gets the string to be sent in response to CTCP USERINFO requests.
/// This defaults to an empty string when not specified.
pub fn user_info(&self) -> &str {
self.user_info.as_ref().map(|s| &s[..]).unwrap_or("")
self.user_info.as_ref().map_or("", |s| &s[..])
}
/// Gets the amount of time in seconds since last activity necessary for the client to ping the
/// server.
/// This defaults to 180 seconds when not specified.
pub fn ping_time(&self) -> u32 {
self.ping_time.as_ref().map(|t| *t).unwrap_or(180)
self.ping_time.as_ref().cloned().unwrap_or(180)
}
/// Gets the amount of time in seconds for the client to reconnect after no ping response.
/// This defaults to 10 seconds when not specified.
pub fn ping_timeout(&self) -> u32 {
self.ping_timeout.as_ref().map(|t| *t).unwrap_or(10)
self.ping_timeout.as_ref().cloned().unwrap_or(10)
}
/// Gets whether or not to attempt nickname reclamation using NickServ GHOST.
/// This defaults to false when not specified.
pub fn should_ghost(&self) -> bool {
self.should_ghost.as_ref().map(|u| *u).unwrap_or(false)
self.should_ghost.as_ref().cloned().unwrap_or(false)
}
/// Gets the NickServ command sequence to recover a nickname.
/// This defaults to `["GHOST"]` when not specified.
pub fn ghost_sequence(&self) -> Vec<&str> {
self.ghost_sequence.as_ref().map(|v| v.iter().map(|s| &s[..]).collect()).unwrap_or(vec!["GHOST"])
self.ghost_sequence.as_ref().map_or(vec!["GHOST"], |v| v.iter().map(|s| &s[..]).collect())
}
/// Looks up the specified string in the options map.

View file

@ -47,7 +47,7 @@ impl Message {
}
/// Converts a Message into a String according to the IRC protocol.
pub fn into_string(&self) -> String {
pub fn to_string(&self) -> String {
// TODO: tags
let mut ret = String::new();
if let Some(ref prefix) = self.prefix {
@ -71,20 +71,20 @@ impl From<Command> for Message {
impl FromStr for Message {
type Err = &'static str;
fn from_str(s: &str) -> Result<Message, &'static str> {
let mut state = s.clone();
if s.len() == 0 { return Err("Cannot parse an empty string as a message.") }
let tags = if state.starts_with("@") {
let mut state = s;
if s.is_empty() { return Err("Cannot parse an empty string as a message.") }
let tags = if state.starts_with('@') {
let tags = state.find(' ').map(|i| &state[1..i]);
state = state.find(' ').map_or("", |i| &state[i+1..]);
tags.map(|ts| ts.split(";").filter(|s| s.len() != 0).map(|s: &str| {
let mut iter = s.splitn(2, "=");
tags.map(|ts| ts.split(';').filter(|s| !s.is_empty()).map(|s: &str| {
let mut iter = s.splitn(2, '=');
let (fst, snd) = (iter.next(), iter.next());
Tag(fst.unwrap_or("").to_owned(), snd.map(|s| s.to_owned()))
}).collect::<Vec<_>>())
} else {
None
};
let prefix = if state.starts_with(":") {
let prefix = if state.starts_with(':') {
let prefix = state.find(' ').map(|i| &state[1..i]);
state = state.find(' ').map_or("", |i| &state[i+1..]);
prefix
@ -106,7 +106,7 @@ impl FromStr for Message {
_ => return Err("Cannot parse a message without a command.")
};
if suffix.is_none() { state = &state[..state.len() - 2] }
let args: Vec<_> = state.splitn(14, ' ').filter(|s| s.len() != 0).collect();
let args: Vec<_> = state.splitn(14, ' ').filter(|s| !s.is_empty()).collect();
Message::with_tags(
tags, prefix, command, args, suffix
).map_err(|_| "Invalid input for Command.")
@ -174,19 +174,19 @@ mod test {
}
#[test]
fn into_string() {
fn to_string() {
let message = Message {
tags: None,
prefix: None,
command: PRIVMSG(format!("test"), format!("Testing!")),
};
assert_eq!(&message.into_string()[..], "PRIVMSG test :Testing!\r\n");
assert_eq!(&message.to_string()[..], "PRIVMSG test :Testing!\r\n");
let message = Message {
tags: None,
prefix: Some(format!("test!test@test")),
command: PRIVMSG(format!("test"), format!("Still testing!")),
};
assert_eq!(&message.into_string()[..], ":test!test@test PRIVMSG test :Still testing!\r\n");
assert_eq!(&message.to_string()[..], ":test!test@test PRIVMSG test :Still testing!\r\n");
}
#[test]

View file

@ -27,330 +27,330 @@ macro_rules! make_response {
make_response! {
// Expected replies
/// 001 Welcome to the Internet Relay Network <nick>!<user>@<host>
/// `001 Welcome to the Internet Relay Network <nick>!<user>@<host>`
RPL_WELCOME = 001,
/// 002 Your host is <servername>, running version <ver>
/// `002 Your host is <servername>, running version <ver>`
RPL_YOURHOST = 002,
/// 003 This server was created <date>
/// `003 This server was created <date>`
RPL_CREATED = 003,
/// 004 <servername> <version> <available user modes> available channel modes>
/// `004 <servername> <version> <available user modes> available channel modes>`
RPL_MYINFO = 004,
/// 005 Try server <server name>, port <port number>
/// `005 Try server <server name>, port <port number>`
RPL_BOUNCE = 005,
/// 302 :*1<reply> *( " " <reply> )
/// `302 :*1<reply> *( " " <reply> )`
RPL_USERHOST = 302,
/// 303 :*1<nick> *( " " <nick> )
/// `303 :*1<nick> *( " " <nick> )`
RPL_ISON = 303,
/// 301 <nick> :<away message>
/// `301 <nick> :<away message>`
RPL_AWAY = 301,
/// 305 :You are no longer marked as being away
/// `305 :You are no longer marked as being away`
RPL_UNAWAY = 305,
/// 306 :You have been marked as being away
/// `306 :You have been marked as being away`
RPL_NOWAWAY = 306,
/// 311 <nick> <user> <host> * :<real name>
/// `311 <nick> <user> <host> * :<real name>`
RPL_WHOISUSER = 311,
/// 312 <nick> <server> :<server info>
/// `312 <nick> <server> :<server info>`
RPL_WHOISSERVER = 312,
/// 313 <nick> :is an IRC operator
/// `313 <nick> :is an IRC operator`
RPL_WHOISOPERATOR = 313,
/// 317 <nick> <integer> :seconds idle
/// `317 <nick> <integer> :seconds idle`
RPL_WHOISIDLE = 317,
/// 318 <nick> :End of WHOIS list
/// `318 <nick> :End of WHOIS list`
RPL_ENDOFWHOIS = 318,
/// 319 <nick> :*( ( "@" / "+" ) <channel> " " )
/// `319 <nick> :*( ( "@" / "+" ) <channel> " " )`
RPL_WHOISCHANNELS = 319,
/// 314 <nick> <user> <host> * :<real name>
/// `314 <nick> <user> <host> * :<real name>`
RPL_WHOWASUSER = 314,
/// 369 <nick> :End of WHOWAS
/// `369 <nick> :End of WHOWAS`
RPL_ENDOFWHOWAS = 369,
/// Obsolete. Not used.
RPL_LISTSTART = 321,
/// 322 <channel> <# visible> :<topic>
/// `322 <channel> <# visible> :<topic>`
RPL_LIST = 322,
/// 323 :End of LIST
/// `323 :End of LIST
RPL_LISTEND = 323,
/// 325 <channel> <nickname>
/// `325 <channel> <nickname>`
RPL_UNIQOPIS = 325,
/// 324 <channel> <mode> <mode params>
/// `324 <channel> <mode> <mode params>`
RPL_CHANNELMODEIS = 324,
/// 331 <channel> :No topic is set
/// `331 <channel> :No topic is set`
RPL_NOTOPIC = 331,
/// 332 <channel> :<topic>
/// `332 <channel> :<topic>`
RPL_TOPIC = 332,
/// 341 <channel> <nick>
/// `341 <channel> <nick>`
RPL_INVITING = 341,
/// 342 <user> :Summoning user to IRC
/// `342 <user> :Summoning user to IRC`
RPL_SUMMONING = 342,
/// 346 <channel> <invitemask>
/// `346 <channel> <invitemask>`
RPL_INVITELIST = 346,
/// 347 <channel> :End of channel invite list
/// `347 <channel> :End of channel invite list`
RPL_ENDOFINVITELIST = 347,
/// 348 <channel> <exceptionmask>
/// `348 <channel> <exceptionmask>`
RPL_EXCEPTLIST = 348,
/// 349 <channel> :End of channel exception list
/// `349 <channel> :End of channel exception list`
RPL_ENDOFEXCEPTLIST = 349,
/// 351 <version>.<debuglevel> <server> :<comments>
/// `351 <version>.<debuglevel> <server> :<comments>`
RPL_VERSION = 351,
/** 352 <channel> <user> <host> <server> <nick> ( "H" / "G" > ["*"] [ ( "@" / "+" ) ]
:<hopcount> <real name> **/
/** `352 <channel> <user> <host> <server> <nick> ( "H" / "G" > ["*"] [ ( "@" / "+" ) ]
:<hopcount> <real name>` **/
RPL_WHOREPLY = 352,
/// 315 <name> :End of WHO list
/// `315 <name> :End of WHO list`
RPL_ENDOFWHO = 315,
/// 353 ( "=" / "*" / "@" ) <channel> :[ "@" / "+" ] <nick> *( " " [ "@" / "+" ] <nick> )
/// `353 ( "=" / "*" / "@" ) <channel> :[ "@" / "+" ] <nick> *( " " [ "@" / "+" ] <nick> )`
RPL_NAMREPLY = 353,
/// 366 <channel> :End of NAMES list
/// `366 <channel> :End of NAMES list`
RPL_ENDOFNAMES = 366,
/// 364 <mask> <server> :<hopcount> <server info>
/// `364 <mask> <server> :<hopcount> <server info>`
RPL_LINKS = 364,
/// 365 <mask> :End of LINKS list
/// `365 <mask> :End of LINKS list`
RPL_ENDOFLINKS = 365,
/// 367 <channel> <banmask>
/// `367 <channel> <banmask>`
RPL_BANLIST = 367,
/// 368 <channel> :End of channel ban list
/// `368 <channel> :End of channel ban list`
RPL_ENDOFBANLIST = 368,
/// 371 :<string>
/// `371 :<string>`
RPL_INFO = 371,
/// 374 :End of INFO list
/// `374 :End of INFO list`
RPL_ENDOFINFO = 374,
/// 375 :- <server> Message of the day -
/// `375 :- <server> Message of the day -`
RPL_MOTDSTART = 375,
/// 372 :- <text>
/// `372 :- <text>
RPL_MOTD = 372,
/// 376 :End of MOTD command
/// `376 :End of MOTD command
RPL_ENDOFMOTD = 376,
/// 381 :You are now an IRC operator
/// `381 :You are now an IRC operator
RPL_YOUREOPER = 381,
/// 382 <config file> :Rehashing
/// `382 <config file> :Rehashing
RPL_REHASHING = 382,
/// 383 You are service <servicename>
/// `383 You are service <servicename>
RPL_YOURESERVICE = 383,
/// 391 <server> :<string showing server's local time>
/// `391 <server> :<string showing server's local time>
RPL_TIME = 391,
/// 392 :UserID Terminal Host
/// `392 :UserID Terminal Host
RPL_USERSSTART = 392,
/// 393 :<username> <ttyline> <hostname>
/// `393 :<username> <ttyline> <hostname>
RPL_USERS = 393,
/// 394 :End of users
/// `394 :End of users
RPL_ENDOFUSERS = 394,
/// 395 :Nobody logged in
/// `395 :Nobody logged in
RPL_NOUSERS = 395,
/** 200 Link <version & debug level> <destination> <next server> V<protocol version>
/** `200 Link <version & debug level> <destination> <next server> V<protocol version>
<link uptime in seconds> <backstream sendq> <upstream sendq> **/
RPL_TRACELINK = 200,
/// 201 Try. <class> <server>
/// `201 Try. <class> <server>
RPL_TRACECONNECTING = 201,
/// 202 H.S. <class> <server>
/// `202 H.S. <class> <server>
RPL_TRACEHANDSHAKE = 202,
/// 203 ???? <class> [<client IP address in dot form>]
/// `203 ???? <class> [<client IP address in dot form>]
RPL_TRACEUKNOWN = 203,
/// 204 Oper <class> <nick>
/// `204 Oper <class> <nick>
RPL_TRACEOPERATOR = 204,
/// 205 User <class> <nick>
/// `205 User <class> <nick>
RPL_TRACEUSER = 205,
/// 206 Serv <class> <int>S <int>C <server> <nick!user|*!*>@<host|server> V<protocol version>
/// `206 Serv <class> <int>S <int>C <server> <nick!user|*!*>@<host|server> V<protocol version>
RPL_TRACESERVER = 206,
/// 207 Service <class> <name> <type> <active type>
/// `207 Service <class> <name> <type> <active type>
RPL_TRACESERVICE = 207,
/// 208 <newtype> 0 <client name>
/// `208 <newtype> 0 <client name>
RPL_TRACENEWTYPE = 208,
/// 209 Class <class> <count>
/// `209 Class <class> <count>
RPL_TRACECLASS = 209,
/// Unused.
RPL_TRACERECONNECT = 210,
/// 261 File <logfile> <debug level>
/// `261 File <logfile> <debug level>
RPL_TRACELOG = 261,
/// 262 <server name> <version & debug level> :End of TRACE
/// `262 <server name> <version & debug level> :End of TRACE
RPL_TRACEEND = 262,
/** 211 <linkname> <sendq> <sent messages> <sent Kbytes> <received messages> <received Kbytes>
/** `211 <linkname> <sendq> <sent messages> <sent Kbytes> <received messages> <received Kbytes>
<time open> **/
RPL_STATSLINKINFO = 211,
/// 212 <command> <count> <byte count> <remote count>
/// `212 <command> <count> <byte count> <remote count>
RPL_STATSCOMMANDS = 212,
/// 219 <stats letter> :End of STATS report
/// `219 <stats letter> :End of STATS report
RPL_ENDOFSTATS = 219,
/// 242 :Server Up %d days %d:%02d:%02d
/// `242 :Server Up %d days %d:%02d:%02d
RPL_STATSUPTIME = 242,
/// O <hostmask> * <name>
/// `243 O <hostmask> * <name>
RPL_STATSOLINE = 243,
/// 221 <user mode string>
/// `221 <user mode string>
RPL_UMODEIS = 221,
/// 234 <name> <server> <mask> <type> <hopcount> <info>
/// `234 <name> <server> <mask> <type> <hopcount> <info>
RPL_SERVLIST = 234,
/// 235 <mask> <type> :End of service listing
/// `235 <mask> <type> :End of service listing
RPL_SERVLISTEND = 235,
/// 251 :There are <integer> users and <integer> services on <integer> servers
/// `251 :There are <integer> users and <integer> services on <integer> servers
RPL_LUSERCLIENT = 251,
/// 252 <integer> :operator(s) online
/// `252 <integer> :operator(s) online
RPL_LUSEROP = 252,
/// 253 <integer> :unknown connection(s)
/// `253 <integer> :unknown connection(s)
RPL_LUSERUNKNOWN = 253,
/// 254 <integer> :channels formed
/// `254 <integer> :channels formed
RPL_LUSERCHANNELS = 254,
/// 255 :I have <integer> clients and <integer> servers
/// `255 :I have <integer> clients and <integer> servers
RPL_LUSERME = 255,
/// 256 <server> :Administrative info
/// `256 <server> :Administrative info
RPL_ADMINME = 256,
/// 257 :<admin info>
/// `257 :<admin info>
RPL_ADMINLOC1 = 257,
/// 258 :<admin info>
/// `258 :<admin info>
RPL_ADMINLOC2 = 258,
/// 259 :<admin info>
/// `259 :<admin info>
RPL_ADMINEMAIL = 259,
/// 263 <command> :Please wait a while and try again.
/// `263 <command> :Please wait a while and try again.
RPL_TRYAGAIN = 263,
/// 730 <nick> :target[,target2]*
/// `730 <nick> :target[,target2]*
RPL_MONONLINE = 730,
/// 731 <nick> :target[,target2]*
/// `731 <nick> :target[,target2]*
RPL_MONOFFLINE = 731,
/// 732 <nick> :target[,target2]*
/// `732 <nick> :target[,target2]*
RPL_MONLIST = 732,
/// 733 <nick> :End of MONITOR list
/// `733 <nick> :End of MONITOR list
RPL_ENDOFMONLIST = 733,
/// 760 <target> <key> <visibility> :<value>
/// `760 <target> <key> <visibility> :<value>
RPL_WHOISKEYVALUE = 760,
/// 761 <target> <key> <visibility> :[<value>]
/// `761 <target> <key> <visibility> :[<value>]
RPL_KEYVALUE = 761,
/// 762 :end of metadata
/// `762 :end of metadata
RPL_METADATAEND = 762,
/// 900 <nick> <nick>!<ident>@<host> <account> :You are now logged in as <user>
/// `900 <nick> <nick>!<ident>@<host> <account> :You are now logged in as <user>
RPL_LOGGEDIN = 900,
/// 901 <nick> <nick>!<ident>@<host> :You are now logged out
/// `901 <nick> <nick>!<ident>@<host> :You are now logged out
RPL_LOGGEDOUT = 901,
/// 903 <nick> :SASL authentication successful
/// `903 <nick> :SASL authentication successful
RPL_SASLSUCCESS = 903,
/// 908 <nick> <mechanisms> :are available SASL mechanisms
/// `908 <nick> <mechanisms> :are available SASL mechanisms
RPL_SASLMECHS = 908,
// Error replies
/// 401 <nickname> :No such nick/channel
/// `401 <nickname> :No such nick/channel
ERR_NOSUCHNICK = 401,
/// 402 <server name> :No such server
/// `402 <server name> :No such server
ERR_NOSUCHSERVER = 402,
/// 403 <channel name> :No such channel
/// `403 <channel name> :No such channel
ERR_NOSUCHCHANNEL = 403,
/// 404 <channel name> :Cannot send to channel
/// `404 <channel name> :Cannot send to channel
ERR_CANNOTSENDTOCHAN = 404,
/// 405 <channel name> :You have joined too many channels
/// `405 <channel name> :You have joined too many channels
ERR_TOOMANYCHANNELS = 405,
/// 406 <nickname> :There was no such nickname
/// `406 <nickname> :There was no such nickname
ERR_WASNOSUCHNICK = 406,
/// 407 <target> :<error code> recipients. <abort message>
/// `407 <target> :<error code> recipients. <abort message>
ERR_TOOMANYTARGETS = 407,
/// 408 <service name> :No such service
/// `408 <service name> :No such service
ERR_NOSUCHSERVICE = 408,
/// 409 :No origin specified
/// `409 :No origin specified
ERR_NOORIGIN = 409,
/// 411 :No recipient given (<command>)
/// `411 :No recipient given (<command>)
ERR_NORECIPIENT = 411,
/// 412 :No text to send
/// `412 :No text to send
ERR_NOTEXTTOSEND = 412,
/// 413 <mask> :No toplevel domain specified
/// `413 <mask> :No toplevel domain specified
ERR_NOTOPLEVEL = 413,
/// 414 <mask> :Wildcard in toplevel domain
/// `414 <mask> :Wildcard in toplevel domain
ERR_WILDTOPLEVEL = 414,
/// 415 <mask> :Bad Server/host mask
/// `415 <mask> :Bad Server/host mask
ERR_BADMASK = 415,
/// 421 <command> :Unknown command
/// `421 <command> :Unknown command
ERR_UNKNOWNCOMMAND = 421,
/// 422 :MOTD File is missing
/// `422 :MOTD File is missing
ERR_NOMOTD = 422,
/// 423 <server> :No administrative info available
/// `423 <server> :No administrative info available
ERR_NOADMININFO = 423,
/// 424 :File error doing <file op> on <file>
/// `424 :File error doing <file op> on <file>
ERR_FILEERROR = 424,
/// 431 :No nickname given
/// `431 :No nickname given
ERR_NONICKNAMEGIVEN = 431,
/// 432 <nick> :Erroneous nickname"
/// `432 <nick> :Erroneous nickname"
ERR_ERRONEOUSNICKNAME = 432,
/// 433 <nick> :Nickname is already in use
/// `433 <nick> :Nickname is already in use
ERR_NICKNAMEINUSE = 433,
/// 436 <nick> :Nickname collision KILL from <user>@<host>
/// `436 <nick> :Nickname collision KILL from <user>@<host>
ERR_NICKCOLLISION = 436,
/// 437 <nick/channel> :Nick/channel is temporarily unavailable
/// `437 <nick/channel> :Nick/channel is temporarily unavailable
ERR_UNAVAILRESOURCE = 437,
/// 441 <nick> <channel> :They aren't on that channel
/// `441 <nick> <channel> :They aren't on that channel
ERR_USERNOTINCHANNEL = 441,
/// 442 <channel> :You're not on that channel
/// `442 <channel> :You're not on that channel
ERR_NOTONCHANNEL = 442,
/// 443 <user> <channel> :is already on channel
/// `443 <user> <channel> :is already on channel
ERR_USERONCHANNEL = 443,
/// 444 <user> :User not logged in
/// `444 <user> :User not logged in
ERR_NOLOGIN = 444,
/// 445 :SUMMON has been disabled
/// `445 :SUMMON has been disabled
ERR_SUMMONDISABLED = 445,
/// 446 :USERS has been disabled
/// `446 :USERS has been disabled
ERR_USERSDISABLED = 446,
/// 451 :You have not registered
/// `451 :You have not registered
ERR_NOTREGISTERED = 451,
/// 461 <command> :Not enough parameters
/// `461 <command> :Not enough parameters
ERR_NEEDMOREPARAMS = 461,
/// 462 :Unauthorized command (already registered)
/// `462 :Unauthorized command (already registered)
ERR_ALREADYREGISTRED = 462,
/// 463 :Your host isn't among the privileged
/// `463 :Your host isn't among the privileged
ERR_NOPERMFORHOST = 463,
/// 464 :Password incorrect
/// `464 :Password incorrect
ERR_PASSWDMISMATCH = 464,
/// 465 :You are banned from this server
/// `465 :You are banned from this server
ERR_YOUREBANNEDCREEP = 465,
/// 466
/// `466
ERR_YOUWILLBEBANNED = 466,
/// 467 <channel> :Channel key already set
/// `467 <channel> :Channel key already set
ERR_KEYSET = 467,
/// 471 <channel> :Cannot join channel (+l)
/// `471 <channel> :Cannot join channel (+l)
ERR_CHANNELISFULL = 471,
/// 472 <char> :is unknown mode char to me for <channel>
/// `472 <char> :is unknown mode char to me for <channel>
ERR_UNKNOWNMODE = 472,
/// 473 <channel> :Cannot join channel (+i)
/// `473 <channel> :Cannot join channel (+i)
ERR_INVITEONLYCHAN = 473,
/// 474 <channel> :Cannot join channel (+b)
/// `474 <channel> :Cannot join channel (+b)
ERR_BANNEDFROMCHAN = 474,
/// 475 <channel> :Cannot join channel (+k)
/// `475 <channel> :Cannot join channel (+k)
ERR_BADCHANNELKEY = 475,
/// 476 <channel> :Bad Channel Mask
/// `476 <channel> :Bad Channel Mask
ERR_BADCHANMASK = 476,
/// 477 <channel> :Channel doesn't support modes
/// `477 <channel> :Channel doesn't support modes
ERR_NOCHANMODES = 477,
/// 478 <channel> <char> :Channel list is full
/// `478 <channel> <char> :Channel list is full
ERR_BANLISTFULL = 478,
/// 481 :Permission Denied- You're not an IRC operator
/// `481 :Permission Denied- You're not an IRC operator
ERR_NOPRIVILEGES = 481,
/// 482 <channel> :You're not channel operator
/// `482 <channel> :You're not channel operator
ERR_CHANOPRIVSNEEDED = 482,
/// 483 :You can't kill a server!
/// `483 :You can't kill a server!
ERR_CANTKILLSERVER = 483,
/// 484 :Your connection is restricted!
/// `484 :Your connection is restricted!
ERR_RESTRICTED = 484,
/// 485 :You're not the original channel operator
/// `485 :You're not the original channel operator
ERR_UNIQOPPRIVSNEEDED = 485,
/// 491 :No O-lines for your host
/// `491 :No O-lines for your host
ERR_NOOPERHOST = 491,
/// 501 :Unknown MODE flag
/// `501 :Unknown MODE flag
ERR_UMODEUNKNOWNFLAG = 501,
/// 502 :Cannot change mode for other users
/// `502 :Cannot change mode for other users
ERR_USERSDONTMATCH = 502,
/// 734 <nick> <limit> <targets> :Monitor list is full.
/// `734 <nick> <limit> <targets> :Monitor list is full.
ERR_MONLISTFULL = 734,
/// 764 <target> :metadata limit reached
/// `764 <target> :metadata limit reached
ERR_METADATALIMIT = 764,
/// 765 <target> :invalid metadata target
/// `765 <target> :invalid metadata target
ERR_TARGETINVALID = 765,
/// 766 <key> :no matching key
/// `766 <key> :no matching key
ERR_NOMATCHINGKEY = 766,
/// 767 <key> :invalid metadata key
/// `767 <key> :invalid metadata key
ERR_KEYINVALID = 767,
/// 768 <target> <key> :key not set
/// `768 <target> <key> :key not set
ERR_KEYNOTSET = 768,
/// 769 <target> <key> :permission denied
/// `769 <target> <key> :permission denied
ERR_KEYNOPERMISSION = 769,
/// 902 <nick> :You must use a nick assigned to you.
/// `902 <nick> :You must use a nick assigned to you.
ERR_NICKLOCKED = 902,
/// 904 <nick> :SASL authentication failed
/// `904 <nick> :SASL authentication failed
ERR_SASLFAIL = 904,
/// 905 <nick> :SASL message too long
/// `905 <nick> :SASL message too long
ERR_SASLTOOLONG = 905,
/// 906 <nick> :SASL authentication aborted
/// `906 <nick> :SASL authentication aborted
ERR_SASLABORT = 906,
/// 907 <nick> :You have already authenticated using SASL
/// `907 <nick> :You have already authenticated using SASL
ERR_SASLALREADY = 907
}

View file

@ -98,7 +98,7 @@ impl User {
if level > self.highest_access_level() {
self.highest_access_level = level
}
self.access_levels.push(level.clone())
self.access_levels.push(level)
}
/// Removes an access level from the list, and updates the highest level if necessary.
@ -109,9 +109,9 @@ impl User {
if level == self.highest_access_level() {
self.highest_access_level = {
let mut max = AccessLevel::Member;
for level in self.access_levels.iter() {
for level in &self.access_levels {
if level > &max {
max = level.clone()
max = *level
}
}
max
@ -147,37 +147,37 @@ pub enum AccessLevel {
impl PartialOrd for AccessLevel {
fn partial_cmp(&self, other: &AccessLevel) -> Option<Ordering> {
if self == other { return Some(Equal) }
match self {
&AccessLevel::Owner => Some(Greater),
&AccessLevel::Admin => {
match *self {
AccessLevel::Owner => Some(Greater),
AccessLevel::Admin => {
if other == &AccessLevel::Owner {
Some(Less)
} else {
Some(Greater)
}
},
&AccessLevel::Oper => {
AccessLevel::Oper => {
if other == &AccessLevel::Owner || other == &AccessLevel::Admin {
Some(Less)
} else {
Some(Greater)
}
},
&AccessLevel::HalfOp => {
AccessLevel::HalfOp => {
if other == &AccessLevel::Voice || other == &AccessLevel::Member {
Some(Greater)
} else {
Some(Less)
}
},
&AccessLevel::Voice => {
AccessLevel::Voice => {
if other == &AccessLevel::Member {
Some(Greater)
} else {
Some(Less)
}
},
&AccessLevel::Member => Some(Less),
AccessLevel::Member => Some(Less),
}
}
}
@ -212,7 +212,7 @@ impl Iterator for AccessLevelIterator {
type Item = AccessLevel;
fn next(&mut self) -> Option<AccessLevel> {
let ret = self.value.parse();
if self.value.len() > 0 {
if !self.value.is_empty() {
self.value = self.value.chars().skip(1).collect()
}
ret.ok()

View file

@ -96,7 +96,7 @@ impl ServerState {
}
fn last_ping_data(&self) -> Option<Timespec> {
self.last_ping_data.lock().unwrap().clone()
*self.last_ping_data.lock().unwrap()
}
fn send_impl(&self, msg: Message) {
@ -108,12 +108,12 @@ impl ServerState {
#[cfg(feature = "encode")]
fn write<M: Into<Message>>(&self, msg: M) -> Result<()> {
self.conn.send(&msg.into().into_string(), self.config.encoding())
self.conn.send(&msg.into().to_string(), self.config.encoding())
}
#[cfg(not(feature = "encode"))]
fn write<M: Into<Message>>(&self, msg: M) -> Result<()> {
self.conn.send(&msg.into().into_string())
self.conn.send(&msg.into().to_string())
}
}
@ -269,79 +269,31 @@ impl IrcServer {
fn handle_message(&self, msg: &Message) -> Result<()> {
match msg.command {
PING(ref data, _) => try!(self.send_pong(&data)),
JOIN(ref chan, _, _) => if cfg!(not(feature = "nochanlists")) {
if let Some(vec) = self.chanlists().lock().unwrap().get_mut(&chan.to_owned()) {
if let Some(src) = msg.source_nickname() {
vec.push(User::new(src))
}
}
},
PART(ref chan, _) => if cfg!(not(feature = "nochanlists")) {
if let Some(vec) = self.chanlists().lock().unwrap().get_mut(&chan.to_owned()) {
if let Some(src) = msg.source_nickname() {
if let Some(n) = vec.iter().position(|x| x.get_nickname() == src) {
vec.swap_remove(n);
}
}
}
},
MODE(ref chan, ref mode, Some(ref user)) => if cfg!(not(feature = "nochanlists")) {
if let Some(vec) = self.chanlists().lock().unwrap().get_mut(chan) {
if let Some(n) = vec.iter().position(|x| x.get_nickname() == user) {
vec[n].update_access_level(&mode)
}
}
},
PRIVMSG(ref target, ref body) => if body.starts_with("\u{001}") {
JOIN(ref chan, _, _) => self.handle_join(msg.source_nickname().unwrap_or(""), chan),
PART(ref chan, _) => self.handle_part(msg.source_nickname().unwrap_or(""), chan),
MODE(ref chan, ref mode, Some(ref user)) => self.handle_mode(chan, mode, user),
PRIVMSG(ref target, ref body) => if body.starts_with('\u{001}') {
let tokens: Vec<_> = {
let end = if body.ends_with("\u{001}") {
let end = if body.ends_with('\u{001}') {
body.len() - 1
} else {
body.len()
};
body[1..end].split(" ").collect()
body[1..end].split(' ').collect()
};
if target.starts_with("#") {
if target.starts_with('#') {
try!(self.handle_ctcp(&target, tokens))
} else if let Some(user) = msg.source_nickname() {
try!(self.handle_ctcp(user, tokens))
}
},
Command::Response(Response::RPL_NAMREPLY, ref args, ref suffix) => {
if cfg!(not(feature = "nochanlists")) {
if let Some(users) = suffix.clone() {
if args.len() == 3 {
let ref chan = args[2];
for user in users.split(" ") {
let mut chanlists = self.state.chanlists.lock().unwrap();
chanlists.entry(chan.clone()).or_insert(Vec::new())
.push(User::new(user))
}
}
}
}
self.handle_namreply(args, suffix)
},
Command::Response(Response::RPL_ENDOFMOTD, _, _) |
Command::Response(Response::ERR_NOMOTD, _, _) => {
if self.config().nick_password() != "" {
let mut index = self.state.alt_nick_index.write().unwrap();
if self.config().should_ghost() && *index != 0 {
for seq in self.config().ghost_sequence().iter() {
try!(self.send(NICKSERV(format!(
"{} {} {}", seq, self.config().nickname(),
self.config().nick_password()
))));
}
*index = 0;
try!(self.send(NICK(self.config().nickname().to_owned())))
}
try!(self.send(NICKSERV(
format!("IDENTIFY {}", self.config().nick_password())
)))
}
if self.config().umodes() != "" {
try!(self.send_mode(self.current_nickname(), self.config().umodes(), ""))
}
try!(self.send_nick_password());
try!(self.send_umodes());
for chan in self.config().channels().into_iter() {
try!(self.send_join(chan))
}
@ -362,6 +314,88 @@ impl IrcServer {
Ok(())
}
fn send_nick_password(&self) -> Result<()> {
if self.config().nick_password().is_empty() {
Ok(())
} else {
let mut index = self.state.alt_nick_index.write().unwrap();
if self.config().should_ghost() && *index != 0 {
for seq in &self.config().ghost_sequence() {
try!(self.send(NICKSERV(format!(
"{} {} {}", seq, self.config().nickname(),
self.config().nick_password()
))));
}
*index = 0;
try!(self.send(NICK(self.config().nickname().to_owned())))
}
self.send(NICKSERV(format!("IDENTIFY {}", self.config().nick_password())))
}
}
fn send_umodes(&self) -> Result<()> {
if self.config().umodes().is_empty() {
Ok(())
} else {
self.send_mode(self.current_nickname(), self.config().umodes(), "")
}
}
#[cfg(feature = "nochanlists")]
fn handle_join(&self, _: &str, _: &str) {}
#[cfg(not(feature = "nochanlists"))]
fn handle_join(&self, src: &str, chan: &str) {
if let Some(vec) = self.chanlists().lock().unwrap().get_mut(&chan.to_owned()) {
if !src.is_empty() {
vec.push(User::new(src))
}
}
}
#[cfg(feature = "nochanlists")]
fn handle_part(&self, src: &str, chan: &str) {}
#[cfg(not(feature = "nochanlists"))]
fn handle_part(&self, src: &str, chan: &str) {
if let Some(vec) = self.chanlists().lock().unwrap().get_mut(&chan.to_owned()) {
if !src.is_empty() {
if let Some(n) = vec.iter().position(|x| x.get_nickname() == src) {
vec.swap_remove(n);
}
}
}
}
#[cfg(feature = "nochanlists")]
fn handle_mode(&self, chan: &str, mode: &str, user: &str) {}
#[cfg(not(feature = "nochanlists"))]
fn handle_mode(&self, chan: &str, mode: &str, user: &str) {
if let Some(vec) = self.chanlists().lock().unwrap().get_mut(chan) {
if let Some(n) = vec.iter().position(|x| x.get_nickname() == user) {
vec[n].update_access_level(&mode)
}
}
}
#[cfg(feature = "nochanlists")]
fn handle_namreply(&self, _: &[String], _: &Option<String>) {}
#[cfg(not(feature = "nochanlists"))]
fn handle_namreply(&self, args: &[String], suffix: &Option<String>) {
if let Some(ref users) = *suffix {
if args.len() == 3 {
let chan = &args[2];
for user in users.split(' ') {
let mut chanlists = self.state.chanlists.lock().unwrap();
chanlists.entry(chan.clone()).or_insert_with(Vec::new)
.push(User::new(user))
}
}
}
}
/// Handles CTCP requests if the CTCP feature is enabled.
#[cfg(feature = "ctcp")]
fn handle_ctcp(&self, resp: &str, tokens: Vec<&str>) -> Result<()> {
@ -487,7 +521,7 @@ mod test {
let server = IrcServer::from_connection(test_config(), MockConnection::new(exp));
let mut messages = String::new();
for message in server.iter() {
messages.push_str(&message.unwrap().into_string());
messages.push_str(&message.unwrap().to_string());
}
assert_eq!(&messages[..], exp);
}

View file

@ -95,7 +95,7 @@ pub trait ServerExt: Server {
/// Sets the topic of a channel or requests the current one.
/// If `topic` is an empty string, it won't be included in the message.
fn send_topic(&self, channel: &str, topic: &str) -> Result<()> where Self: Sized {
self.send(TOPIC(channel.to_owned(), if topic.len() == 0 {
self.send(TOPIC(channel.to_owned(), if topic.is_empty() {
None
} else {
Some(topic.to_owned())
@ -111,7 +111,7 @@ pub trait ServerExt: Server {
/// If `message` is an empty string, it won't be included in the message.
fn send_kick(&self, chanlist: &str, nicklist: &str, message: &str) -> Result<()>
where Self: Sized {
self.send(KICK(chanlist.to_owned(), nicklist.to_owned(), if message.len() == 0 {
self.send(KICK(chanlist.to_owned(), nicklist.to_owned(), if message.is_empty() {
None
} else {
Some(message.to_owned())
@ -122,7 +122,7 @@ pub trait ServerExt: Server {
/// If `modeparmas` is an empty string, it won't be included in the message.
fn send_mode(&self, target: &str, mode: &str, modeparams: &str) -> Result<()>
where Self: Sized {
self.send(MODE(target.to_owned(), mode.to_owned(), if modeparams.len() == 0 {
self.send(MODE(target.to_owned(), mode.to_owned(), if modeparams.is_empty() {
None
} else {
Some(modeparams.to_owned())
@ -133,7 +133,7 @@ pub trait ServerExt: Server {
/// If `modeparams` is an empty string, it won't be included in the message.
fn send_samode(&self, target: &str, mode: &str, modeparams: &str) -> Result<()>
where Self: Sized {
self.send(SAMODE(target.to_owned(), mode.to_owned(), if modeparams.len() == 0 {
self.send(SAMODE(target.to_owned(), mode.to_owned(), if modeparams.is_empty() {
None
} else {
Some(modeparams.to_owned())
@ -153,7 +153,7 @@ pub trait ServerExt: Server {
/// Quits the server entirely with a message.
/// This defaults to `Powered by Rust.` if none is specified.
fn send_quit(&self, msg: &str) -> Result<()> where Self: Sized {
self.send(QUIT(Some(if msg.len() == 0 {
self.send(QUIT(Some(if msg.is_empty() {
"Powered by Rust.".to_owned()
} else {
msg.to_owned()