mirror of
https://github.com/google/comprehensive-rust.git
synced 2024-12-15 22:37:28 +02:00
"Strings and Iterators" solution that uses let-else (#833)
Add "Strings and Iterators" solution that uses let-else.
This commit is contained in:
parent
b83dd9a1f9
commit
0c867c952f
@ -15,23 +15,25 @@
|
|||||||
// ANCHOR: prefix_matches
|
// ANCHOR: prefix_matches
|
||||||
pub fn prefix_matches(prefix: &str, request_path: &str) -> bool {
|
pub fn prefix_matches(prefix: &str, request_path: &str) -> bool {
|
||||||
// ANCHOR_END: prefix_matches
|
// ANCHOR_END: prefix_matches
|
||||||
let prefixes = prefix.split('/');
|
|
||||||
let request_paths = request_path
|
|
||||||
.split('/')
|
|
||||||
.map(|p| Some(p))
|
|
||||||
.chain(std::iter::once(None));
|
|
||||||
|
|
||||||
for (prefix, request_path) in prefixes.zip(request_paths) {
|
let mut request_segments = request_path.split('/');
|
||||||
match request_path {
|
|
||||||
Some(request_path) => {
|
for prefix_segment in prefix.split('/') {
|
||||||
if (prefix != "*") && (prefix != request_path) {
|
let Some(request_segment) = request_segments.next() else {
|
||||||
return false;
|
return false;
|
||||||
}
|
};
|
||||||
}
|
if request_segment != prefix_segment && prefix_segment != "*" {
|
||||||
None => return false,
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
true
|
true
|
||||||
|
|
||||||
|
// Alternatively, Iterator::zip() lets us iterate simultaneously over prefix
|
||||||
|
// and request segments. The zip() iterator is finished as soon as one of
|
||||||
|
// the source iterators is finished, but we need to iterate over all request
|
||||||
|
// segments. A neat trick that makes zip() work is to use map() and chain()
|
||||||
|
// to produce an iterator that returns Some(str) for each pattern segments,
|
||||||
|
// and then returns None indefinitely.
|
||||||
}
|
}
|
||||||
|
|
||||||
// ANCHOR: unit-tests
|
// ANCHOR: unit-tests
|
||||||
|
Loading…
Reference in New Issue
Block a user