servo: Merge #5403 - Improve and fix default_path cookie algorithm (from frewsxcv:cookie-default-path); r=jdm

* Previously, the function returned an owned String, which is not
  necessary, so now it returns a slice
* Steps have now been documented/labeled
* The last step of the algorithm was incorrect; it would only slice the
  path if the "/" was the last character, which is not what the spec
  says. The spec says to slice up until (but not including) the last
  "/". Also added a regression test for this.

Source-Repo: https://github.com/servo/servo
Source-Revision: 0d00e37c23dce23cad5b98f82ae711675f324810
This commit is contained in:
Corey Farwell 2015-03-30 08:52:06 -06:00
Родитель ed80e888c3
Коммит 7d70a4f3b7
1 изменённых файлов: 16 добавлений и 9 удалений

Просмотреть файл

@ -71,7 +71,7 @@ impl Cookie {
if path.is_empty() || path.char_at(0) != '/' {
let url_path = request.serialize_path();
let url_path = url_path.as_ref().map(|path| &**path);
path = Cookie::default_path(url_path.unwrap_or(""));
path = Cookie::default_path(url_path.unwrap_or("")).to_owned();
}
cookie.path = Some(path);
@ -96,15 +96,21 @@ impl Cookie {
}
// http://tools.ietf.org/html/rfc6265#section-5.1.4
fn default_path(request_path: &str) -> String {
if request_path == "" || request_path.char_at(0) != '/' ||
request_path.chars().filter(|&c| c == '/').count() == 1 {
"/".to_owned()
} else if request_path.ends_with("/") {
request_path[..request_path.len() - 1].to_owned()
} else {
request_path.to_owned()
fn default_path(request_path: &str) -> &str {
// Step 2
if request_path.is_empty() || !request_path.starts_with("/") {
return "/";
}
// Step 3
let rightmost_slash_idx = request_path.rfind("/").unwrap();
if rightmost_slash_idx == 0 {
// There's only one slash; it's the first character
return "/";
}
// Step 4
&request_path[..rightmost_slash_idx]
}
// http://tools.ietf.org/html/rfc6265#section-5.1.4
@ -180,6 +186,7 @@ fn test_domain_match() {
#[test]
fn test_default_path() {
assert!(&*Cookie::default_path("/foo/bar/baz/") == "/foo/bar/baz");
assert!(&*Cookie::default_path("/foo/bar/baz") == "/foo/bar");
assert!(&*Cookie::default_path("/foo/") == "/foo");
assert!(&*Cookie::default_path("/foo") == "/");
assert!(&*Cookie::default_path("/") == "/");