tokio-xmpp: clippy run

skip-changelog

Signed-off-by: Maxime “pep” Buquet <pep@bouah.net>
This commit is contained in:
Maxime “pep” Buquet 2025-04-07 22:57:33 +02:00
commit 23c947d081
14 changed files with 54 additions and 73 deletions

View file

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

View file

@ -137,7 +137,7 @@ impl Client {
/// and yield events. /// and yield events.
pub fn new<J: Into<Jid>, P: Into<String>>(jid: J, password: P) -> Self { pub fn new<J: Into<Jid>, P: Into<String>>(jid: J, password: P) -> Self {
let jid = jid.into(); 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()) Self::new_starttls(jid, password, dns_config, Timeouts::default())
} }

View file

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

View file

@ -118,7 +118,7 @@ impl ServerConnector for StartTlsServerConnector {
channel_binding, channel_binding,
)) ))
} else { } 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)) let tls_stream = TlsConnector::from(Arc::new(config))
.connect(domain, stream) .connect(domain, stream)
.await .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. // Extract the channel-binding information before we hand the stream over to ktls.
let (_, connection) = tls_stream.get_ref(); 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 = vec![0u8; 32];
let data = connection let data = connection
.export_keying_material(data, b"EXPORTER-Channel-Binding", None) .export_keying_material(data, b"EXPORTER-Channel-Binding", None)
.map_err(|e| StartTlsError::Tls(e))?; .map_err(StartTlsError::Tls)?;
ChannelBinding::TlsExporter(data) ChannelBinding::TlsExporter(data)
} }
_ => ChannelBinding::None, _ => ChannelBinding::None,

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -127,7 +127,7 @@ impl<T: AsyncBufRead> AsyncBufRead for CaptureBufRead<T> {
this.inner.consume(amt); this.inner.consume(amt);
if let Some((_, consumed_up_to)) = this.buf.as_mut() { if let Some((_, consumed_up_to)) = this.buf.as_mut() {
// Increase the amount of data to preserve. // 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); log::trace!("RECV (error: {}) [data capture disabled]", err);
} }
}, },
None => match capture { None => {
Some(capture) => { if let Some(capture) = capture {
log::trace!("RECV (ok) {}", LogXsoBuf(&capture)); log::trace!("RECV (ok) {}", LogXsoBuf(&capture));
} }
None => (), }
},
} }
} }

View file

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

View file

@ -111,10 +111,10 @@ fn highlight_xml(xml: &str) -> String {
struct LogXsoBuf<'x>(&'x [u8]); 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 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// We always generate UTF-8, so this should be good... I think. // 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")] #[cfg(feature = "syntax-highlighting")]
let text = highlight_xml(text); let text = highlight_xml(text);
f.write_str(&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>>, 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<()>; type Output = io::Result<()>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> { fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Self::Output> {