Skip to content

Commit 68582ba

Browse files
Reject non integer sort keys in stable_counting_sort with a static_assert
1 parent 20729e8 commit 68582ba

1 file changed

Lines changed: 8 additions & 0 deletions

File tree

libs/libvtrutil/src/vtr_sort.h

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
#include <iterator>
1515
#include <limits>
1616
#include <tuple>
17+
#include <type_traits>
1718
#include <utility>
1819
#include <vector>
1920

@@ -48,6 +49,13 @@ namespace vtr {
4849
template<typename InIt, typename OutIt, typename KeyFn>
4950
requires std::forward_iterator<InIt> && std::random_access_iterator<OutIt>
5051
void stable_counting_sort(InIt first, InIt last, OutIt out, size_t num_keys, KeyFn key_of) {
52+
// The key must be an integer like value: a built in integer, an enum, or a
53+
// class such as vtr::StrongId that converts explicitly to size_t. Floating
54+
// point keys would be silently truncated by the cast below, so reject them.
55+
using Key = std::remove_cvref_t<std::invoke_result_t<KeyFn&, std::iter_reference_t<InIt>>>;
56+
static_assert((std::is_constructible_v<size_t, Key> || std::is_enum_v<Key>) && !std::is_floating_point_v<Key>,
57+
"Sort key must be an integer, enum, or a type explicitly convertible to size_t");
58+
5159
// The sort runs in three passes:
5260
// 1. Count how many elements have each key.
5361
// 2. Prefix sum the counts so that each key maps to the output position

0 commit comments

Comments
 (0)