Last active
November 3, 2019 09:25
-
-
Save ivan/f196cd8916aff2133599a5d029608a9d to your computer and use it in GitHub Desktop.
Elixir vs Rust: delete all ?ei= or &ei= from URL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defp sanitize_url(s) do | |
uri = URI.parse(s) | |
new_query = case uri.query do | |
nil -> nil | |
query -> | |
query | |
|> URI.decode_query() | |
|> Map.delete("ei") | |
|> URI.encode_query() | |
end | |
new_uri = %{uri | query: new_query} | |
URI.to_string(new_uri) | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fn set_query_pairs(url: &mut Url, pairs: Vec<(String, String)>) { | |
let mut query_pairs = url.query_pairs_mut(); | |
query_pairs.clear(); | |
for (k, v) in pairs.iter() { | |
query_pairs.append_pair(k, v); | |
} | |
} | |
pub(crate) fn sanitize_url(url: &str) -> String { | |
let mut url = Url::parse(url).unwrap(); | |
let wanted_pairs = | |
url.query_pairs() | |
.filter_map(|(k, v)| { | |
match k { | |
Cow::Borrowed("ei") => None, | |
_ => Some((k.to_string(), v.to_string())) | |
} | |
}) | |
.collect::<Vec<_>>(); | |
set_query_pairs(&mut url, wanted_pairs); | |
url.to_string() | |
} |
Elixir disadvantages: it can't process more than one of the same query key:
iex(5)> URI.decode_query("a=3&a=4")
%{"a" => "4"}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The Rust version is split up into two functions to avoid a silly
drop(query_pairs)