Skip to content

Commit

Permalink
Use default max_with in rustfmt.toml
Browse files Browse the repository at this point in the history
  • Loading branch information
chrislearn committed Aug 25, 2024
1 parent 2d8cc24 commit dd7a338
Show file tree
Hide file tree
Showing 153 changed files with 3,158 additions and 1,116 deletions.
49 changes: 40 additions & 9 deletions crates/cache/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,11 @@ pub trait CacheIssuer: Send + Sync + 'static {
/// The key is used to identify the rate limit.
type Key: Hash + Eq + Send + Sync + 'static;
/// Issue a new key for the request. If it returns `None`, the request will not be cached.
fn issue(&self, req: &mut Request, depot: &Depot) -> impl Future<Output = Option<Self::Key>> + Send;
fn issue(
&self,
req: &mut Request,
depot: &Depot,
) -> impl Future<Output = Option<Self::Key>> + Send;
}
impl<F, K> CacheIssuer for F
where
Expand Down Expand Up @@ -153,7 +157,11 @@ pub trait CacheStore: Send + Sync + 'static {
Self::Key: Borrow<Q>,
Q: Hash + Eq + Sync;
/// Save the cache item from the store.
fn save_entry(&self, key: Self::Key, data: CachedEntry) -> impl Future<Output = Result<(), Self::Error>> + Send;
fn save_entry(
&self,
key: Self::Key,
data: CachedEntry,
) -> impl Future<Output = Result<(), Self::Error>> + Send;
}

/// `CachedBody` is used to save response body to `CachedStore`.
Expand Down Expand Up @@ -207,7 +215,11 @@ pub struct CachedEntry {
impl CachedEntry {
/// Create a new `CachedEntry`.
pub fn new(status: Option<StatusCode>, headers: HeaderMap, body: CachedBody) -> Self {
Self { status, headers, body }
Self {
status,
headers,
body,
}
}

/// Get the response status.
Expand Down Expand Up @@ -279,7 +291,13 @@ where
S: CacheStore<Key = I::Key>,
I: CacheIssuer,
{
async fn handle(&self, req: &mut Request, depot: &mut Depot, res: &mut Response, ctrl: &mut FlowCtrl) {
async fn handle(
&self,
req: &mut Request,
depot: &mut Depot,
res: &mut Response,
ctrl: &mut FlowCtrl,
) {
if self.skipper.skipped(req, depot) {
return;
}
Expand Down Expand Up @@ -309,7 +327,11 @@ where
return;
}
};
let CachedEntry { status, headers, body } = cache;
let CachedEntry {
status,
headers,
body,
} = cache;
if let Some(status) = status {
res.status_code(status);
}
Expand All @@ -328,7 +350,10 @@ mod tests {

#[handler]
async fn cached() -> String {
format!("Hello World, my birth time is {}", OffsetDateTime::now_utc())
format!(
"Hello World, my birth time is {}",
OffsetDateTime::now_utc()
)
}

#[tokio::test]
Expand All @@ -342,19 +367,25 @@ mod tests {
let router = Router::new().hoop(cache).goal(cached);
let service = Service::new(router);

let mut res = TestClient::get("http://127.0.0.1:5801").send(&service).await;
let mut res = TestClient::get("http://127.0.0.1:5801")
.send(&service)
.await;
assert_eq!(res.status_code.unwrap(), StatusCode::OK);

let content0 = res.take_string().await.unwrap();

let mut res = TestClient::get("http://127.0.0.1:5801").send(&service).await;
let mut res = TestClient::get("http://127.0.0.1:5801")
.send(&service)
.await;
assert_eq!(res.status_code.unwrap(), StatusCode::OK);

let content1 = res.take_string().await.unwrap();
assert_eq!(content0, content1);

tokio::time::sleep(tokio::time::Duration::from_secs(6)).await;
let mut res = TestClient::post("http://127.0.0.1:5801").send(&service).await;
let mut res = TestClient::post("http://127.0.0.1:5801")
.send(&service)
.await;
let content2 = res.take_string().await.unwrap();

assert_ne!(content0, content2);
Expand Down
28 changes: 23 additions & 5 deletions crates/compression/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@ use std::str::FromStr;
use indexmap::IndexMap;

use salvo_core::http::body::ResBody;
use salvo_core::http::header::{HeaderValue, ACCEPT_ENCODING, CONTENT_ENCODING, CONTENT_LENGTH, CONTENT_TYPE};
use salvo_core::http::header::{
HeaderValue, ACCEPT_ENCODING, CONTENT_ENCODING, CONTENT_LENGTH, CONTENT_TYPE,
};
use salvo_core::http::{self, mime, Mime, StatusCode};
use salvo_core::{async_trait, Depot, FlowCtrl, Handler, Request, Response};

Expand Down Expand Up @@ -264,7 +266,11 @@ impl Compression {
self
}

fn negotiate(&self, req: &Request, res: &Response) -> Option<(CompressionAlgo, CompressionLevel)> {
fn negotiate(
&self,
req: &Request,
res: &Response,
) -> Option<(CompressionAlgo, CompressionLevel)> {
if req.headers().contains_key(&CONTENT_ENCODING) {
return None;
}
Expand All @@ -289,7 +295,10 @@ impl Compression {
return None;
}
}
let header = req.headers().get(ACCEPT_ENCODING).and_then(|v| v.to_str().ok())?;
let header = req
.headers()
.get(ACCEPT_ENCODING)
.and_then(|v| v.to_str().ok())?;

let accept_algos = http::parse_accept_encoding(header)
.into_iter()
Expand All @@ -302,7 +311,10 @@ impl Compression {
})
.collect::<Vec<_>>();
if self.force_priority {
let accept_algos = accept_algos.into_iter().map(|(algo, _)| algo).collect::<Vec<_>>();
let accept_algos = accept_algos
.into_iter()
.map(|(algo, _)| algo)
.collect::<Vec<_>>();
self.algos
.iter()
.find(|(algo, _level)| accept_algos.contains(algo))
Expand All @@ -317,7 +329,13 @@ impl Compression {

#[async_trait]
impl Handler for Compression {
async fn handle(&self, req: &mut Request, depot: &mut Depot, res: &mut Response, ctrl: &mut FlowCtrl) {
async fn handle(
&self,
req: &mut Request,
depot: &mut Depot,
res: &mut Response,
ctrl: &mut FlowCtrl,
) {
ctrl.call_next(req, depot, res).await;
if ctrl.is_ceased() || res.headers().contains_key(CONTENT_ENCODING) {
return;
Expand Down
3 changes: 2 additions & 1 deletion crates/compression/src/stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@ impl<B> EncodeStream<B> {
impl EncodeStream<BoxStream<'static, Result<Bytes, BoxedError>>> {
#[inline]
fn poll_chunk(&mut self, cx: &mut Context<'_>) -> Poll<Option<IoResult<Bytes>>> {
Stream::poll_next(Pin::new(&mut self.body), cx).map_err(|e| IoError::new(ErrorKind::Other, e))
Stream::poll_next(Pin::new(&mut self.body), cx)
.map_err(|e| IoError::new(ErrorKind::Other, e))
}
}
impl EncodeStream<BoxStream<'static, Result<BytesFrame, BoxedError>>> {
Expand Down
39 changes: 33 additions & 6 deletions crates/core/src/catcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,10 @@ impl Catcher {
H: Handler,
F: Fn(&Request, &Depot) -> bool + Send + Sync + 'static,
{
self.hoops.push(Arc::new(WhenHoop { inner: hoop, filter }));
self.hoops.push(Arc::new(WhenHoop {
inner: hoop,
filter,
}));
self
}

Expand Down Expand Up @@ -146,15 +149,29 @@ impl DefaultGoal {
}
#[async_trait]
impl Handler for DefaultGoal {
async fn handle(&self, req: &mut Request, _depot: &mut Depot, res: &mut Response, _ctrl: &mut FlowCtrl) {
async fn handle(
&self,
req: &mut Request,
_depot: &mut Depot,
res: &mut Response,
_ctrl: &mut FlowCtrl,
) {
let status = res.status_code.unwrap_or(StatusCode::NOT_FOUND);
if (status.is_server_error() || status.is_client_error()) && (res.body.is_none() || res.body.is_error()) {
if (status.is_server_error() || status.is_client_error())
&& (res.body.is_none() || res.body.is_error())
{
write_error_default(req, res, self.footer.as_deref());
}
}
}

fn status_error_html(code: StatusCode, name: &str, brief: &str, cause: Option<&str>, footer: Option<&str>) -> String {
fn status_error_html(
code: StatusCode,
name: &str,
brief: &str,
cause: Option<&str>,
footer: Option<&str>,
) -> String {
format!(
r#"<!DOCTYPE html>
<html>
Expand Down Expand Up @@ -253,7 +270,11 @@ fn status_error_xml(code: StatusCode, name: &str, brief: &str, cause: Option<&st
/// Create bytes from `StatusError`.
#[doc(hidden)]
#[inline]
pub fn status_error_bytes(err: &StatusError, prefer_format: &Mime, footer: Option<&str>) -> (Mime, Bytes) {
pub fn status_error_bytes(
err: &StatusError,
prefer_format: &Mime,
footer: Option<&str>,
) -> (Mime, Bytes) {
let format = if !SUPPORTED_FORMATS.contains(&prefer_format.subtype()) {
mime::TEXT_HTML
} else {
Expand Down Expand Up @@ -309,7 +330,13 @@ mod tests {
}

#[handler]
async fn handle404(&self, _req: &Request, _depot: &Depot, res: &mut Response, ctrl: &mut FlowCtrl) {
async fn handle404(
&self,
_req: &Request,
_depot: &Depot,
res: &mut Response,
ctrl: &mut FlowCtrl,
) {
if res.status_code.is_none() || Some(StatusCode::NOT_FOUND) == res.status_code {
res.render("Custom 404 Error Page");
ctrl.skip_rest();
Expand Down
23 changes: 19 additions & 4 deletions crates/core/src/conn/joined.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,11 @@ where
B: AsyncRead + Send + Unpin + 'static,
{
#[inline]
fn poll_read(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<IoResult<()>> {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut ReadBuf<'_>,
) -> Poll<IoResult<()>> {
match &mut self.get_mut() {
JoinedStream::A(a) => Pin::new(a).poll_read(cx, buf),
JoinedStream::B(b) => Pin::new(b).poll_read(cx, buf),
Expand Down Expand Up @@ -95,7 +99,12 @@ where
async fn try_bind(self) -> crate::Result<Self::Acceptor> {
let a = self.a.try_bind().await?;
let b = self.b.try_bind().await?;
let holdings = a.holdings().iter().chain(b.holdings().iter()).cloned().collect();
let holdings = a
.holdings()
.iter()
.chain(b.holdings().iter())
.cloned()
.collect();
Ok(JoinedAcceptor { a, b, holdings })
}
}
Expand Down Expand Up @@ -148,7 +157,10 @@ where
}

#[inline]
async fn accept(&mut self, fuse_factory: Option<ArcFuseFactory>) -> IoResult<Accepted<Self::Conn>> {
async fn accept(
&mut self,
fuse_factory: Option<ArcFuseFactory>,
) -> IoResult<Accepted<Self::Conn>> {
tokio::select! {
accepted = self.a.accept(fuse_factory.clone()) => {
Ok(accepted?.map_conn(JoinedStream::A))
Expand All @@ -173,7 +185,10 @@ mod tests {
let addr1 = std::net::SocketAddr::from(([127, 0, 0, 1], 6978));
let addr2 = std::net::SocketAddr::from(([127, 0, 0, 1], 6979));

let mut acceptor = TcpListener::new(addr1).join(TcpListener::new(addr2)).bind().await;
let mut acceptor = TcpListener::new(addr1)
.join(TcpListener::new(addr2))
.bind()
.await;
tokio::spawn(async move {
let mut stream = TcpStream::connect(addr1).await.unwrap();
stream.write_i32(50).await.unwrap();
Expand Down
24 changes: 20 additions & 4 deletions crates/core/src/conn/proto.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,11 @@ impl HttpBuilder {
match version {
Version::HTTP_10 | Version::HTTP_11 => {
#[cfg(not(feature = "http1"))]
return Err(std::io::Error::new(std::io::ErrorKind::Other, "http1 feature not enabled").into());
return Err(std::io::Error::new(
std::io::ErrorKind::Other,
"http1 feature not enabled",
)
.into());
#[cfg(feature = "http1")]
{
let mut conn = self
Expand Down Expand Up @@ -163,7 +167,11 @@ impl HttpBuilder {
}
Version::HTTP_2 => {
#[cfg(not(feature = "http2"))]
return Err(std::io::Error::new(std::io::ErrorKind::Other, "http2 feature not enabled").into());
return Err(std::io::Error::new(
std::io::ErrorKind::Other,
"http2 feature not enabled",
)
.into());
#[cfg(feature = "http2")]
{
let mut conn = self.http2.serve_connection(TokioIo::new(socket), service);
Expand Down Expand Up @@ -305,7 +313,11 @@ impl<T> AsyncRead for Rewind<T>
where
T: AsyncRead + Unpin,
{
fn poll_read(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<IoResult<()>> {
fn poll_read(
mut self: Pin<&mut Self>,
cx: &mut task::Context<'_>,
buf: &mut ReadBuf<'_>,
) -> Poll<IoResult<()>> {
if let Some(mut prefix) = self.pre.take() {
// If there are no remaining bytes, let the bytes get dropped.
if !prefix.is_empty() {
Expand All @@ -328,7 +340,11 @@ impl<T> AsyncWrite for Rewind<T>
where
T: AsyncWrite + Unpin,
{
fn poll_write(mut self: Pin<&mut Self>, cx: &mut task::Context<'_>, buf: &[u8]) -> Poll<IoResult<usize>> {
fn poll_write(
mut self: Pin<&mut Self>,
cx: &mut task::Context<'_>,
buf: &[u8],
) -> Poll<IoResult<usize>> {
Pin::new(&mut self.inner).poll_write(cx, buf)
}

Expand Down
12 changes: 10 additions & 2 deletions crates/core/src/conn/stream/straight.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,11 @@ impl<C> AsyncRead for StraightStream<C>
where
C: AsyncRead,
{
fn poll_read(self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>) -> Poll<IoResult<()>> {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut ReadBuf<'_>,
) -> Poll<IoResult<()>> {
let this = self.project();
let remaining = buf.remaining();
match this.inner.poll_read(cx, buf) {
Expand Down Expand Up @@ -119,7 +123,11 @@ where
this.inner.poll_shutdown(cx)
}

fn poll_write_vectored(self: Pin<&mut Self>, cx: &mut Context<'_>, bufs: &[IoSlice<'_>]) -> Poll<IoResult<usize>> {
fn poll_write_vectored(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
bufs: &[IoSlice<'_>],
) -> Poll<IoResult<usize>> {
let this = self.project();
if let Some(fusewire) = &this.fusewire {
fusewire.event(FuseEvent::Alive);
Expand Down
Loading

0 comments on commit dd7a338

Please sign in to comment.