Skip to content

Commit

Permalink
Merge pull request #174 from Totodore/fix-clippy-lints
Browse files Browse the repository at this point in the history
fix(clippy): fix clippy lints
  • Loading branch information
Totodore authored Nov 22, 2023
2 parents c0e2b22 + b2800a8 commit c03303a
Show file tree
Hide file tree
Showing 10 changed files with 49 additions and 58 deletions.
10 changes: 5 additions & 5 deletions engineioxide/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
//! let svc = EngineIoService::with_config(MyHandler, config);
//! ```
use std::time::Duration;
use std::{borrow::Cow, time::Duration};

use crate::service::TransportType;

Expand All @@ -38,7 +38,7 @@ use crate::service::TransportType;
pub struct EngineIoConfig {
/// The path to listen for engine.io requests on.
/// Defaults to "/engine.io".
pub req_path: String,
pub req_path: Cow<'static, str>,

/// The interval at which the server will send a ping packet to the client.
/// Defaults to 25 seconds.
Expand Down Expand Up @@ -67,7 +67,7 @@ pub struct EngineIoConfig {
impl Default for EngineIoConfig {
fn default() -> Self {
Self {
req_path: "/engine.io".to_string(),
req_path: "/engine.io".into(),
ping_interval: Duration::from_millis(25000),
ping_timeout: Duration::from_millis(20000),
max_buffer_size: 128,
Expand Down Expand Up @@ -105,8 +105,8 @@ impl EngineIoConfigBuilder {

/// The path to listen for engine.io requests on.
/// Defaults to "/engine.io".
pub fn req_path(mut self, req_path: String) -> Self {
self.config.req_path = req_path;
pub fn req_path(mut self, req_path: impl Into<Cow<'static, str>>) -> Self {
self.config.req_path = req_path.into();
self
}

Expand Down
3 changes: 0 additions & 3 deletions engineioxide/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
#![cfg_attr(docsrs, feature(doc_cfg))]
#![warn(
clippy::future_not_send,
clippy::all,
clippy::todo,
clippy::empty_enum,
clippy::enum_glob_use,
clippy::mem_forget,
clippy::unused_self,
clippy::filter_map_next,
Expand All @@ -27,7 +25,6 @@
clippy::option_option,
clippy::verbose_file_reads,
clippy::unnested_or_patterns,
clippy::str_to_string,
rust_2018_idioms,
future_incompatible,
nonstandard_style,
Expand Down
6 changes: 4 additions & 2 deletions engineioxide/src/service/hyper_v1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,8 @@ where
}

fn call(&mut self, req: Request<ReqBody>) -> Self::Future {
if req.uri().path().starts_with(&self.0.engine.config.req_path) {
let path = self.0.engine.config.req_path.as_ref();
if req.uri().path().starts_with(path) {
let req = req.map(IncomingBody::new);
dispatch_req(
req,
Expand All @@ -108,7 +109,8 @@ where
type Future = ResponseFuture<S::Future, ResBody>;

fn call(&self, req: Request<Incoming>) -> Self::Future {
if req.uri().path().starts_with(&self.0.engine.config.req_path) {
let path = self.0.engine.config.req_path.as_ref();
if req.uri().path().starts_with(path) {
let req = req.map(IncomingBody::new);
dispatch_req(
req,
Expand Down
3 changes: 2 additions & 1 deletion engineioxide/src/service/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,8 @@ where
}

fn call(&mut self, req: Request<ReqBody>) -> Self::Future {
if req.uri().path().starts_with(&self.engine.config.req_path) {
let path = self.engine.config.req_path.as_ref();
if req.uri().path().starts_with(path) {
dispatch_req(
req,
self.engine.clone(),
Expand Down
4 changes: 2 additions & 2 deletions engineioxide/src/transport/polling/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -159,15 +159,15 @@ where
engine.close_session(sid, DisconnectReason::TransportClose);
break;
}
Ok(Packet::Pong) | Ok(Packet::Ping) => socket
Ok(Packet::Pong | Packet::Ping) => socket
.heartbeat_tx
.try_send(())
.map_err(|_| Error::HeartbeatTimeout),
Ok(Packet::Message(msg)) => {
engine.handler.on_message(msg, socket.clone());
Ok(())
}
Ok(Packet::Binary(bin)) | Ok(Packet::BinaryV3(bin)) => {
Ok(Packet::Binary(bin) | Packet::BinaryV3(bin)) => {
engine.handler.on_binary(bin, socket.clone());
Ok(())
}
Expand Down
64 changes: 30 additions & 34 deletions socketioxide/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,28 +33,6 @@ impl<A: Adapter> Client<A> {
}
}

/// Applies an incoming binary payload to a partial binary packet waiting to be filled with all the payloads
///
/// Returns true if the packet is complete and should be processed
fn apply_payload_on_packet(&self, data: Vec<u8>, socket: &EIoSocket<SocketData>) -> bool {
#[cfg(feature = "tracing")]
tracing::debug!("[sid={}] applying payload on packet", socket.id);
if let Some(ref mut packet) = *socket.data.partial_bin_packet.lock().unwrap() {
match packet.inner {
PacketData::BinaryEvent(_, ref mut bin, _)
| PacketData::BinaryAck(ref mut bin, _) => {
bin.add_payload(data);
bin.is_complete()
}
_ => unreachable!("partial_bin_packet should only be set for binary packets"),
}
} else {
#[cfg(feature = "tracing")]
tracing::debug!("[sid={}] socket received unexpected bin data", socket.id);
false
}
}

/// Called when a socket connects to a new namespace
fn sock_connect(
&self,
Expand Down Expand Up @@ -92,16 +70,6 @@ impl<A: Adapter> Client<A> {
}
}

/// Cache-in the socket data until all the binary payloads are received
fn sock_recv_bin_packet(&self, socket: &EIoSocket<SocketData>, packet: Packet<'static>) {
socket
.data
.partial_bin_packet
.lock()
.unwrap()
.replace(packet);
}

/// Propagate a packet to a its target namespace
fn sock_propagate_packet(&self, packet: Packet<'_>, sid: Sid) -> Result<(), Error> {
if let Some(ns) = self.get_ns(&packet.ns) {
Expand Down Expand Up @@ -243,7 +211,13 @@ impl<A: Adapter> EngineIoHandler for Client<A> {
.sock_connect(auth, &packet.ns, &socket)
.map_err(Into::into),
PacketData::BinaryEvent(_, _, _) | PacketData::BinaryAck(_, _) => {
self.sock_recv_bin_packet(&socket, packet);
// Cache-in the socket data until all the binary payloads are received
socket
.data
.partial_bin_packet
.lock()
.unwrap()
.replace(packet);
Ok(())
}
_ => self.sock_propagate_packet(packet, socket.id),
Expand All @@ -265,7 +239,7 @@ impl<A: Adapter> EngineIoHandler for Client<A> {
///
/// If the packet is complete, it is propagated to the namespace
fn on_binary(&self, data: Vec<u8>, socket: Arc<EIoSocket<SocketData>>) {
if self.apply_payload_on_packet(data, &socket) {
if apply_payload_on_packet(data, &socket) {
if let Some(packet) = socket.data.partial_bin_packet.lock().unwrap().take() {
if let Err(ref err) = self.sock_propagate_packet(packet, socket.id) {
#[cfg(feature = "tracing")]
Expand All @@ -282,3 +256,25 @@ impl<A: Adapter> EngineIoHandler for Client<A> {
}
}
}

/// Utility that applies an incoming binary payload to a partial binary packet
/// waiting to be filled with all the payloads
///
/// Returns true if the packet is complete and should be processed
fn apply_payload_on_packet(data: Vec<u8>, socket: &EIoSocket<SocketData>) -> bool {
#[cfg(feature = "tracing")]
tracing::debug!("[sid={}] applying payload on packet", socket.id);
if let Some(ref mut packet) = *socket.data.partial_bin_packet.lock().unwrap() {
match packet.inner {
PacketData::BinaryEvent(_, ref mut bin, _) | PacketData::BinaryAck(ref mut bin, _) => {
bin.add_payload(data);
bin.is_complete()
}
_ => unreachable!("partial_bin_packet should only be set for binary packets"),
}
} else {
#[cfg(feature = "tracing")]
tracing::debug!("[sid={}] socket received unexpected bin data", socket.id);
false
}
}
4 changes: 2 additions & 2 deletions socketioxide/src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use tokio::sync::{mpsc::error::TrySendError, oneshot};
#[derive(thiserror::Error, Debug)]
pub enum Error {
#[error("error serializing json packet: {0:?}")]
SerializeError(#[from] serde_json::Error),
Serialize(#[from] serde_json::Error),

#[error("invalid packet type")]
InvalidPacketType,
Expand All @@ -33,7 +33,7 @@ impl From<&Error> for Option<EIoDisconnectReason> {
use EIoDisconnectReason::*;
match value {
Error::SocketGone(_) => Some(TransportClose),
Error::SerializeError(_) | Error::InvalidPacketType | Error::InvalidEventName => {
Error::Serialize(_) | Error::InvalidPacketType | Error::InvalidEventName => {
Some(PacketParsingError)
}
Error::Adapter(_) | Error::InvalidNamespace => None,
Expand Down
4 changes: 2 additions & 2 deletions socketioxide/src/io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ impl Default for SocketIoConfig {
fn default() -> Self {
Self {
engine_config: EngineIoConfig {
req_path: "/socket.io".to_string(),
req_path: "/socket.io".into(),
..Default::default()
},
ack_timeout: Duration::from_secs(5),
Expand Down Expand Up @@ -71,7 +71,7 @@ impl SocketIoBuilder {
///
/// Defaults to "/socket.io".
#[inline]
pub fn req_path(mut self, req_path: String) -> Self {
pub fn req_path(mut self, req_path: impl Into<Cow<'static, str>>) -> Self {
self.engine_config_builder = self.engine_config_builder.req_path(req_path);
self
}
Expand Down
3 changes: 0 additions & 3 deletions socketioxide/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
#![cfg_attr(docsrs, feature(doc_cfg))]
#![warn(
clippy::future_not_send,
clippy::all,
clippy::todo,
clippy::empty_enum,
clippy::enum_glob_use,
clippy::mem_forget,
clippy::unused_self,
clippy::filter_map_next,
Expand All @@ -27,7 +25,6 @@
clippy::option_option,
clippy::verbose_file_reads,
clippy::unnested_or_patterns,
clippy::str_to_string,
rust_2018_idioms,
future_incompatible,
nonstandard_style,
Expand Down
6 changes: 2 additions & 4 deletions socketioxide/src/packet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -310,7 +310,7 @@ impl<'a> TryInto<String> for Packet<'a> {
// Expand the packet if it is an array with data -> ["event", ...data]
let packet = match data {
Value::Array(ref mut v) if !v.is_empty() => {
v.insert(0, Value::String(e.to_string()));
v.insert(0, Value::String((*e).to_string()));
serde_json::to_string(&v)
}
Value::Array(_) => serde_json::to_string::<(_, [(); 0])>(&(e, [])),
Expand Down Expand Up @@ -478,9 +478,7 @@ impl<'a> TryFrom<String> for Packet<'a> {
let ack: Option<i64> = loop {
match chars.get(i) {
Some(c) if c.is_ascii_digit() => i += 1,
Some(b'[') | Some(b'{') if i > start_index => {
break value[start_index..i].parse().ok()
}
Some(b'[' | b'{') if i > start_index => break value[start_index..i].parse().ok(),
_ => break None,
}
};
Expand Down

0 comments on commit c03303a

Please sign in to comment.