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 //! 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 { macro_rules! register {
(colon) => {{ (colon) => {{
@ -150,7 +150,7 @@ macro_rules! register {
}}; }};
} }
fn call() -> impl Iterator<Item=&'static str> { fn call() -> impl Iterator<Item = &'static str> {
let arr = [ let arr = [
"/authorizations", "/authorizations",
"/user/repos", "/user/repos",

View File

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

View File

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

View File

@ -1,7 +1,7 @@
use std::mem; use std::mem;
use crate::Path;
use crate::resource::ResourceMatchInfo; use crate::resource::ResourceMatchInfo;
use crate::Path;
// TODO: this trait is necessary, document it // TODO: this trait is necessary, document it
// see impl Resource for ServiceRequest // see impl Resource for ServiceRequest
@ -17,7 +17,11 @@ pub trait Resource {
ResourceMatchInfo::Static { matched_len } => { ResourceMatchInfo::Static { matched_len } => {
path.skip(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() { for i in 0..matched_vars.len() {
path.add(matched_vars[i], mem::take(&mut segments[i])); 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> { impl<T, U> Router<T, U> {
/// Constructs new `RouterBuilder` with empty route list. /// Constructs new `RouterBuilder` with empty route list.
pub fn build() -> RouterBuilder<T, U> { 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). /// 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, val: T,
ctx: U, ctx: U,
) -> (&mut ResourceDef, &mut T, &mut U) { ) -> (&mut ResourceDef, &mut T, &mut U) {
if let Some((_, path_conflicts)) = self.path_conflicts.iter_mut() if let Some((_, path_conflicts)) = self
.find(|(current_rdef, _)| rdef.eq(current_rdef)) { .path_conflicts
.iter_mut()
.find(|(current_rdef, _)| rdef.eq(current_rdef))
{
*path_conflicts += 1; *path_conflicts += 1;
} else { } else {
self.path_conflicts.push((rdef.clone(), 1)); self.path_conflicts.push((rdef.clone(), 1));
@ -135,7 +141,9 @@ impl<T, U> RouterBuilder<T, U> {
/// Finish configuration and create router instance. /// Finish configuration and create router instance.
pub fn finish(self) -> Router<T, U> { 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) .map(|(_, path_conflicts)| *path_conflicts)
.max() .max()
.unwrap_or(1); .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
assert!(router.recognize_fn(&mut Path::new("/test2"), failures_until_fn_builder(2)).is_some()); .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}, config::{AppConfig, AppService},
data::FnDataFactory, data::FnDataFactory,
dev::Extensions, dev::Extensions,
Error,
guard::Guard, guard::Guard,
HttpResponse,
request::{HttpRequest, HttpRequestPool}, request::{HttpRequest, HttpRequestPool},
rmap::ResourceMap, service::{ rmap::ResourceMap,
service::{
AppServiceFactory, BoxedHttpService, BoxedHttpServiceFactory, ServiceRequest, AppServiceFactory, BoxedHttpService, BoxedHttpServiceFactory, ServiceRequest,
ServiceResponse, ServiceResponse,
}, },
Error, HttpResponse,
}; };
/// Service factory to convert [`Request`] to a [`ServiceRequest<S>`]. /// Service factory to convert [`Request`] to a [`ServiceRequest<S>`].
@ -29,10 +29,10 @@ pub struct AppInit<T, B>
where where
T: ServiceFactory< T: ServiceFactory<
ServiceRequest, ServiceRequest,
Config=(), Config = (),
Response=ServiceResponse<B>, Response = ServiceResponse<B>,
Error=Error, Error = Error,
InitError=(), InitError = (),
>, >,
{ {
pub(crate) endpoint: T, pub(crate) endpoint: T,
@ -48,10 +48,10 @@ impl<T, B> ServiceFactory<Request> for AppInit<T, B>
where where
T: ServiceFactory< T: ServiceFactory<
ServiceRequest, ServiceRequest,
Config=(), Config = (),
Response=ServiceResponse<B>, Response = ServiceResponse<B>,
Error=Error, Error = Error,
InitError=(), InitError = (),
>, >,
T::Future: 'static, T::Future: 'static,
{ {
@ -145,7 +145,7 @@ where
/// Wraps a service receiving a [`ServiceRequest`] into one receiving a [`Request`]. /// Wraps a service receiving a [`ServiceRequest`] into one receiving a [`Request`].
pub struct AppInitService<T, B> pub struct AppInitService<T, B>
where where
T: Service<ServiceRequest, Response=ServiceResponse<B>, Error=Error>, T: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
{ {
service: T, service: T,
app_data: Rc<Extensions>, app_data: Rc<Extensions>,
@ -190,7 +190,7 @@ impl AppInitServiceState {
impl<T, B> Service<Request> for AppInitService<T, B> impl<T, B> Service<Request> for AppInitService<T, B>
where where
T: Service<ServiceRequest, Response=ServiceResponse<B>, Error=Error>, T: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
{ {
type Response = ServiceResponse<B>; type Response = ServiceResponse<B>;
type Error = T::Error; type Error = T::Error;
@ -230,7 +230,7 @@ where
impl<T, B> Drop for AppInitService<T, B> impl<T, B> Drop for AppInitService<T, B>
where where
T: Service<ServiceRequest, Response=ServiceResponse<B>, Error=Error>, T: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
{ {
fn drop(&mut self) { fn drop(&mut self) {
self.app_state.pool().clear(); self.app_state.pool().clear();
@ -347,15 +347,15 @@ impl ServiceFactory<ServiceRequest> for AppEntry {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use std::sync::{ use std::sync::{
Arc,
atomic::{AtomicBool, Ordering}, atomic::{AtomicBool, Ordering},
Arc,
}; };
use actix_service::Service; use actix_service::Service;
use crate::{ use crate::{
App, test::{init_service, TestRequest},
HttpResponse, test::{init_service, TestRequest}, web, web, App, HttpResponse,
}; };
struct DropData(Arc<AtomicBool>); struct DropData(Arc<AtomicBool>);

View File

@ -14,13 +14,13 @@ use crate::{
config::ServiceConfig, config::ServiceConfig,
data::Data, data::Data,
dev::AppService, dev::AppService,
Error,
guard::Guard, guard::Guard,
Resource, rmap::ResourceMap,
rmap::ResourceMap, Route, service::{ service::{
AppServiceFactory, BoxedHttpService, BoxedHttpServiceFactory, HttpServiceFactory, AppServiceFactory, BoxedHttpService, BoxedHttpServiceFactory, HttpServiceFactory,
ServiceFactoryWrapper, ServiceRequest, ServiceResponse, ServiceFactoryWrapper, ServiceRequest, ServiceResponse,
}, },
Error, Resource, Route,
}; };
type Guards = Vec<Box<dyn Guard>>; type Guards = Vec<Box<dyn Guard>>;
@ -86,7 +86,7 @@ impl Scope {
impl<T> Scope<T> impl<T> Scope<T>
where where
T: ServiceFactory<ServiceRequest, Config=(), Error=Error, InitError=()>, T: ServiceFactory<ServiceRequest, Config = (), Error = Error, InitError = ()>,
{ {
/// Add match guard to a scope. /// Add match guard to a scope.
/// ///
@ -273,7 +273,7 @@ where
pub fn default_service<F, U>(mut self, f: F) -> Self pub fn default_service<F, U>(mut self, f: F) -> Self
where where
F: IntoServiceFactory<U, ServiceRequest>, F: IntoServiceFactory<U, ServiceRequest>,
U: ServiceFactory<ServiceRequest, Config=(), Response=ServiceResponse, Error=Error> U: ServiceFactory<ServiceRequest, Config = (), Response = ServiceResponse, Error = Error>
+ 'static, + 'static,
U::InitError: fmt::Debug, U::InitError: fmt::Debug,
{ {
@ -301,19 +301,19 @@ where
) -> Scope< ) -> Scope<
impl ServiceFactory< impl ServiceFactory<
ServiceRequest, ServiceRequest,
Config=(), Config = (),
Response=ServiceResponse<B>, Response = ServiceResponse<B>,
Error=Error, Error = Error,
InitError=(), InitError = (),
>, >,
> >
where where
M: Transform< M: Transform<
T::Service, T::Service,
ServiceRequest, ServiceRequest,
Response=ServiceResponse<B>, Response = ServiceResponse<B>,
Error=Error, Error = Error,
InitError=(), InitError = (),
> + 'static, > + 'static,
B: MessageBody, B: MessageBody,
{ {
@ -344,15 +344,15 @@ where
) -> Scope< ) -> Scope<
impl ServiceFactory< impl ServiceFactory<
ServiceRequest, ServiceRequest,
Config=(), Config = (),
Response=ServiceResponse<B>, Response = ServiceResponse<B>,
Error=Error, Error = Error,
InitError=(), InitError = (),
>, >,
> >
where where
F: Fn(ServiceRequest, &T::Service) -> R + Clone + 'static, F: Fn(ServiceRequest, &T::Service) -> R + Clone + 'static,
R: Future<Output=Result<ServiceResponse<B>, Error>>, R: Future<Output = Result<ServiceResponse<B>, Error>>,
B: MessageBody, B: MessageBody,
{ {
Scope { Scope {
@ -372,10 +372,10 @@ impl<T, B> HttpServiceFactory for Scope<T>
where where
T: ServiceFactory< T: ServiceFactory<
ServiceRequest, ServiceRequest,
Config=(), Config = (),
Response=ServiceResponse<B>, Response = ServiceResponse<B>,
Error=Error, Error = Error,
InitError=(), InitError = (),
> + 'static, > + 'static,
B: MessageBody + 'static, B: MessageBody + 'static,
{ {
@ -554,14 +554,14 @@ mod tests {
use bytes::Bytes; use bytes::Bytes;
use crate::{ use crate::{
App,
guard, guard,
http::{ http::{
header::{self, HeaderValue}, header::{self, HeaderValue},
Method, StatusCode, Method, StatusCode,
}, },
HttpMessage, middleware::DefaultHeaders,
HttpRequest, HttpResponse, middleware::DefaultHeaders, test::{assert_body_eq, call_service, init_service, read_body, TestRequest}, web, test::{assert_body_eq, call_service, init_service, read_body, TestRequest},
web, App, HttpMessage, HttpRequest, HttpResponse,
}; };
use super::*; use super::*;
@ -576,10 +576,10 @@ mod tests {
fn my_scope_2() -> Scope< fn my_scope_2() -> Scope<
impl ServiceFactory< impl ServiceFactory<
ServiceRequest, ServiceRequest,
Config=(), Config = (),
Response=ServiceResponse<impl MessageBody>, Response = ServiceResponse<impl MessageBody>,
Error=Error, Error = Error,
InitError=(), InitError = (),
>, >,
> { > {
web::scope("/test-compat") web::scope("/test-compat")