Skip to content

Commit

Permalink
Optimize decoding
Browse files Browse the repository at this point in the history
  • Loading branch information
CathalMullan committed Aug 19, 2024
1 parent e476dd9 commit dfe83cf
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 12 deletions.
23 changes: 17 additions & 6 deletions src/path.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,30 @@
use crate::{decode::percent_decode, errors::decode::DecodeError};
use std::borrow::Cow;

pub struct Path {
pub inner: Vec<u8>,
pub struct Path<'a> {
original: Cow<'a, [u8]>,
decoded: Option<Vec<u8>>,
}

impl Path {
impl<'a> Path<'a> {
#[must_use]
pub fn new(path: &str) -> Self {
pub const fn new(path: &'a str) -> Self {
Self {
inner: path.as_bytes().to_vec(),
original: Cow::Borrowed(path.as_bytes()),
decoded: None,
}
}

pub fn percent_decode(&mut self) -> Result<(), DecodeError> {
self.inner = percent_decode(&self.inner)?;
if self.decoded.is_none() {
self.decoded = Some(percent_decode(&self.original)?);
}

Ok(())
}

#[must_use]
pub fn as_bytes(&self) -> &[u8] {
self.decoded.as_deref().unwrap_or(&self.original)
}
}
6 changes: 1 addition & 5 deletions src/router.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,10 +131,6 @@ impl<T> Router<T> {
self.root.delete(&mut parts)
}

// FIXME: Let's try a 'Path' style approach to the returned value.
// Like what actix/ntex does.
// Maybe instead of returning anything, we just set something everything in Path?
// i.e. merge Match with Path?
pub fn search<'k, 'v>(
&'k self,
path: &'v mut Path,
Expand All @@ -146,7 +142,7 @@ impl<T> Router<T> {
let mut parameters = smallvec![];
let Some(node) = self
.root
.search(&path.inner, &mut parameters, &self.constraints)
.search(path.as_bytes(), &mut parameters, &self.constraints)
else {
return Ok(None);
};
Expand Down
2 changes: 1 addition & 1 deletion tests/poem.rs
Original file line number Diff line number Diff line change
Expand Up @@ -512,7 +512,7 @@ fn test_percent_decoded() -> Result<(), Box<dyn Error>> {
"id" => "abc"
}
}
"/a/你好" => {
"/a/%E4%BD%A0%E5%A5%BD" => {
path: "/a/{id}",
value: 1,
params: {
Expand Down

0 comments on commit dfe83cf

Please sign in to comment.