tokio-xmpp: clippy run

Maxime “pep” Buquet created

skip-changelog

Signed-off-by: Maxime “pep” Buquet <pep@bouah.net>

Change summary

tokio-xmpp/src/client/login.rs                   |  3 -
tokio-xmpp/src/client/mod.rs                     |  2 
tokio-xmpp/src/connect/dns.rs                    |  4 +-
tokio-xmpp/src/connect/starttls.rs               |  6 ++--
tokio-xmpp/src/event.rs                          |  7 +---
tokio-xmpp/src/stanzastream/connected.rs         | 20 ++++++---------
tokio-xmpp/src/stanzastream/mod.rs               |  2 
tokio-xmpp/src/stanzastream/negotiation.rs       | 23 +++++++----------
tokio-xmpp/src/stanzastream/queue.rs             |  4 +-
tokio-xmpp/src/stanzastream/stream_management.rs |  2 
tokio-xmpp/src/stanzastream/worker.rs            | 18 +++++--------
tokio-xmpp/src/xmlstream/capture.rs              |  9 +++---
tokio-xmpp/src/xmlstream/common.rs               | 21 +++++++---------
tokio-xmpp/src/xmlstream/mod.rs                  |  6 ++--
14 files changed, 54 insertions(+), 73 deletions(-)

Detailed changes

tokio-xmpp/src/client/login.rs 🔗

@@ -57,7 +57,7 @@ pub async fn auth<S: AsyncBufRead + AsyncWrite + Unpin>(
                         Nonza::Challenge(challenge) => {
                             let response = mechanism
                                 .response(&challenge.data)
-                                .map_err(|e| AuthError::Sasl(e))?;
+                                .map_err(AuthError::Sasl)?;
 
                             // Send response and loop
                             stream
@@ -110,7 +110,6 @@ pub async fn client_auth<C: ServerConnector>(
     timeouts: Timeouts,
 ) -> Result<(StreamFeatures, XmppStream<C::Stream>), Error> {
     let username = jid.node().unwrap().as_str();
-    let password = password;
 
     let (xmpp_stream, channel_binding) = server.connect(&jid, ns::JABBER_CLIENT, timeouts).await?;
     let (features, xmpp_stream) = xmpp_stream.recv_features().await?;

tokio-xmpp/src/client/mod.rs 🔗

@@ -137,7 +137,7 @@ impl Client {
     /// and yield events.
     pub fn new<J: Into<Jid>, P: Into<String>>(jid: J, password: P) -> Self {
         let jid = jid.into();
-        let dns_config = DnsConfig::srv(&jid.domain().to_string(), "_xmpp-client._tcp", 5222);
+        let dns_config = DnsConfig::srv(jid.domain().as_ref(), "_xmpp-client._tcp", 5222);
         Self::new_starttls(jid, password, dns_config, Timeouts::default())
     }
 

tokio-xmpp/src/connect/dns.rs 🔗

@@ -113,7 +113,7 @@ impl DnsConfig {
 
     #[cfg(feature = "dns")]
     async fn resolve_srv(host: &str, srv: &str, fallback_port: u16) -> Result<TcpStream, Error> {
-        let ascii_domain = idna::domain_to_ascii(&host)?;
+        let ascii_domain = idna::domain_to_ascii(host)?;
 
         if let Ok(ip) = ascii_domain.parse() {
             debug!("Attempting connection to {ip}:{fallback_port}");
@@ -148,7 +148,7 @@ impl DnsConfig {
 
     #[cfg(feature = "dns")]
     async fn resolve_no_srv(host: &str, port: u16) -> Result<TcpStream, Error> {
-        let ascii_domain = idna::domain_to_ascii(&host)?;
+        let ascii_domain = idna::domain_to_ascii(host)?;
 
         if let Ok(ip) = ascii_domain.parse() {
             return Ok(TcpStream::connect(&SocketAddr::new(ip, port)).await?);

tokio-xmpp/src/connect/starttls.rs 🔗

@@ -118,7 +118,7 @@ impl ServerConnector for StartTlsServerConnector {
                 channel_binding,
             ))
         } else {
-            Err(crate::Error::Protocol(ProtocolError::NoTls).into())
+            Err(crate::Error::Protocol(ProtocolError::NoTls))
         }
     }
 }
@@ -168,7 +168,7 @@ async fn get_tls_stream<S: AsyncRead + AsyncWrite + Unpin + AsRawFd>(
     let tls_stream = TlsConnector::from(Arc::new(config))
         .connect(domain, stream)
         .await
-        .map_err(|e| Error::from(crate::Error::Io(e)))?;
+        .map_err(crate::Error::Io)?;
 
     // Extract the channel-binding information before we hand the stream over to ktls.
     let (_, connection) = tls_stream.get_ref();
@@ -178,7 +178,7 @@ async fn get_tls_stream<S: AsyncRead + AsyncWrite + Unpin + AsRawFd>(
             let data = vec![0u8; 32];
             let data = connection
                 .export_keying_material(data, b"EXPORTER-Channel-Binding", None)
-                .map_err(|e| StartTlsError::Tls(e))?;
+                .map_err(StartTlsError::Tls)?;
             ChannelBinding::TlsExporter(data)
         }
         _ => ChannelBinding::None,

tokio-xmpp/src/event.rs 🔗

@@ -43,7 +43,7 @@ impl Stanza {
     pub fn ensure_id(&mut self) -> &str {
         match self {
             Self::Iq(iq) => {
-                if iq.id.len() == 0 {
+                if iq.id.is_empty() {
                     iq.id = make_id();
                 }
                 &iq.id
@@ -136,10 +136,7 @@ pub enum Event {
 impl Event {
     /// `Online` event?
     pub fn is_online(&self) -> bool {
-        match *self {
-            Event::Online { .. } => true,
-            _ => false,
-        }
+        matches!(&self, Event::Online { .. })
     }
 
     /// Get the server-assigned JID for the `Online` event

tokio-xmpp/src/stanzastream/connected.rs 🔗

@@ -214,10 +214,7 @@ impl ConnectedState {
         // from the peer when everything has been transmitted, which may be
         // longer than the stream timeout.
         ready!(Self::poll_write_sm_req(
-            match sm_state {
-                None => None,
-                Some(ref mut v) => Some(v),
-            },
+            sm_state.as_mut().map(|x| x as &mut SmState),
             stream.as_mut(),
             cx
         ))?;
@@ -558,7 +555,7 @@ impl ConnectedState {
                                         "Failed to process <sm:a/> sent by the server: {e}",
                                     );
                                     self.to_stream_error_state(e.into());
-                                    return Poll::Ready(None);
+                                    Poll::Ready(None)
                                 }
                             }
                         } else {
@@ -823,13 +820,12 @@ impl ConnectedState {
 
     pub fn queue_sm_request(&mut self) -> bool {
         match self {
-            Self::Ready { sm_state, .. } => {
-                if let Some(sm_state) = sm_state {
-                    sm_state.pending_req = true;
-                    true
-                } else {
-                    false
-                }
+            Self::Ready {
+                sm_state: Some(sm_state),
+                ..
+            } => {
+                sm_state.pending_req = true;
+                true
             }
             _ => false,
         }

tokio-xmpp/src/stanzastream/mod.rs 🔗

@@ -168,7 +168,7 @@ impl StanzaStream {
                                 // TODO: auth errors should probably be fatal??
                                 log::error!("Failed to connect: {}. Retrying in {:?}.", e, delay);
                                 tokio::time::sleep(delay).await;
-                                delay = delay * 2;
+                                delay *= 2;
                                 if delay > MAX_DELAY {
                                     delay = MAX_DELAY;
                                 }

tokio-xmpp/src/stanzastream/negotiation.rs 🔗

@@ -101,18 +101,15 @@ pub(super) enum NegotiationResult {
 
 impl NegotiationState {
     pub fn new(features: &StreamFeatures, sm_state: Option<SmState>) -> io::Result<Self> {
-        match sm_state {
-            Some(sm_state) => {
-                if features.stream_management.is_some() {
-                    return Ok(Self::SendSmRequest {
-                        sm_state: Some(sm_state),
-                        bound_jid: None,
-                    });
-                } else {
-                    log::warn!("Peer is not offering stream management anymore. Dropping state.");
-                }
+        if let Some(sm_state) = sm_state {
+            if features.stream_management.is_some() {
+                return Ok(Self::SendSmRequest {
+                    sm_state: Some(sm_state),
+                    bound_jid: None,
+                });
+            } else {
+                log::warn!("Peer is not offering stream management anymore. Dropping state.");
             }
-            None => (),
         }
 
         if !features.can_bind() {
@@ -247,7 +244,7 @@ impl NegotiationState {
 
                     Ok(XmppStreamElement::StreamError(error)) => {
                         log::debug!("Received stream:error, failing stream and discarding any stream management state.");
-                        let error = io::Error::new(io::ErrorKind::Other, error);
+                        let error = io::Error::other(error);
                         transmit_queue.fail(&(&error).into());
                         Poll::Ready(Break(NegotiationResult::Disconnect {
                             error,
@@ -472,7 +469,7 @@ impl NegotiationState {
 
                     Ok(XmppStreamElement::StreamError(error)) => {
                         log::debug!("Received stream error, failing stream and discarding any stream management state.");
-                        let error = io::Error::new(io::ErrorKind::Other, error);
+                        let error = io::Error::other(error);
                         transmit_queue.fail(&(&error).into());
                         Poll::Ready(Break(NegotiationResult::Disconnect {
                             error,

tokio-xmpp/src/stanzastream/queue.rs 🔗

@@ -224,7 +224,7 @@ pub(super) struct TransmitQueueRef<'x, T> {
     q: &'x mut VecDeque<T>,
 }
 
-impl<'x, T> TransmitQueueRef<'x, T> {
+impl<T> TransmitQueueRef<'_, T> {
     /// Take the item out of the queue.
     pub fn take(self) -> T {
         // Unwrap: when this type is created, a check is made that the queue
@@ -265,7 +265,7 @@ impl<T: Unpin> TransmitQueue<T> {
 
     /// Poll the queue for the next item to transmit.
     pub fn poll_next(&mut self, cx: &mut Context) -> Poll<Option<TransmitQueueRef<'_, T>>> {
-        if self.peek.len() > 0 {
+        if !self.peek.is_empty() {
             // Cannot use `if let Some(.) = .` here because of a borrowchecker
             // restriction. If the reference is created before the branch is
             // entered, it will think it needs to be borrowed until the end

tokio-xmpp/src/stanzastream/stream_management.rs 🔗

@@ -177,7 +177,7 @@ impl SmState {
         let to_drop = h.wrapping_sub(self.outbound_base) as usize;
         if to_drop > 0 {
             log::trace!("remote_acked: need to drop {to_drop} stanzas");
-            if to_drop as usize > self.unacked_stanzas.len() {
+            if to_drop > self.unacked_stanzas.len() {
                 if to_drop as u32 > u32::MAX / 2 {
                     // If we look at the stanza counter values as RFC 1982
                     // values, a wrapping difference greater than half the

tokio-xmpp/src/stanzastream/worker.rs 🔗

@@ -196,7 +196,7 @@ impl WorkerStream {
                     match ready!(substate.poll(
                         Pin::new(stream),
                         identity,
-                        &features,
+                        features,
                         transmit_queue,
                         cx
                     )) {
@@ -205,13 +205,9 @@ impl WorkerStream {
 
                         // produced an event to emit.
                         Some(ConnectedEvent::Worker(v)) => {
-                            match v {
-                                // Capture the JID from a stream reset to
-                                // update our state.
-                                WorkerEvent::Reset { ref bound_jid, .. } => {
-                                    *identity = bound_jid.clone();
-                                }
-                                _ => (),
+                            // Capture the JID from a stream reset to update our state.
+                            if let WorkerEvent::Reset { ref bound_jid, .. } = v {
+                                *identity = bound_jid.clone();
                             }
                             return Poll::Ready(Some(v));
                         }
@@ -364,7 +360,7 @@ struct DriveDuplex<'x> {
     queue: &'x mut TransmitQueue<QueueEntry>,
 }
 
-impl<'x> Future for DriveDuplex<'x> {
+impl Future for DriveDuplex<'_> {
     type Output = Option<WorkerEvent>;
 
     fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
@@ -378,7 +374,7 @@ struct DriveWrites<'x> {
     queue: &'x mut TransmitQueue<QueueEntry>,
 }
 
-impl<'x> Future for DriveWrites<'x> {
+impl Future for DriveWrites<'_> {
     type Output = Never;
 
     fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {
@@ -391,7 +387,7 @@ struct Close<'x> {
     stream: Pin<&'x mut WorkerStream>,
 }
 
-impl<'x> Future for Close<'x> {
+impl Future for Close<'_> {
     type Output = io::Result<()>;
 
     fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {

tokio-xmpp/src/xmlstream/capture.rs 🔗

@@ -127,7 +127,7 @@ impl<T: AsyncBufRead> AsyncBufRead for CaptureBufRead<T> {
         this.inner.consume(amt);
         if let Some((_, consumed_up_to)) = this.buf.as_mut() {
             // Increase the amount of data to preserve.
-            *consumed_up_to = *consumed_up_to + amt;
+            *consumed_up_to += amt;
         }
     }
 }
@@ -186,12 +186,11 @@ pub(super) fn log_recv(err: Option<&xmpp_parsers::Error>, capture: Option<Vec<u8
                 log::trace!("RECV (error: {}) [data capture disabled]", err);
             }
         },
-        None => match capture {
-            Some(capture) => {
+        None => {
+            if let Some(capture) = capture {
                 log::trace!("RECV (ok) {}", LogXsoBuf(&capture));
             }
-            None => (),
-        },
+        }
     }
 }
 

tokio-xmpp/src/xmlstream/common.rs 🔗

@@ -152,7 +152,7 @@ impl TimeoutState {
         self.level = TimeoutLevel::Soft;
         self.deadline
             .as_mut()
-            .reset((Instant::now() + self.timeouts.data_to_soft()).into());
+            .reset(Instant::now() + self.timeouts.data_to_soft());
     }
 }
 
@@ -380,10 +380,10 @@ impl<Io: AsyncBufRead> Stream for RawXmlStream<Io> {
     }
 }
 
-impl<'x, Io: AsyncWrite> RawXmlStreamProj<'x, Io> {
+impl<Io: AsyncWrite> RawXmlStreamProj<'_, Io> {
     fn flush_tx_log(&mut self) {
         let range = &self.tx_buffer[*self.tx_buffer_logged..];
-        if range.len() == 0 {
+        if range.is_empty() {
             return;
         }
         log_send(range);
@@ -413,12 +413,12 @@ impl<'x, Io: AsyncWrite> RawXmlStreamProj<'x, Io> {
 
     fn progress_write(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
         self.flush_tx_log();
-        while self.tx_buffer.len() > 0 {
+        while !self.tx_buffer.is_empty() {
             let written = match ready!(self
                 .parser
                 .as_mut()
                 .inner_pinned()
-                .poll_write(cx, &self.tx_buffer))
+                .poll_write(cx, self.tx_buffer))
             {
                 Ok(v) => v,
                 Err(e) => return Poll::Ready(Err(e)),
@@ -461,7 +461,7 @@ impl<'x, Io: AsyncWrite> Sink<xso::Item<'x>> for RawXmlStream<Io> {
             // Some progress and it went fine, move on.
             Poll::Ready(Ok(())) => (),
             // Something went wrong -> return the error.
-            Poll::Ready(Err(e)) => return Poll::Ready(Err(e.into())),
+            Poll::Ready(Err(e)) => return Poll::Ready(Err(e)),
         }
         if this.tx_buffer.len() < *this.tx_buffer_high_water_mark {
             Poll::Ready(Ok(()))
@@ -608,10 +608,7 @@ impl<T: FromXml> ReadXsoState<T> {
             // whitespace keepalives.
             // (And also, we'll know faster when the remote side sends
             // non-whitespace garbage.)
-            let text_buffering = match self {
-                ReadXsoState::PreData => false,
-                _ => true,
-            };
+            let text_buffering = !matches!(self, ReadXsoState::PreData);
             source
                 .as_mut()
                 .parser_pinned()
@@ -745,7 +742,7 @@ impl<'x, Io: AsyncBufRead, T: FromXml> ReadXso<'x, Io, T> {
     }
 }
 
-impl<'x, Io: AsyncBufRead, T: FromXml> Future for ReadXso<'x, Io, T>
+impl<Io: AsyncBufRead, T: FromXml> Future for ReadXso<'_, Io, T>
 where
     T::Builder: Unpin,
 {
@@ -770,7 +767,7 @@ pub struct StreamHeader<'x> {
     pub id: Option<Cow<'x, str>>,
 }
 
-impl<'x> StreamHeader<'x> {
+impl StreamHeader<'_> {
     /// Take the contents and return them as new object.
     ///
     /// `self` will be left with all its parts set to `None`.

tokio-xmpp/src/xmlstream/mod.rs 🔗

@@ -111,10 +111,10 @@ fn highlight_xml(xml: &str) -> String {
 
 struct LogXsoBuf<'x>(&'x [u8]);
 
-impl<'x> fmt::Display for LogXsoBuf<'x> {
+impl fmt::Display for LogXsoBuf<'_> {
     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
         // We always generate UTF-8, so this should be good... I think.
-        let text = core::str::from_utf8(&self.0).unwrap();
+        let text = core::str::from_utf8(self.0).unwrap();
         #[cfg(feature = "syntax-highlighting")]
         let text = highlight_xml(text);
         f.write_str(&text)
@@ -493,7 +493,7 @@ pub struct Shutdown<'a, Io: AsyncWrite, T: FromXml + AsXml> {
     stream: Pin<&'a mut XmlStream<Io, T>>,
 }
 
-impl<'a, Io: AsyncWrite, T: FromXml + AsXml> Future for Shutdown<'a, Io, T> {
+impl<Io: AsyncWrite, T: FromXml + AsXml> Future for Shutdown<'_, Io, T> {
     type Output = io::Result<()>;
 
     fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {