Day 2 Afternoon Exercises

    (back to exercise)

    1. //
    2. // Licensed under the Apache License, Version 2.0 (the "License");
    3. // you may not use this file except in compliance with the License.
    4. // You may obtain a copy of the License at
    5. //
    6. // http://www.apache.org/licenses/LICENSE-2.0
    7. //
    8. // Unless required by applicable law or agreed to in writing, software
    9. // distributed under the License is distributed on an "AS IS" BASIS,
    10. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    11. // See the License for the specific language governing permissions and
    12. // limitations under the License.
    13. // ANCHOR: prefix_matches
    14. pub fn prefix_matches(prefix: &str, request_path: &str) -> bool {
    15. // ANCHOR_END: prefix_matches
    16. let prefixes = prefix.split('/');
    17. let request_paths = request_path
    18. .split('/')
    19. .map(|p| Some(p))
    20. .chain(std::iter::once(None));
    21. for (prefix, request_path) in prefixes.zip(request_paths) {
    22. Some(request_path) => {
    23. if (prefix != "*") && (prefix != request_path) {
    24. return false;
    25. }
    26. }
    27. None => return false,
    28. }
    29. }
    30. true
    31. }
    32. // ANCHOR: unit-tests
    33. #[test]
    34. fn test_matches_without_wildcard() {
    35. assert!(prefix_matches("/v1/publishers", "/v1/publishers"));
    36. assert!(prefix_matches("/v1/publishers", "/v1/publishers/abc-123"));
    37. assert!(prefix_matches("/v1/publishers", "/v1/publishers/abc/books"));
    38. assert!(!prefix_matches("/v1/publishers", "/v1"));
    39. assert!(!prefix_matches("/v1/publishers", "/v1/publishersBooks"));
    40. assert!(!prefix_matches("/v1/publishers", "/v1/parent/publishers"));
    41. }
    42. fn test_matches_with_wildcard() {
    43. assert!(prefix_matches(
    44. "/v1/publishers/*/books",
    45. "/v1/publishers/foo/books"
    46. ));
    47. assert!(prefix_matches(
    48. "/v1/publishers/*/books",
    49. "/v1/publishers/bar/books"
    50. ));
    51. assert!(prefix_matches(
    52. "/v1/publishers/*/books",
    53. "/v1/publishers/foo/books/book1"
    54. ));
    55. assert!(!prefix_matches("/v1/publishers/*/books", "/v1/publishers"));
    56. assert!(!prefix_matches(
    57. "/v1/publishers/*/books",
    58. "/v1/publishers/foo/booksByAuthor"
    59. ));
    60. }
    61. // ANCHOR_END: unit-tests
    62. fn main() {}