Skip to content

Commit 4a7eced

Browse files
committed
fix: conform to url specification for set
1 parent 51a2eab commit 4a7eced

File tree

2 files changed

+22
-5
lines changed

2 files changed

+22
-5
lines changed

src/url_search_params.cpp

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -34,12 +34,17 @@ void url_search_params::sort() {
3434

3535
void url_search_params::set(const std::string_view key,
3636
const std::string_view value) {
37-
params.erase(
38-
std::remove_if(params.begin(), params.end(),
39-
[&key](auto &param) { return param.first == key; }),
40-
params.end());
37+
const auto find = [&key](auto &param) { return param.first == key; };
38+
39+
auto it = std::find_if(params.begin(), params.end(), find);
4140

42-
params.emplace_back(key, value);
41+
if (it == params.end()) {
42+
params.emplace_back(key, value);
43+
} else {
44+
it->second = value;
45+
params.erase(std::remove_if(std::next(it), params.end(), find),
46+
params.end());
47+
}
4348
}
4449

4550
std::string url_search_params::to_string() {

tests/url_search_params.cpp

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,18 @@ TEST(url_search_params, set) {
2929
search_params.set("key1", "hello");
3030
ASSERT_EQ(search_params.size(), 1);
3131
ASSERT_EQ(search_params.to_string(), "key1=hello");
32+
33+
// reset to initial state
34+
search_params.remove("key1");
35+
search_params.append("key1", "value1");
36+
search_params.append("key1", "value2");
37+
search_params.append("key2", "value1");
38+
search_params.set("key1", "value3");
39+
ASSERT_EQ(search_params.size(), 2);
40+
ASSERT_EQ(search_params.to_string(), "key1=value3&key2=value1");
41+
search_params.set("key1", "value4");
42+
ASSERT_EQ(search_params.to_string(), "key1=value4&key2=value1");
43+
3244
SUCCEED();
3345
}
3446

0 commit comments

Comments
 (0)