From 6ee00ad1bd9aeeef56229decf23a37029cee1310 Mon Sep 17 00:00:00 2001
From: Yutaro Ohno <yutaro.ono.418@gmail.com>
Date: Wed, 14 Jun 2023 21:28:51 +0900
Subject: [PATCH] Only strip spaces from opaque path when both query and
 fragment are null

In the current behavior, when `url.set_query(None)` is called to remove
the query from a opaque path, spaces are stripped even if a fragment
remains.

As the spec [1] says, strip spaces only when both the query and fragment
are null. For example:

```
let mut url = URL::parse("data:space   ?query#hash");
url.set_query(None);
assert_eq!(url.as_str(), "data:space   #hash")
```

[1]: https://url.spec.whatwg.org/#potentially-strip-trailing-spaces-from-an-opaque-path
---
 url/src/lib.rs    | 4 ++--
 url/tests/unit.rs | 9 +++++++++
 2 files changed, 11 insertions(+), 2 deletions(-)

diff --git a/url/src/lib.rs b/url/src/lib.rs
index ad3c89001..4ae09c463 100644
--- a/url/src/lib.rs
+++ b/url/src/lib.rs
@@ -1552,12 +1552,12 @@ impl Url {
                     parser::Input::trim_tab_and_newlines(input, vfn),
                 )
             });
+            self.restore_already_parsed_fragment(fragment);
         } else {
             self.query_start = None;
+            self.restore_already_parsed_fragment(fragment);
             self.strip_trailing_spaces_from_opaque_path();
         }
-
-        self.restore_already_parsed_fragment(fragment);
     }
 
     /// Manipulate this URL’s query string, viewed as a sequence of name/value pairs
diff --git a/url/tests/unit.rs b/url/tests/unit.rs
index 6cb0f37fe..9c8b350ae 100644
--- a/url/tests/unit.rs
+++ b/url/tests/unit.rs
@@ -43,6 +43,15 @@ fn test_strip_trailing_spaces_from_opaque_path() {
     let mut url: Url = "data:space   #hash".parse().unwrap();
     url.set_fragment(None);
     assert_eq!(url.as_str(), "data:space");
+
+    // Strip spaces only when both query and fragment are null.
+    let mut url: Url = "data:space   ?query#hash".parse().unwrap();
+    url.set_query(None);
+    assert_eq!(url.as_str(), "data:space   #hash");
+
+    let mut url: Url = "data:space   ?query#hash".parse().unwrap();
+    url.set_fragment(None);
+    assert_eq!(url.as_str(), "data:space   ?query");
 }
 
 #[test]