Trait front_line::FromRoute
source · pub trait FromRoute<'de>: Sized {
// Required method
fn parse_path_variable(slice: &'de str) -> Option<Self>;
}
Expand description
A trait to enable zero-copy parsing from route paths.
This trait is designed as an alternative to FromStr
to support both zero-copy and copy parsing.
It’s especially useful for HTTP route parsing where parts of the route can be efficiently parsed
without the need to allocate memory for every segment of the route. This can lead to performance
benefits, especially in web applications where route parsing happens frequently.
Implement this trait for types that need to be parsed from route paths.
Examples
// Suppose you have a route segment "/user/42"
// and you want to directly parse "42" into a UserId type.
use front_line_router::FromRoute;
struct UserId(u32);
impl<'de> FromRoute<'de> for UserId {
fn parse_path_variable(slice: &'de str) -> Option<Self> {
slice.parse().map(UserId).ok()
}
}
Zero-copy example:
// For cases where the exact slice from the route path can be directly used,
// the `FromRoute` trait allows efficient zero-copy parsing.
use front_line_router::FromRoute;
struct UserName<'a>(&'a str);
impl<'de> FromRoute<'de> for UserName<'de> {
fn parse_path_variable(slice: &'de str) -> Option<Self> {
if slice.is_empty() {
None
} else {
Some(UserName(slice))
}
}
}
// Given a route segment "/user/alice", "alice" can be parsed directly as UserName
// without creating a new String.
Required Methods§
Object Safety§
This trait is not object safe.