Skip to content

Instantly share code, notes, and snippets.

@ivan
Last active November 3, 2019 09:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ivan/f196cd8916aff2133599a5d029608a9d to your computer and use it in GitHub Desktop.
Save ivan/f196cd8916aff2133599a5d029608a9d to your computer and use it in GitHub Desktop.
Elixir vs Rust: delete all ?ei= or &ei= from URL
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
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()
}
@ivan
Copy link
Author

ivan commented Nov 3, 2019

The Rust version is split up into two functions to avoid a silly drop(query_pairs)

@ivan
Copy link
Author

ivan commented Nov 3, 2019

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