Created
December 28, 2023 19:20
-
-
Save olback/de8e22033fb53595427e50c4d1d712bb to your computer and use it in GitHub Desktop.
Simple query-parameter parser in c++
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
#include <unordered_map> | |
#include <iostream> | |
// Parse URI-query parameters into a unordered_map, borrowing the input string. String must be null-terminated. | |
template <typename C> | |
std::unordered_map<std::basic_string_view<C>, std::basic_string_view<C>> parse_query_string(const C *query_string) | |
{ | |
std::unordered_map<std::basic_string_view<C>, std::basic_string_view<C>> query_map; | |
if (query_string == nullptr) | |
{ | |
return query_map; | |
} | |
if (*query_string == '\0') | |
{ | |
return query_map; | |
} | |
const C *key = query_string + 1; | |
const C *value = nullptr; | |
const C *p = key; | |
while (true) | |
{ | |
if (*p == '=') | |
{ | |
value = p + 1; | |
} | |
else if (*p == '&' || *p == '\0') | |
{ | |
if (value == nullptr) | |
{ | |
if (p - key != 0) | |
{ | |
query_map.emplace(std::basic_string_view<C>(key, p - key), std::basic_string_view<C>()); | |
} | |
} | |
else | |
{ | |
query_map[std::basic_string_view<C>(key, value - key - 1)] = std::basic_string_view<C>(value, p - value); | |
} | |
key = p + 1; | |
value = nullptr; | |
} | |
if (*p == '\0') | |
{ | |
break; | |
} | |
else | |
{ | |
p++; | |
} | |
} | |
return query_map; | |
} | |
int main(int, char **, char **) | |
{ | |
const wchar_t *query_string = L"?cool4&query=hello+world&cool2&lang=en&enc=utf-8&cool=yes&cool3"; | |
auto query_map = parse_query_string(query_string); | |
for (auto &pair : query_map) | |
{ | |
std::wcout << pair.first << L": " << pair.second << std::endl; | |
} | |
return 0; | |
} |
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
CLFAGS=-std=c++17 -g -O1 -flto -fPIE -pie -Wall -Wextra -fno-omit-frame-pointer -fsanitize=address,leak,undefined | |
SRC=main.cpp | |
CXX=clang++ | |
query-param-thing: $(SRC) | |
$(CXX) $(CLFAGS) -o query-param-thing $(SRC) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment