Shamrock 2025.10.0
Astrophysical Code
Loading...
Searching...
No Matches
binary_range_search.hpp
Go to the documentation of this file.
1// -------------------------------------------------------//
2//
3// SHAMROCK code for hydrodynamics
4// Copyright (c) 2021-2026 Timothée David--Cléris <tim.shamrock@proton.me>
5// SPDX-License-Identifier: CeCILL Free Software License Agreement v2.1
6// Shamrock is licensed under the CeCILL 2.1 License, see LICENSE for more information
7//
8// -------------------------------------------------------//
9
10#pragma once
11
19#include "shambase/assert.hpp"
22
23namespace shamalgs::primitives {
24
58 template<class Tkey>
59 constexpr void binary_range_search(
60 const Tkey *__restrict__ key,
61 u32 first,
62 u32 last,
63 const Tkey &value_min,
64 const Tkey &value_max,
65 u32 &inf,
66 u32 &sup) {
67
68 SHAM_ASSERT(value_min <= value_max);
69 SHAM_ASSERT((first < last) ? key[first] <= value_min : true);
70 SHAM_ASSERT((first < last) ? key[last - 1] >= value_max : true);
71
72 inf = binary_search_lower_bound(key, first, last, value_min);
73 sup = binary_search_upper_bound(key, first, last, value_max);
74
75 // std::lower_bound and std::upper_bound are quirky:
76 // - std::lower_bound returns the first such that >= value_min (searching 8 in [7,9] return
77 // 1 where we want 0)
78 // - std::upper_bound returns the first such that > value_max (searching 8 in
79 // [7,8,9] return 2 where we want 1)
80 // The following adjust that to the range with expect in this function
81 if (inf > first && inf < last) {
82 inf -= (key[inf] > value_min);
83 }
84 if (sup > first && sup <= last) {
85 sup -= (key[sup - 1] == value_max);
86 }
87 }
88
89} // namespace shamalgs::primitives
std::uint32_t u32
32 bit unsigned integer
Shamrock assertion utility.
#define SHAM_ASSERT(x)
Shorthand for SHAM_ASSERT_NAMED without a message.
Definition assert.hpp:67
GPU compatible implementation of std::lower_bound.
namespace for primitive algorithm (e.g. sort, scan, reductions, ...)
constexpr u32 binary_search_upper_bound(const Tkey *__restrict__ key, u32 first, u32 last, const Tkey &value)
GPU compatible implementation of std::upper_bound.
constexpr void binary_range_search(const Tkey *__restrict__ key, u32 first, u32 last, const Tkey &value_min, const Tkey &value_max, u32 &inf, u32 &sup)
Find the range of indices for which key[inf] <= value_min <= value_max <= key[sup].
constexpr u32 binary_search_lower_bound(const Tkey *__restrict__ key, u32 first, u32 last, const Tkey &value)
GPU compatible implementation of std::lower_bound.
GPU compatible implementation of std::upper_bound.