Skip to content

Instantly share code, notes, and snippets.

@jonwis
Created October 2, 2023 02:51
Show Gist options
  • Save jonwis/f130c55bfd08bc1b5b5922e423a1c385 to your computer and use it in GitHub Desktop.
Save jonwis/f130c55bfd08bc1b5b5922e423a1c385 to your computer and use it in GitHub Desktop.
Compile time sort and lookup example
#include <array>
#include <algorithm>
#include <string_view>
// From https://medium.com/@vgasparyan1995/compile-time-merge-sort-c-bb0ace62cc23
constexpr auto sort(const auto& arr)
{
auto result = arr;
auto sortless = [](auto const& a, auto const& b) { return a.first < b.first; };
std::sort(std::begin(result), std::end(result), sortless);
return result;
}
bool IsAppInAllowedList(std::wstring_view shortcut, std::wstring_view appid)
{
constexpr static std::array<std::pair<std::wstring_view, std::wstring_view>, 3> const arr{{
{ L"foo", L"bar" },
{ L"zot", L"quux" },
{ L"fleep", L"moo" },
}};
constexpr static auto const sorted = sort(arr);
auto findless = [](auto const& a, auto const& b) { return a.first < b; };
auto i = std::lower_bound(std::begin(sorted), std::end(sorted), shortcut, findless);
return i != std::end(sorted) && (i->first == shortcut);
}
bool quack() {
return IsAppInAllowedList(L"fleep", L"");
}
bool moo() {
return IsAppInAllowedList(L"moo", L"kitten");
}
@jonwis
Copy link
Author

jonwis commented Oct 2, 2023

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment