Skip to content

Commit 4263f48

Browse files
committed
Fix clippy and fmt
1 parent 4e152e1 commit 4263f48

File tree

7 files changed

+98
-77
lines changed

7 files changed

+98
-77
lines changed

compio-ws/examples/autobahn-server.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
1+
use std::net::SocketAddr;
2+
13
use compio_net::{TcpListener, TcpStream};
2-
use compio_ws::{accept_async_with_config, WebSocketConfig};
4+
use compio_ws::{WebSocketConfig, accept_async_with_config};
35
use log::*;
4-
use std::net::SocketAddr;
56
use tungstenite::{Error, Result};
67

78
async fn accept_connection(peer: SocketAddr, stream: TcpStream) {

compio-ws/examples/client_tls.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
1-
use compio_ws::{connect_async_with_tls_connector, Connector};
2-
use rustls::ClientConfig;
31
use std::sync::Arc;
2+
3+
use compio_ws::{Connector, connect_async_with_tls_connector};
4+
use rustls::ClientConfig;
45
use tungstenite::Message;
56

67
async fn create_insecure_tls_connector() -> Result<Connector, Box<dyn std::error::Error>> {

compio-ws/examples/echo_server_tls.rs

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,16 @@
1+
use std::{fs, sync::Arc};
2+
13
use compio_net::{TcpListener, TcpStream};
24
use compio_tls::TlsAcceptor;
35
use compio_ws::accept_async;
46
use rustls::ServerConfig;
5-
use std::fs;
6-
use std::sync::Arc;
77
use tungstenite::Message;
88

99
async fn create_tls_acceptor() -> Result<TlsAcceptor, Box<dyn std::error::Error>> {
1010
// Load certificate and key from files
1111
// Generate these files with:
12-
// openssl req -x509 -newkey rsa:2048 -keyout localhost.key -out localhost.crt -days 365 -nodes -subj "/CN=localhost"
12+
// openssl req -x509 -newkey rsa:2048 -keyout localhost.key -out localhost.crt
13+
// -days 365 -nodes -subj "/CN=localhost"
1314

1415
let cert_file = fs::read_to_string("localhost.crt")?;
1516
let key_file = fs::read_to_string("localhost.key")?;
@@ -42,7 +43,10 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
4243
{
4344
eprintln!("Error: Certificate files not found!");
4445
eprintln!("Please generate them with:");
45-
eprintln!("openssl req -x509 -newkey rsa:2048 -keyout localhost.key -out localhost.crt -days 365 -nodes -subj \"/CN=localhost\"");
46+
eprintln!(
47+
"openssl req -x509 -newkey rsa:2048 -keyout localhost.key -out localhost.crt -days \
48+
365 -nodes -subj \"/CN=localhost\""
49+
);
4650
return Err("Missing certificate files".into());
4751
}
4852

compio-ws/src/growable_sync_stream.rs

Lines changed: 34 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -5,28 +5,33 @@ use compio_io::{AsyncRead, AsyncWrite};
55

66
/// A growable buffered stream adapter that bridges async I/O with sync traits.
77
///
8-
/// This is similar to `compio_io::compat::SyncStream` but with dynamically growing
9-
/// buffers that can expand beyond the initial capacity up to a configurable maximum.
8+
/// This is similar to `compio_io::compat::SyncStream` but with dynamically
9+
/// growing buffers that can expand beyond the initial capacity up to a
10+
/// configurable maximum.
1011
///
1112
/// # Buffer Growth Strategy
1213
///
13-
/// - **Read buffer**: Grows as needed to accommodate incoming data, up to `max_buffer_size`
14-
/// - **Write buffer**: Grows as needed for outgoing data, up to `max_buffer_size`
15-
/// - Both buffers shrink back to `base_capacity` when fully consumed and capacity exceeds 4x base
14+
/// - **Read buffer**: Grows as needed to accommodate incoming data, up to
15+
/// `max_buffer_size`
16+
/// - **Write buffer**: Grows as needed for outgoing data, up to
17+
/// `max_buffer_size`
18+
/// - Both buffers shrink back to `base_capacity` when fully consumed and
19+
/// capacity exceeds 4x base
1620
///
1721
/// # Usage Pattern
1822
///
19-
/// The sync `Read` and `Write` implementations will return `WouldBlock` errors when
20-
/// buffers need servicing via the async methods:
23+
/// The sync `Read` and `Write` implementations will return `WouldBlock` errors
24+
/// when buffers need servicing via the async methods:
2125
///
2226
/// - Call `fill_read_buf()` when `Read::read()` returns `WouldBlock`
2327
/// - Call `flush_write_buf()` when `Write::write()` returns `WouldBlock`
2428
///
2529
/// # Note on flush()
2630
///
27-
/// The `Write::flush()` method intentionally returns `Ok(())` without checking if there's
28-
/// buffered data. This is for compatibility with libraries like tungstenite that call
29-
/// `flush()` after every write. Actual flushing happens via the async `flush_write_buf()` method.
31+
/// The `Write::flush()` method intentionally returns `Ok(())` without checking
32+
/// if there's buffered data. This is for compatibility with libraries like
33+
/// tungstenite that call `flush()` after every write. Actual flushing happens
34+
/// via the async `flush_write_buf()` method.
3035
#[derive(Debug)]
3136
pub struct GrowableSyncStream<S> {
3237
inner: S,
@@ -39,8 +44,11 @@ pub struct GrowableSyncStream<S> {
3944
}
4045

4146
impl<S> GrowableSyncStream<S> {
42-
const DEFAULT_BASE_CAPACITY: usize = 8 * 1024; // 8KB base
43-
const DEFAULT_MAX_BUFFER: usize = 64 * 1024 * 1024; // 64MB max
47+
const DEFAULT_BASE_CAPACITY: usize = 8 * 1024;
48+
// 8KB base
49+
const DEFAULT_MAX_BUFFER: usize = 64 * 1024 * 1024;
50+
51+
// 64MB max
4452

4553
/// Creates a new `GrowableSyncStream` with default buffer sizes.
4654
///
@@ -65,7 +73,8 @@ impl<S> GrowableSyncStream<S> {
6573
}
6674
}
6775

68-
/// Creates a new `GrowableSyncStream` with custom base capacity and maximum buffer size.
76+
/// Creates a new `GrowableSyncStream` with custom base capacity and maximum
77+
/// buffer size.
6978
pub fn with_limits(base_capacity: usize, max_buffer_size: usize, stream: S) -> Self {
7079
Self {
7180
inner: stream,
@@ -149,8 +158,9 @@ impl<S> Read for GrowableSyncStream<S> {
149158
impl<S> Write for GrowableSyncStream<S> {
150159
/// Writes data to the internal buffer.
151160
///
152-
/// Returns `WouldBlock` if the buffer needs flushing or has reached max capacity.
153-
/// In the latter case, it may write partial data before returning `WouldBlock`.
161+
/// Returns `WouldBlock` if the buffer needs flushing or has reached max
162+
/// capacity. In the latter case, it may write partial data before
163+
/// returning `WouldBlock`.
154164
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
155165
// Check if we should flush first
156166
if self.write_buf.len() > self.base_capacity * 2 / 3 && !self.write_buf.is_empty() {
@@ -179,13 +189,14 @@ impl<S> Write for GrowableSyncStream<S> {
179189

180190
/// Returns `Ok(())` without checking for buffered data.
181191
///
182-
/// **Important**: This does NOT actually flush data to the underlying stream.
183-
/// This behavior is intentional for compatibility with libraries like tungstenite
184-
/// that call `flush()` after every write operation. The actual async flush
185-
/// happens when `flush_write_buf()` is called.
192+
/// **Important**: This does NOT actually flush data to the underlying
193+
/// stream. This behavior is intentional for compatibility with
194+
/// libraries like tungstenite that call `flush()` after every write
195+
/// operation. The actual async flush happens when `flush_write_buf()`
196+
/// is called.
186197
///
187-
/// This prevents spurious errors in sync code that expects `flush()` to succeed
188-
/// after successfully buffering data.
198+
/// This prevents spurious errors in sync code that expects `flush()` to
199+
/// succeed after successfully buffering data.
189200
fn flush(&mut self) -> io::Result<()> {
190201
Ok(())
191202
}
@@ -307,7 +318,8 @@ impl<S: AsyncWrite> GrowableSyncStream<S> {
307318
/// # Errors
308319
///
309320
/// Returns an error if the underlying stream returns an error.
310-
/// In this case, the buffer retains any data that wasn't successfully written.
321+
/// In this case, the buffer retains any data that wasn't successfully
322+
/// written.
311323
pub async fn flush_write_buf(&mut self) -> io::Result<usize> {
312324
if self.write_buf.is_empty() {
313325
return Ok(0);

compio-ws/src/lib.rs

Lines changed: 23 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
//! Async WebSocket support for compio.
22
//!
3-
//! This library is an implementation of WebSocket handshakes and streams for compio.
4-
//! It is based on the tungstenite crate which implements all required WebSocket protocol
5-
//! logic. This crate brings compio support / compio integration to it.
3+
//! This library is an implementation of WebSocket handshakes and streams for
4+
//! compio. It is based on the tungstenite crate which implements all required
5+
//! WebSocket protocol logic. This crate brings compio support / compio
6+
//! integration to it.
67
//!
78
//! Each WebSocket stream implements message reading and writing.
89
@@ -16,21 +17,16 @@ use std::io::ErrorKind;
1617

1718
use compio_io::{AsyncRead, AsyncWrite};
1819
use growable_sync_stream::GrowableSyncStream;
19-
2020
use tungstenite::{
2121
Error as WsError, HandshakeError, Message, WebSocket,
2222
client::IntoClientRequest,
2323
handshake::server::{Callback, NoCallback},
2424
protocol::CloseFrame,
2525
};
26-
27-
pub use crate::stream::MaybeTlsStream;
28-
29-
pub use tungstenite::{Message as WebSocketMessage, handshake::client::Response};
30-
31-
pub use tungstenite::protocol::WebSocketConfig;
32-
33-
pub use tungstenite::error::Error as TungsteniteError;
26+
pub use tungstenite::{
27+
Message as WebSocketMessage, error::Error as TungsteniteError, handshake::client::Response,
28+
protocol::WebSocketConfig,
29+
};
3430

3531
#[cfg(feature = "rustls")]
3632
pub use crate::rustls::{
@@ -39,6 +35,7 @@ pub use crate::rustls::{
3935
connect_async_with_config, connect_async_with_tls_connector,
4036
connect_async_with_tls_connector_and_config,
4137
};
38+
pub use crate::stream::MaybeTlsStream;
4239

4340
pub struct WebSocketStream<S> {
4441
inner: WebSocket<GrowableSyncStream<S>>,
@@ -140,8 +137,8 @@ where
140137
accept_hdr_async(stream, NoCallback).await
141138
}
142139

143-
/// The same as `accept_async()` but the one can specify a websocket configuration.
144-
/// Please refer to `accept_async()` for more details.
140+
/// The same as `accept_async()` but the one can specify a websocket
141+
/// configuration. Please refer to `accept_async()` for more details.
145142
pub async fn accept_async_with_config<S>(
146143
stream: S,
147144
config: Option<WebSocketConfig>,
@@ -153,9 +150,9 @@ where
153150
}
154151
/// Accepts a new WebSocket connection with the provided stream.
155152
///
156-
/// This function does the same as `accept_async()` but accepts an extra callback
157-
/// for header processing. The callback receives headers of the incoming
158-
/// requests and is able to add extra headers to the reply.
153+
/// This function does the same as `accept_async()` but accepts an extra
154+
/// callback for header processing. The callback receives headers of the
155+
/// incoming requests and is able to add extra headers to the reply.
159156
pub async fn accept_hdr_async<S, C>(stream: S, callback: C) -> Result<WebSocketStream<S>, WsError>
160157
where
161158
S: AsyncRead + AsyncWrite + Unpin + std::fmt::Debug,
@@ -164,8 +161,8 @@ where
164161
accept_hdr_with_config_async(stream, callback, None).await
165162
}
166163

167-
/// The same as `accept_hdr_async()` but the one can specify a websocket configuration.
168-
/// Please refer to `accept_hdr_async()` for more details.
164+
/// The same as `accept_hdr_async()` but the one can specify a websocket
165+
/// configuration. Please refer to `accept_hdr_async()` for more details.
169166
pub async fn accept_hdr_with_config_async<S, C>(
170167
stream: S,
171168
callback: C,
@@ -228,8 +225,8 @@ where
228225
client_async_with_config(request, stream, None).await
229226
}
230227

231-
/// The same as `client_async()` but the one can specify a websocket configuration.
232-
/// Please refer to `client_async()` for more details.
228+
/// The same as `client_async()` but the one can specify a websocket
229+
/// configuration. Please refer to `client_async()` for more details.
233230
pub async fn client_async_with_config<R, S>(
234231
request: R,
235232
stream: S,
@@ -281,11 +278,12 @@ pub(crate) fn domain(
281278
.uri()
282279
.host()
283280
.map(|host| {
284-
// If host is an IPv6 address, it might be surrounded by brackets. These brackets are
285-
// *not* part of a valid IP, so they must be stripped out.
281+
// If host is an IPv6 address, it might be surrounded by brackets. These
282+
// brackets are *not* part of a valid IP, so they must be stripped
283+
// out.
286284
//
287-
// The URI from the request is guaranteed to be valid, so we don't need a separate
288-
// check for the closing bracket.
285+
// The URI from the request is guaranteed to be valid, so we don't need a
286+
// separate check for the closing bracket.
289287
let host = if host.starts_with('[') {
290288
&host[1..host.len() - 1]
291289
} else {

compio-ws/src/rustls.rs

Lines changed: 25 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,19 @@
1+
use std::sync::Arc;
2+
13
use compio_io::{AsyncRead, AsyncWrite};
24
use compio_net::TcpStream;
35
use compio_tls::TlsConnector;
46
use rustls::{ClientConfig, RootCertStore};
7+
use tungstenite::{
8+
Error,
9+
client::{IntoClientRequest, uri_mode},
10+
handshake::client::{Request, Response},
11+
stream::Mode,
12+
};
513

6-
use tungstenite::Error;
7-
use tungstenite::client::{IntoClientRequest, uri_mode};
8-
use tungstenite::handshake::client::{Request, Response};
9-
use tungstenite::stream::Mode;
10-
11-
use std::sync::Arc;
12-
13-
use crate::stream::MaybeTlsStream;
14-
use crate::{WebSocketConfig, WebSocketStream, client_async_with_config, domain};
14+
use crate::{
15+
WebSocketConfig, WebSocketStream, client_async_with_config, domain, stream::MaybeTlsStream,
16+
};
1517

1618
pub type AutoStream<S> = MaybeTlsStream<S>;
1719

@@ -35,7 +37,7 @@ where
3537
} else {
3638
// Only create root_store when we actually have certificate features enabled
3739
#[cfg(any(feature = "rustls-native-certs", feature = "webpki-roots"))]
38-
let mut root_store = {
40+
let root_store = {
3941
let mut store = RootCertStore::empty();
4042

4143
#[cfg(feature = "rustls-native-certs")]
@@ -80,8 +82,7 @@ where
8082
{
8183
use log::debug;
8284

83-
let webpki_certs: Vec<_> =
84-
webpki_roots::TLS_SERVER_ROOTS.iter().cloned().collect();
85+
let webpki_certs = webpki_roots::TLS_SERVER_ROOTS.to_vec();
8586
store.extend(webpki_certs);
8687
debug!(
8788
"Added {} webpki root certificates",
@@ -97,7 +98,8 @@ where
9798
{
9899
return Err(Error::Io(std::io::Error::new(
99100
std::io::ErrorKind::NotFound,
100-
"No root certificate features enabled. Enable either 'rustls-native-certs' or 'webpki-roots'",
101+
"No root certificate features enabled. Enable either \
102+
'rustls-native-certs' or 'webpki-roots'",
101103
)));
102104
}
103105

@@ -145,7 +147,8 @@ where
145147
client_async_tls_with_connector_and_config(request, stream, None, None).await
146148
}
147149

148-
/// The same as `client_async_tls()` but the one can specify a websocket configuration.
150+
/// The same as `client_async_tls()` but the one can specify a websocket
151+
/// configuration.
149152
pub async fn client_async_tls_with_config<R, S>(
150153
request: R,
151154
stream: S,
@@ -173,8 +176,8 @@ where
173176
client_async_tls_with_connector_and_config(request, stream, connector, None).await
174177
}
175178

176-
/// The same as `client_async_tls()` but the one can specify a websocket configuration,
177-
/// and an optional connector.
179+
/// The same as `client_async_tls()` but the one can specify a websocket
180+
/// configuration, and an optional connector.
178181
pub async fn client_async_tls_with_connector_and_config<R, S>(
179182
request: R,
180183
stream: S,
@@ -208,9 +211,10 @@ where
208211
connect_async_with_config(request, None, false).await
209212
}
210213

211-
/// The same as `connect_async()` but the one can specify a websocket configuration.
212-
/// `disable_nagle` specifies if the Nagle's algorithm must be disabled, i.e. `set_nodelay(true)`.
213-
/// If you don't know what the Nagle's algorithm is, better leave it to `false`.
214+
/// The same as `connect_async()` but the one can specify a websocket
215+
/// configuration. `disable_nagle` specifies if the Nagle's algorithm must be
216+
/// disabled, i.e. `set_nodelay(true)`. If you don't know what the Nagle's
217+
/// algorithm is, better leave it to `false`.
214218
pub async fn connect_async_with_config<R>(
215219
request: R,
216220
config: Option<WebSocketConfig>,
@@ -246,8 +250,8 @@ where
246250
connect_async_with_tls_connector_and_config(request, connector, None).await
247251
}
248252

249-
/// The same as `connect_async()` but the one can specify a websocket configuration,
250-
/// a TLS connector, and whether to disable Nagle's algorithm.
253+
/// The same as `connect_async()` but the one can specify a websocket
254+
/// configuration, a TLS connector, and whether to disable Nagle's algorithm.
251255
pub async fn connect_async_with_tls_connector_and_config<R>(
252256
request: R,
253257
connector: Option<Connector>,

compio-ws/src/stream.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
1+
use std::io::Result as IoResult;
2+
13
use compio_buf::{BufResult, IoBuf, IoBufMut};
24
use compio_io::{AsyncRead, AsyncWrite};
35
#[cfg(feature = "rustls")]
46
use compio_tls::TlsStream;
5-
use std::io::Result as IoResult;
67

78
/// Stream that can be either plain TCP or TLS-encrypted
89
#[derive(Debug)]

0 commit comments

Comments
 (0)