Strings and Iterators

In this exercise, you are implementing a routing component of a web server. The server is configured with a number of path prefixes which are matched against request paths. The path prefixes can contain a wildcard character which matches a full segment. See the unit tests below.

Copy the following code to https://play.rust-lang.org/ and make the tests pass. Try avoiding allocating a Vec for your intermediate results:

  1. #![allow(unused)]
  2. fn main() {
  3. // TODO: remove this when you're done with your implementation.
  4. #![allow(unused_variables, dead_code)]
  5. pub fn prefix_matches(prefix: &str, request_path: &str) -> bool {
  6. unimplemented!()
  7. }
  8. #[test]
  9. fn test_matches_without_wildcard() {
  10. assert!(prefix_matches("/v1/publishers", "/v1/publishers"));
  11. assert!(prefix_matches("/v1/publishers", "/v1/publishers/abc-123"));
  12. assert!(prefix_matches("/v1/publishers", "/v1/publishers/abc/books"));
  13. assert!(!prefix_matches("/v1/publishers", "/v1"));
  14. assert!(!prefix_matches("/v1/publishers", "/v1/publishersBooks"));
  15. assert!(!prefix_matches("/v1/publishers", "/v1/parent/publishers"));
  16. }
  17. #[test]
  18. fn test_matches_with_wildcard() {
  19. assert!(prefix_matches(
  20. "/v1/publishers/*/books",
  21. "/v1/publishers/foo/books"
  22. ));
  23. assert!(prefix_matches(
  24. "/v1/publishers/*/books",
  25. "/v1/publishers/bar/books"
  26. ));
  27. assert!(prefix_matches(
  28. "/v1/publishers/*/books",
  29. "/v1/publishers/foo/books/book1"
  30. ));
  31. assert!(!prefix_matches("/v1/publishers/*/books", "/v1/publishers"));
  32. assert!(!prefix_matches(
  33. "/v1/publishers/*/books",
  34. "/v1/publishers/foo/booksByAuthor"
  35. ));
  36. }
  37. }