feat: Add fix to visibility warning and apply code format

This commit is contained in:
manuelgdlvh 2025-05-14 21:34:50 +02:00
parent b47530d66a
commit 9f2b207137
7 changed files with 116 additions and 98 deletions

View File

@ -1,6 +1,6 @@
//! Based on https://github.com/ibraheemdev/matchit/blob/master/benches/bench.rs
use criterion::{black_box, Criterion, criterion_group, criterion_main};
use criterion::{black_box, criterion_group, criterion_main, Criterion};
macro_rules! register {
(colon) => {{
@ -150,7 +150,7 @@ macro_rules! register {
}};
}
fn call() -> impl Iterator<Item=&'static str> {
fn call() -> impl Iterator<Item = &'static str> {
let arr = [
"/authorizations",
"/user/repos",

View File

@ -8,7 +8,7 @@ use serde::{de, Deserialize};
use crate::{de::PathDeserializer, Resource, ResourcePath};
#[derive(Debug, Clone)]
pub(crate) enum PathItem {
pub enum PathItem {
Static(Cow<'static, str>),
Segment(u16, u16),
}

View File

@ -1,15 +1,15 @@
use std::{
borrow::{Borrow, Cow},
collections::HashMap,
hash::{BuildHasher, Hash, Hasher}
hash::{BuildHasher, Hash, Hasher},
};
use tracing::error;
use crate::{
IntoPatterns,
path::PathItem,
Patterns, regex_set::{escape, Regex, RegexSet}, Resource,
regex_set::{escape, Regex, RegexSet},
IntoPatterns, Patterns, Resource,
};
const MAX_DYNAMIC_SEGMENTS: usize = 16;
@ -450,7 +450,7 @@ impl ResourceDef {
/// assert_eq!(iter.next().unwrap(), "/root");
/// assert_eq!(iter.next().unwrap(), "/backup");
/// assert!(iter.next().is_none());
pub fn pattern_iter(&self) -> impl Iterator<Item=&str> {
pub fn pattern_iter(&self) -> impl Iterator<Item = &str> {
struct PatternIter<'a> {
patterns: &'a Patterns,
list_idx: usize,
@ -645,7 +645,7 @@ impl ResourceDef {
/// ```
pub fn resolve_path_if_matches<R: Resource>(&self, resource: &mut R) -> bool {
match self.capture_match_info(resource) {
None => { false }
None => false,
Some(match_info) => {
resource.resolve_path(match_info);
true
@ -698,7 +698,9 @@ impl ResourceDef {
let path_str = path.unprocessed();
match &self.pat_type {
PatternType::Static(pattern) => match self.static_match(pattern, path_str) {
Some(len) => Some(ResourceMatchInfo::Static { matched_len: len as u16 }),
Some(len) => Some(ResourceMatchInfo::Static {
matched_len: len as u16,
}),
None => return None,
},

View File

@ -1,7 +1,7 @@
use std::mem;
use crate::Path;
use crate::resource::ResourceMatchInfo;
use crate::Path;
// TODO: this trait is necessary, document it
// see impl Resource for ServiceRequest
@ -17,7 +17,11 @@ pub trait Resource {
ResourceMatchInfo::Static { matched_len } => {
path.skip(matched_len);
}
ResourceMatchInfo::Dynamic { matched_len, matched_vars, mut segments } => {
ResourceMatchInfo::Dynamic {
matched_len,
matched_vars,
mut segments,
} => {
for i in 0..matched_vars.len() {
path.add(matched_vars[i], mem::take(&mut segments[i]));
}

View File

@ -19,7 +19,10 @@ pub struct Router<T, U = ()> {
impl<T, U> Router<T, U> {
/// Constructs new `RouterBuilder` with empty route list.
pub fn build() -> RouterBuilder<T, U> {
RouterBuilder { routes: Vec::new(), path_conflicts: vec![] }
RouterBuilder {
routes: Vec::new(),
path_conflicts: vec![],
}
}
/// Finds the value in the router that matches a given [routing resource](Resource).
@ -118,8 +121,11 @@ impl<T, U> RouterBuilder<T, U> {
val: T,
ctx: U,
) -> (&mut ResourceDef, &mut T, &mut U) {
if let Some((_, path_conflicts)) = self.path_conflicts.iter_mut()
.find(|(current_rdef, _)| rdef.eq(current_rdef)) {
if let Some((_, path_conflicts)) = self
.path_conflicts
.iter_mut()
.find(|(current_rdef, _)| rdef.eq(current_rdef))
{
*path_conflicts += 1;
} else {
self.path_conflicts.push((rdef.clone(), 1));
@ -135,7 +141,9 @@ impl<T, U> RouterBuilder<T, U> {
/// Finish configuration and create router instance.
pub fn finish(self) -> Router<T, U> {
let max_path_conflicts = self.path_conflicts.iter()
let max_path_conflicts = self
.path_conflicts
.iter()
.map(|(_, path_conflicts)| *path_conflicts)
.max()
.unwrap_or(1);
@ -345,7 +353,11 @@ mod tests {
}
};
assert!(router.recognize_fn(&mut Path::new("/test2"), failures_until_fn_builder(3)).is_none());
assert!(router.recognize_fn(&mut Path::new("/test2"), failures_until_fn_builder(2)).is_some());
assert!(router
.recognize_fn(&mut Path::new("/test2"), failures_until_fn_builder(3))
.is_none());
assert!(router
.recognize_fn(&mut Path::new("/test2"), failures_until_fn_builder(2))
.is_some());
}
}

View File

@ -12,14 +12,14 @@ use crate::{
config::{AppConfig, AppService},
data::FnDataFactory,
dev::Extensions,
Error,
guard::Guard,
HttpResponse,
request::{HttpRequest, HttpRequestPool},
rmap::ResourceMap, service::{
rmap::ResourceMap,
service::{
AppServiceFactory, BoxedHttpService, BoxedHttpServiceFactory, ServiceRequest,
ServiceResponse,
},
Error, HttpResponse,
};
/// Service factory to convert [`Request`] to a [`ServiceRequest<S>`].
@ -29,10 +29,10 @@ pub struct AppInit<T, B>
where
T: ServiceFactory<
ServiceRequest,
Config=(),
Response=ServiceResponse<B>,
Error=Error,
InitError=(),
Config = (),
Response = ServiceResponse<B>,
Error = Error,
InitError = (),
>,
{
pub(crate) endpoint: T,
@ -48,10 +48,10 @@ impl<T, B> ServiceFactory<Request> for AppInit<T, B>
where
T: ServiceFactory<
ServiceRequest,
Config=(),
Response=ServiceResponse<B>,
Error=Error,
InitError=(),
Config = (),
Response = ServiceResponse<B>,
Error = Error,
InitError = (),
>,
T::Future: 'static,
{
@ -145,7 +145,7 @@ where
/// Wraps a service receiving a [`ServiceRequest`] into one receiving a [`Request`].
pub struct AppInitService<T, B>
where
T: Service<ServiceRequest, Response=ServiceResponse<B>, Error=Error>,
T: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
{
service: T,
app_data: Rc<Extensions>,
@ -190,7 +190,7 @@ impl AppInitServiceState {
impl<T, B> Service<Request> for AppInitService<T, B>
where
T: Service<ServiceRequest, Response=ServiceResponse<B>, Error=Error>,
T: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
{
type Response = ServiceResponse<B>;
type Error = T::Error;
@ -230,7 +230,7 @@ where
impl<T, B> Drop for AppInitService<T, B>
where
T: Service<ServiceRequest, Response=ServiceResponse<B>, Error=Error>,
T: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
{
fn drop(&mut self) {
self.app_state.pool().clear();
@ -347,15 +347,15 @@ impl ServiceFactory<ServiceRequest> for AppEntry {
#[cfg(test)]
mod tests {
use std::sync::{
Arc,
atomic::{AtomicBool, Ordering},
Arc,
};
use actix_service::Service;
use crate::{
App,
HttpResponse, test::{init_service, TestRequest}, web,
test::{init_service, TestRequest},
web, App, HttpResponse,
};
struct DropData(Arc<AtomicBool>);
@ -378,7 +378,7 @@ mod tests {
.data(DropData(data.clone()))
.service(web::resource("/test").to(HttpResponse::Ok)),
)
.await;
.await;
let req = TestRequest::with_uri("/test").to_request();
let _ = app.call(req).await.unwrap();
}

View File

@ -14,13 +14,13 @@ use crate::{
config::ServiceConfig,
data::Data,
dev::AppService,
Error,
guard::Guard,
Resource,
rmap::ResourceMap, Route, service::{
rmap::ResourceMap,
service::{
AppServiceFactory, BoxedHttpService, BoxedHttpServiceFactory, HttpServiceFactory,
ServiceFactoryWrapper, ServiceRequest, ServiceResponse,
},
Error, Resource, Route,
};
type Guards = Vec<Box<dyn Guard>>;
@ -86,7 +86,7 @@ impl Scope {
impl<T> Scope<T>
where
T: ServiceFactory<ServiceRequest, Config=(), Error=Error, InitError=()>,
T: ServiceFactory<ServiceRequest, Config = (), Error = Error, InitError = ()>,
{
/// Add match guard to a scope.
///
@ -273,8 +273,8 @@ where
pub fn default_service<F, U>(mut self, f: F) -> Self
where
F: IntoServiceFactory<U, ServiceRequest>,
U: ServiceFactory<ServiceRequest, Config=(), Response=ServiceResponse, Error=Error>
+ 'static,
U: ServiceFactory<ServiceRequest, Config = (), Response = ServiceResponse, Error = Error>
+ 'static,
U::InitError: fmt::Debug,
{
// create and configure default resource
@ -301,20 +301,20 @@ where
) -> Scope<
impl ServiceFactory<
ServiceRequest,
Config=(),
Response=ServiceResponse<B>,
Error=Error,
InitError=(),
Config = (),
Response = ServiceResponse<B>,
Error = Error,
InitError = (),
>,
>
where
M: Transform<
T::Service,
ServiceRequest,
Response=ServiceResponse<B>,
Error=Error,
InitError=(),
> + 'static,
T::Service,
ServiceRequest,
Response = ServiceResponse<B>,
Error = Error,
InitError = (),
> + 'static,
B: MessageBody,
{
Scope {
@ -344,15 +344,15 @@ where
) -> Scope<
impl ServiceFactory<
ServiceRequest,
Config=(),
Response=ServiceResponse<B>,
Error=Error,
InitError=(),
Config = (),
Response = ServiceResponse<B>,
Error = Error,
InitError = (),
>,
>
where
F: Fn(ServiceRequest, &T::Service) -> R + Clone + 'static,
R: Future<Output=Result<ServiceResponse<B>, Error>>,
R: Future<Output = Result<ServiceResponse<B>, Error>>,
B: MessageBody,
{
Scope {
@ -371,12 +371,12 @@ where
impl<T, B> HttpServiceFactory for Scope<T>
where
T: ServiceFactory<
ServiceRequest,
Config=(),
Response=ServiceResponse<B>,
Error=Error,
InitError=(),
> + 'static,
ServiceRequest,
Config = (),
Response = ServiceResponse<B>,
Error = Error,
InitError = (),
> + 'static,
B: MessageBody + 'static,
{
fn register(mut self, config: &mut AppService) {
@ -554,14 +554,14 @@ mod tests {
use bytes::Bytes;
use crate::{
App,
guard,
http::{
header::{self, HeaderValue},
Method, StatusCode,
},
HttpMessage,
HttpRequest, HttpResponse, middleware::DefaultHeaders, test::{assert_body_eq, call_service, init_service, read_body, TestRequest}, web,
middleware::DefaultHeaders,
test::{assert_body_eq, call_service, init_service, read_body, TestRequest},
web, App, HttpMessage, HttpRequest, HttpResponse,
};
use super::*;
@ -576,10 +576,10 @@ mod tests {
fn my_scope_2() -> Scope<
impl ServiceFactory<
ServiceRequest,
Config=(),
Response=ServiceResponse<impl MessageBody>,
Error=Error,
InitError=(),
Config = (),
Response = ServiceResponse<impl MessageBody>,
Error = Error,
InitError = (),
>,
> {
web::scope("/test-compat")
@ -606,7 +606,7 @@ mod tests {
App::new()
.service(web::scope("/app").service(web::resource("/path1").to(HttpResponse::Ok))),
)
.await;
.await;
let req = TestRequest::with_uri("/app/path1").to_request();
let resp = srv.call(req).await.unwrap();
@ -622,7 +622,7 @@ mod tests {
.service(web::resource("/").to(HttpResponse::Created)),
),
)
.await;
.await;
let req = TestRequest::with_uri("/app").to_request();
let resp = srv.call(req).await.unwrap();
@ -638,7 +638,7 @@ mod tests {
let srv = init_service(
App::new().service(web::scope("/app/").service(web::resource("").to(HttpResponse::Ok))),
)
.await;
.await;
let req = TestRequest::with_uri("/app").to_request();
let resp = srv.call(req).await.unwrap();
@ -655,7 +655,7 @@ mod tests {
App::new()
.service(web::scope("/app/").service(web::resource("/").to(HttpResponse::Ok))),
)
.await;
.await;
let req = TestRequest::with_uri("/app").to_request();
let resp = srv.call(req).await.unwrap();
@ -675,7 +675,7 @@ mod tests {
.route("/path1", web::delete().to(HttpResponse::Ok)),
),
)
.await;
.await;
let req = TestRequest::with_uri("/app/path1").to_request();
let resp = srv.call(req).await.unwrap();
@ -705,7 +705,7 @@ mod tests {
),
),
)
.await;
.await;
let req = TestRequest::with_uri("/app/path1").to_request();
let resp = srv.call(req).await.unwrap();
@ -733,7 +733,7 @@ mod tests {
.service(web::resource("/path1").to(HttpResponse::Ok)),
),
)
.await;
.await;
let req = TestRequest::with_uri("/app/path1")
.method(Method::POST)
@ -755,7 +755,7 @@ mod tests {
HttpResponse::Ok().body(format!("project: {}", &r.match_info()["project"]))
}),
)))
.await;
.await;
let req = TestRequest::with_uri("/ab-project1/path1").to_request();
let res = srv.call(req).await.unwrap();
@ -772,7 +772,7 @@ mod tests {
let srv = init_service(App::new().service(web::scope("/app").service(
web::scope("/t1").service(web::resource("/path1").to(HttpResponse::Created)),
)))
.await;
.await;
let req = TestRequest::with_uri("/app/t1/path1").to_request();
let resp = srv.call(req).await.unwrap();
@ -785,7 +785,7 @@ mod tests {
init_service(App::new().service(web::scope("/app").service(
web::scope("t1").service(web::resource("/path1").to(HttpResponse::Created)),
)))
.await;
.await;
let req = TestRequest::with_uri("/app/t1/path1").to_request();
let resp = srv.call(req).await.unwrap();
@ -803,7 +803,7 @@ mod tests {
),
),
)
.await;
.await;
let req = TestRequest::with_uri("/app/t1").to_request();
let resp = srv.call(req).await.unwrap();
@ -825,7 +825,7 @@ mod tests {
),
),
)
.await;
.await;
let req = TestRequest::with_uri("/app/t1/path1")
.method(Method::POST)
@ -847,7 +847,7 @@ mod tests {
HttpResponse::Created().body(format!("project: {}", &r.match_info()["project_id"]))
})),
)))
.await;
.await;
let req = TestRequest::with_uri("/app/project_1/path1").to_request();
let res = srv.call(req).await.unwrap();
@ -868,7 +868,7 @@ mod tests {
}),
)),
)))
.await;
.await;
let req = TestRequest::with_uri("/app/test/1/path1").to_request();
let res = srv.call(req).await.unwrap();
@ -891,7 +891,7 @@ mod tests {
}),
),
)
.await;
.await;
let req = TestRequest::with_uri("/app/path2").to_request();
let resp = srv.call(req).await.unwrap();
@ -912,7 +912,7 @@ mod tests {
ok(r.into_response(HttpResponse::MethodNotAllowed()))
}),
)
.await;
.await;
let req = TestRequest::with_uri("/non-exist").to_request();
let resp = srv.call(req).await.unwrap();
@ -939,7 +939,7 @@ mod tests {
.service(web::resource("/test").route(web::get().to(HttpResponse::Ok))),
),
)
.await;
.await;
let req = TestRequest::with_uri("/app/test").to_request();
let resp = call_service(&srv, req).await;
@ -963,7 +963,7 @@ mod tests {
.service(web::resource("/test").route(web::get().to(|| async { "hello" }))),
),
)
.await;
.await;
// test if `MessageBody::try_into_bytes()` is preserved across scope layer
use actix_http::body::MessageBody as _;
@ -990,7 +990,7 @@ mod tests {
.route("/test", web::get().to(HttpResponse::Ok)),
),
)
.await;
.await;
let req = TestRequest::with_uri("/app/test").to_request();
let resp = call_service(&srv, req).await;
@ -1025,7 +1025,7 @@ mod tests {
}),
),
)
.await;
.await;
let req = TestRequest::with_uri("/app/test").to_request();
let resp = call_service(&srv, req).await;
@ -1049,7 +1049,7 @@ mod tests {
}),
),
))
.await;
.await;
let req = TestRequest::with_uri("/app/t").to_request();
let resp = call_service(&srv, req).await;
@ -1069,7 +1069,7 @@ mod tests {
},
)),
))
.await;
.await;
let req = TestRequest::with_uri("/app/t").to_request();
let resp = call_service(&srv, req).await;
@ -1087,7 +1087,7 @@ mod tests {
}),
),
))
.await;
.await;
let req = TestRequest::with_uri("/app/t").to_request();
let resp = call_service(&srv, req).await;
@ -1099,7 +1099,7 @@ mod tests {
let srv = init_service(App::new().service(web::scope("/app").configure(|s| {
s.route("/path1", web::get().to(HttpResponse::Ok));
})))
.await;
.await;
let req = TestRequest::with_uri("/app/path1").to_request();
let resp = srv.call(req).await.unwrap();
@ -1113,7 +1113,7 @@ mod tests {
s.route("/", web::get().to(HttpResponse::Ok));
}));
})))
.await;
.await;
let req = TestRequest::with_uri("/app/v1/").to_request();
let resp = srv.call(req).await.unwrap();
@ -1134,7 +1134,7 @@ mod tests {
);
}));
})))
.await;
.await;
let req = TestRequest::with_uri("/app/v1/").to_request();
let resp = srv.call(req).await.unwrap();
@ -1152,7 +1152,7 @@ mod tests {
},
))),
)))
.await;
.await;
let req = TestRequest::with_uri("/a/b/c/test").to_request();
let resp = call_service(&srv, req).await;
@ -1179,7 +1179,7 @@ mod tests {
),
),
)
.await;
.await;
// note the unintuitive behavior with trailing slashes on scopes with dynamic segments
let req = TestRequest::with_uri("/a//b//c").to_request();
@ -1211,7 +1211,7 @@ mod tests {
),
),
)
.await;
.await;
let req = TestRequest::with_uri("/a/b/c").to_request();
let resp = call_service(&srv, req).await;