Cleaned up a bunch of code with clippy.

This commit is contained in:
Aaron Weiss 2018-01-01 22:25:25 -05:00
parent 68666aef09
commit a0d0d3e249
No known key found for this signature in database
GPG key ID: 047D32DF25DC22EF
12 changed files with 73 additions and 75 deletions

View file

@ -9,8 +9,8 @@ use args::{Args, ArgsError};
use getopts::Occur; use getopts::Occur;
use irc::client::data::Config; use irc::client::data::Config;
const PROGRAM_DESC: &'static str = "Use this program to convert configs between {JSON, TOML, YAML}."; const PROGRAM_DESC: &str = "Use this program to convert configs between {JSON, TOML, YAML}.";
const PROGRAM_NAME: &'static str = "convertconf"; const PROGRAM_NAME: &str = "convertconf";
fn main() { fn main() {
let args: Vec<_> = env::args().collect(); let args: Vec<_> = env::args().collect();
@ -31,7 +31,7 @@ fn main() {
} }
} }
fn parse(input: &Vec<String>) -> Result<Option<(String, String)>, ArgsError> { fn parse(input: &[String]) -> Result<Option<(String, String)>, ArgsError> {
let mut args = Args::new(PROGRAM_NAME, PROGRAM_DESC); let mut args = Args::new(PROGRAM_NAME, PROGRAM_DESC);
args.flag("h", "help", "Print the usage menu"); args.flag("h", "help", "Print the usage menu");
args.option("i", args.option("i",

View file

@ -23,7 +23,7 @@ fn main() {
match message.command { match message.command {
Command::PRIVMSG(ref target, ref msg) => { Command::PRIVMSG(ref target, ref msg) => {
if msg.starts_with(server.current_nickname()) { if msg.starts_with(server.current_nickname()) {
let tokens: Vec<_> = msg.split(" ").collect(); let tokens: Vec<_> = msg.split(' ').collect();
if tokens.len() > 2 { if tokens.len() > 2 {
let n = tokens[0].len() + tokens[1].len() + 2; let n = tokens[0].len() + tokens[1].len() + 2;
if let Ok(count) = tokens[1].parse::<u8>() { if let Ok(count) = tokens[1].parse::<u8>() {

View file

@ -42,7 +42,7 @@ impl fmt::Debug for Connection {
} }
} }
/// A convenient type alias representing the TlsStream future. /// A convenient type alias representing the `TlsStream` future.
type TlsFuture = Box<Future<Error = error::Error, Item = TlsStream<TcpStream>> + Send>; type TlsFuture = Box<Future<Error = error::Error, Item = TlsStream<TcpStream>> + Send>;
/// A future representing an eventual `Connection`. /// A future representing an eventual `Connection`.
@ -60,30 +60,30 @@ impl<'a> Future for ConnectionFuture<'a> {
type Error = error::Error; type Error = error::Error;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> { fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
match self { match *self {
&mut ConnectionFuture::Unsecured(ref config, ref mut inner) => { ConnectionFuture::Unsecured(ref config, ref mut inner) => {
let framed = try_ready!(inner.poll()).framed(IrcCodec::new(config.encoding())?); let framed = try_ready!(inner.poll()).framed(IrcCodec::new(config.encoding())?);
let transport = IrcTransport::new(config, framed); let transport = IrcTransport::new(config, framed);
Ok(Async::Ready(Connection::Unsecured(transport))) Ok(Async::Ready(Connection::Unsecured(transport)))
} }
&mut ConnectionFuture::Secured(ref config, ref mut inner) => { ConnectionFuture::Secured(ref config, ref mut inner) => {
let framed = try_ready!(inner.poll()).framed(IrcCodec::new(config.encoding())?); let framed = try_ready!(inner.poll()).framed(IrcCodec::new(config.encoding())?);
let transport = IrcTransport::new(config, framed); let transport = IrcTransport::new(config, framed);
Ok(Async::Ready(Connection::Secured(transport))) Ok(Async::Ready(Connection::Secured(transport)))
} }
&mut ConnectionFuture::Mock(ref config) => { ConnectionFuture::Mock(ref config) => {
let enc: error::Result<_> = encoding_from_whatwg_label(config.encoding()).ok_or( let enc: error::Result<_> = encoding_from_whatwg_label(
io::Error::new( config.encoding()
io::ErrorKind::InvalidInput, ).ok_or_else(|| io::Error::new(
&format!("Attempted to use unknown codec {}.", config.encoding())[..], io::ErrorKind::InvalidInput,
).into(), &format!("Attempted to use unknown codec {}.", config.encoding())[..],
); ).into());
let encoding = enc?; let encoding = enc?;
let init_str = config.mock_initial_value(); let init_str = config.mock_initial_value();
let initial: error::Result<_> = { let initial: error::Result<_> = {
encoding.encode(&init_str, EncoderTrap::Replace).map_err( encoding.encode(init_str, EncoderTrap::Replace).map_err(
|data| { |data| {
io::Error::new( io::Error::new(
io::ErrorKind::InvalidInput, io::ErrorKind::InvalidInput,
@ -144,8 +144,8 @@ impl Connection {
/// Gets a view of the internal logging if and only if this connection is using a mock stream. /// Gets a view of the internal logging if and only if this connection is using a mock stream.
/// Otherwise, this will always return `None`. This is used for unit testing. /// Otherwise, this will always return `None`. This is used for unit testing.
pub fn log_view(&self) -> Option<LogView> { pub fn log_view(&self) -> Option<LogView> {
match self { match *self {
&Connection::Mock(ref inner) => Some(inner.view()), Connection::Mock(ref inner) => Some(inner.view()),
_ => None, _ => None,
} }
} }
@ -156,10 +156,10 @@ impl Stream for Connection {
type Error = error::Error; type Error = error::Error;
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> { fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
match self { match *self {
&mut Connection::Unsecured(ref mut inner) => inner.poll(), Connection::Unsecured(ref mut inner) => inner.poll(),
&mut Connection::Secured(ref mut inner) => inner.poll(), Connection::Secured(ref mut inner) => inner.poll(),
&mut Connection::Mock(ref mut inner) => inner.poll(), Connection::Mock(ref mut inner) => inner.poll(),
} }
} }
} }
@ -169,18 +169,18 @@ impl Sink for Connection {
type SinkError = error::Error; type SinkError = error::Error;
fn start_send(&mut self, item: Self::SinkItem) -> StartSend<Self::SinkItem, Self::SinkError> { fn start_send(&mut self, item: Self::SinkItem) -> StartSend<Self::SinkItem, Self::SinkError> {
match self { match *self {
&mut Connection::Unsecured(ref mut inner) => inner.start_send(item), Connection::Unsecured(ref mut inner) => inner.start_send(item),
&mut Connection::Secured(ref mut inner) => inner.start_send(item), Connection::Secured(ref mut inner) => inner.start_send(item),
&mut Connection::Mock(ref mut inner) => inner.start_send(item), Connection::Mock(ref mut inner) => inner.start_send(item),
} }
} }
fn poll_complete(&mut self) -> Poll<(), Self::SinkError> { fn poll_complete(&mut self) -> Poll<(), Self::SinkError> {
match self { match *self {
&mut Connection::Unsecured(ref mut inner) => inner.poll_complete(), Connection::Unsecured(ref mut inner) => inner.poll_complete(),
&mut Connection::Secured(ref mut inner) => inner.poll_complete(), Connection::Secured(ref mut inner) => inner.poll_complete(),
&mut Connection::Mock(ref mut inner) => inner.poll_complete(), Connection::Mock(ref mut inner) => inner.poll_complete(),
} }
} }
} }

View file

@ -103,11 +103,11 @@ impl Config {
Some("json") => Config::load_json(&data), Some("json") => Config::load_json(&data),
Some("toml") => Config::load_toml(&data), Some("toml") => Config::load_toml(&data),
Some("yaml") | Some("yml") => Config::load_yaml(&data), Some("yaml") | Some("yml") => Config::load_yaml(&data),
Some(ext) => return Err(Error::new( Some(ext) => Err(Error::new(
ErrorKind::InvalidInput, ErrorKind::InvalidInput,
format!("Failed to decode configuration of unknown format {}", ext), format!("Failed to decode configuration of unknown format {}", ext),
).into()), ).into()),
None => return Err(Error::new( None => Err(Error::new(
ErrorKind::InvalidInput, ErrorKind::InvalidInput,
"Failed to decode configuration of missing or non-unicode format.", "Failed to decode configuration of missing or non-unicode format.",
).into()), ).into()),

View file

@ -80,17 +80,17 @@ impl User {
/// Updates the user's access level. /// Updates the user's access level.
pub fn update_access_level(&mut self, mode: &Mode<ChannelMode>) { pub fn update_access_level(&mut self, mode: &Mode<ChannelMode>) {
match mode { match *mode {
&Mode::Plus(ChannelMode::Founder, _) => self.add_access_level(AccessLevel::Owner), Mode::Plus(ChannelMode::Founder, _) => self.add_access_level(AccessLevel::Owner),
&Mode::Minus(ChannelMode::Founder, _) => self.sub_access_level(AccessLevel::Owner), Mode::Minus(ChannelMode::Founder, _) => self.sub_access_level(AccessLevel::Owner),
&Mode::Plus(ChannelMode::Admin, _) => self.add_access_level(AccessLevel::Admin), Mode::Plus(ChannelMode::Admin, _) => self.add_access_level(AccessLevel::Admin),
&Mode::Minus(ChannelMode::Admin, _) => self.sub_access_level(AccessLevel::Admin), Mode::Minus(ChannelMode::Admin, _) => self.sub_access_level(AccessLevel::Admin),
&Mode::Plus(ChannelMode::Oper, _) => self.add_access_level(AccessLevel::Oper), Mode::Plus(ChannelMode::Oper, _) => self.add_access_level(AccessLevel::Oper),
&Mode::Minus(ChannelMode::Oper, _) => self.sub_access_level(AccessLevel::Oper), Mode::Minus(ChannelMode::Oper, _) => self.sub_access_level(AccessLevel::Oper),
&Mode::Plus(ChannelMode::Halfop, _) => self.add_access_level(AccessLevel::HalfOp), Mode::Plus(ChannelMode::Halfop, _) => self.add_access_level(AccessLevel::HalfOp),
&Mode::Minus(ChannelMode::Halfop, _) => self.sub_access_level(AccessLevel::HalfOp), Mode::Minus(ChannelMode::Halfop, _) => self.sub_access_level(AccessLevel::HalfOp),
&Mode::Plus(ChannelMode::Voice, _) => self.add_access_level(AccessLevel::Voice), Mode::Plus(ChannelMode::Voice, _) => self.add_access_level(AccessLevel::Voice),
&Mode::Minus(ChannelMode::Voice, _) => self.sub_access_level(AccessLevel::Voice), Mode::Minus(ChannelMode::Voice, _) => self.sub_access_level(AccessLevel::Voice),
_ => {} _ => {}
} }
} }

View file

@ -247,7 +247,7 @@ impl<'a> Server for ServerState {
Self: Sized, Self: Sized,
{ {
let msg = &msg.into(); let msg = &msg.into();
self.handle_sent_message(&msg)?; self.handle_sent_message(msg)?;
Ok((&self.outgoing).unbounded_send( Ok((&self.outgoing).unbounded_send(
ServerState::sanitize(&msg.to_string()) ServerState::sanitize(&msg.to_string())
.into(), .into(),
@ -365,9 +365,9 @@ impl ServerState {
body[1..end].split(' ').collect() body[1..end].split(' ').collect()
}; };
if target.starts_with('#') { if target.starts_with('#') {
self.handle_ctcp(target, tokens)? self.handle_ctcp(target, &tokens)?
} else if let Some(user) = msg.source_nickname() { } else if let Some(user) = msg.source_nickname() {
self.handle_ctcp(user, tokens)? self.handle_ctcp(user, &tokens)?
} }
} }
} }
@ -510,8 +510,8 @@ impl ServerState {
#[cfg(not(feature = "nochanlists"))] #[cfg(not(feature = "nochanlists"))]
fn handle_mode(&self, chan: &str, modes: &[Mode<ChannelMode>]) { fn handle_mode(&self, chan: &str, modes: &[Mode<ChannelMode>]) {
for mode in modes { for mode in modes {
match mode { match *mode {
&Mode::Plus(_, Some(ref user)) | &Mode::Minus(_, Some(ref user)) => { Mode::Plus(_, Some(ref user)) | Mode::Minus(_, Some(ref user)) => {
if let Some(vec) = self.chanlists.lock().unwrap().get_mut(chan) { if let Some(vec) = self.chanlists.lock().unwrap().get_mut(chan) {
if let Some(n) = vec.iter().position(|x| x.get_nickname() == user) { if let Some(n) = vec.iter().position(|x| x.get_nickname() == user) {
vec[n].update_access_level(mode) vec[n].update_access_level(mode)
@ -543,7 +543,7 @@ impl ServerState {
} }
#[cfg(feature = "ctcp")] #[cfg(feature = "ctcp")]
fn handle_ctcp(&self, resp: &str, tokens: Vec<&str>) -> error::Result<()> { fn handle_ctcp(&self, resp: &str, tokens: &[&str]) -> error::Result<()> {
if tokens.is_empty() { if tokens.is_empty() {
return Ok(()); return Ok(());
} }
@ -616,7 +616,7 @@ impl Server for IrcServer {
fn stream(&self) -> ServerStream { fn stream(&self) -> ServerStream {
ServerStream { ServerStream {
state: self.state.clone(), state: Arc::clone(&self.state),
stream: self.state.incoming.lock().unwrap().take().expect( stream: self.state.incoming.lock().unwrap().take().expect(
"Stream was already obtained once, and cannot be reobtained." "Stream was already obtained once, and cannot be reobtained."
), ),
@ -766,11 +766,11 @@ impl IrcServer {
/// # } /// # }
/// # fn process_msg(server: &IrcServer, message: Message) -> error::Result<()> { Ok(()) } /// # fn process_msg(server: &IrcServer, message: Message) -> error::Result<()> { Ok(()) }
/// ``` /// ```
pub fn new_future<'a>(handle: Handle, config: &'a Config) -> error::Result<IrcServerFuture<'a>> { pub fn new_future(handle: Handle, config: &Config) -> error::Result<IrcServerFuture> {
let (tx_outgoing, rx_outgoing) = mpsc::unbounded(); let (tx_outgoing, rx_outgoing) = mpsc::unbounded();
Ok(IrcServerFuture { Ok(IrcServerFuture {
conn: Connection::new(&config, &handle)?, conn: Connection::new(config, &handle)?,
handle: handle, handle: handle,
config: config, config: config,
tx_outgoing: Some(tx_outgoing), tx_outgoing: Some(tx_outgoing),

View file

@ -126,7 +126,7 @@ where
// Check PONG responses from the server. // Check PONG responses from the server.
Command::PONG(ref data, None) | Command::PONG(ref data, None) |
Command::PONG(_, Some(ref data)) => { Command::PONG(_, Some(ref data)) => {
if self.last_ping_data == &data[..] { if self.last_ping_data == data[..] {
self.last_pong_received = Instant::now(); self.last_pong_received = Instant::now();
} }
} }

View file

@ -8,10 +8,10 @@ pub trait ChannelExt {
impl<'a> ChannelExt for &'a str { impl<'a> ChannelExt for &'a str {
fn is_channel_name(&self) -> bool { fn is_channel_name(&self) -> bool {
self.starts_with("#") || self.starts_with('#') ||
self.starts_with("&") || self.starts_with('&') ||
self.starts_with("+") || self.starts_with('+') ||
self.starts_with("!") self.starts_with('!')
} }
} }

View file

@ -24,7 +24,7 @@ impl Decoder for IrcCodec {
fn decode(&mut self, src: &mut BytesMut) -> error::Result<Option<Message>> { fn decode(&mut self, src: &mut BytesMut) -> error::Result<Option<Message>> {
self.inner.decode(src).and_then(|res| { self.inner.decode(src).and_then(|res| {
res.map_or(Ok(None), |msg| msg.parse::<Message>().map(|msg| Some(msg))) res.map_or(Ok(None), |msg| msg.parse::<Message>().map(Some))
}) })
} }
} }

View file

@ -19,12 +19,10 @@ impl LineCodec {
pub fn new(label: &str) -> error::Result<LineCodec> { pub fn new(label: &str) -> error::Result<LineCodec> {
encoding_from_whatwg_label(label) encoding_from_whatwg_label(label)
.map(|enc| LineCodec { encoding: enc }) .map(|enc| LineCodec { encoding: enc })
.ok_or( .ok_or_else(|| io::Error::new(
io::Error::new( io::ErrorKind::InvalidInput,
io::ErrorKind::InvalidInput, &format!("Attempted to use unknown codec {}.", label)[..],
&format!("Attempted to use unknown codec {}.", label)[..], ).into())
).into(),
)
} }
} }

View file

@ -202,9 +202,9 @@ impl FromStr for Message {
}; };
let line_ending_len = if state.ends_with("\r\n") { let line_ending_len = if state.ends_with("\r\n") {
"\r\n" "\r\n"
} else if state.ends_with("\r") { } else if state.ends_with('\r') {
"\r" "\r"
} else if state.ends_with("\n") { } else if state.ends_with('\n') {
"\n" "\n"
} else { } else {
"" ""

View file

@ -224,11 +224,11 @@ where
T: ModeType, T: ModeType,
{ {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self { match *self {
&Mode::Plus(ref mode, Some(ref arg)) => write!(f, "{}{} {}", "+", mode, arg), Mode::Plus(ref mode, Some(ref arg)) => write!(f, "{}{} {}", "+", mode, arg),
&Mode::Minus(ref mode, Some(ref arg)) => write!(f, "{}{} {}", "-", mode, arg), Mode::Minus(ref mode, Some(ref arg)) => write!(f, "{}{} {}", "-", mode, arg),
&Mode::Plus(ref mode, None) => write!(f, "{}{}", "+", mode), Mode::Plus(ref mode, None) => write!(f, "{}{}", "+", mode),
&Mode::Minus(ref mode, None) => write!(f, "{}{}", "-", mode), Mode::Minus(ref mode, None) => write!(f, "{}{}", "-", mode),
} }
} }
} }
@ -246,9 +246,9 @@ impl Mode<UserMode> {
use self::PlusMinus::*; use self::PlusMinus::*;
let mut res = vec![]; let mut res = vec![];
let mut pieces = s.split(" "); let mut pieces = s.split(' ');
for term in pieces.clone() { for term in pieces.clone() {
if term.starts_with("+") || term.starts_with("-") { if term.starts_with('+') || term.starts_with('-') {
let _ = pieces.next(); let _ = pieces.next();
let mut chars = term.chars(); let mut chars = term.chars();
@ -285,9 +285,9 @@ impl Mode<ChannelMode> {
use self::PlusMinus::*; use self::PlusMinus::*;
let mut res = vec![]; let mut res = vec![];
let mut pieces = s.split(" "); let mut pieces = s.split(' ');
for term in pieces.clone() { for term in pieces.clone() {
if term.starts_with("+") || term.starts_with("-") { if term.starts_with('+') || term.starts_with('-') {
let _ = pieces.next(); let _ = pieces.next();
let mut chars = term.chars(); let mut chars = term.chars();