Skip to content

mankinskin/enum_paths

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

32 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

enum_paths

Define "/" separated paths with nested enums

#[derive(Debug, PartialEq, AsPath)]
enum Route {
    Users(UserRoute),
}

#[derive(Debug, PartialEq, AsPath)]
enum UserRoute {
    #[name = ""]
    Profile(u32),
    List,
}

And convert between them:

#[test]
fn as_path() {
    assert_eq!(
        Route::Users(UserRoute::Profile(1)).as_path(),
        "/users/1".to_string(),
    );
    assert_eq!(
        Route::Users(UserRoute::List).as_path(),
        "/users/list".to_string(),
    );
}
#[test]
fn parse_path() {
    assert_eq!(
        ParsePath::parse_path("/users/1").unwrap(),
        Route::Users(UserRoute::Profile(1))
    );
    assert_eq!(
        ParsePath::parse_path("/users/list").unwrap(),
        Route::Users(UserRoute::List)
    );
}

Todo:

  • more tests

How to use it

Derive AsPath and ParsePath using the derive macro. Override names using attributes (the default is to convert variant names to snake_case):

#[derive(AsPath)]
enum Route {
    MyRoute, // converts to "my_route"
    
    #[name = "new_name"]
    OldName, // would have been "old_name"
    
    #[name = "prefix"]
    Nested(u32), // turns out as "/prefix/{u32}" instead of "/nested/{u32}"
    
    #[name = ""]
    MustBeAtTheEnd, // a (single) unit variant with no name must be declared last
}

You're good to go!

assert_eq!(
    Route::MyRoute.as_path(),
    "/my_route".to_string(),
);

match Route::parse_path("/") {
    Ok(route) => log!(route),   // Route::MustBeAtTheEnd
    Err(err) => error!(err),
}

About

Derives trait to convert between nested enums and "/" separated paths

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages