HikoGUI
A low latency retained GUI
Loading...
Searching...
No Matches
assert.hpp
Go to the documentation of this file.
1// Copyright Take Vos 2020-2022.
2// Distributed under the Boost Software License, Version 1.0.
3// (See accompanying file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)
4
8#pragma once
9
10#include "type_traits.hpp"
11#include "../macros.hpp"
12#include "debugger.hpp"
13#include "exception.hpp"
14#include <exception>
15#include <ranges>
16
17hi_export_module(hikogui.utility.assert);
18
19hi_warning_push();
20// "C26472: Don't use a static_cast for arithmetic", asserts use static_cast specifically for savety.
21hi_warning_ignore_msvc(26472);
22
23namespace hi { inline namespace v1 {
24
31hi_export [[nodiscard]] constexpr bool bound_check(std::unsigned_integral auto index, std::unsigned_integral auto upper) noexcept
32{
33 using value_type = common_integer_t<decltype(index), decltype(upper)>;
34
35 hilet index_ = static_cast<value_type>(index);
36 hilet upper_ = static_cast<value_type>(upper);
37 return index_ < upper_;
38}
39
40hi_export [[nodiscard]] constexpr bool bound_check(std::unsigned_integral auto index, std::signed_integral auto upper) noexcept
41{
42 if (upper <= 0) {
43 return false;
44 }
45 return bound_check(index, static_cast<std::make_unsigned_t<decltype(upper)>>(upper));
46}
47
56hi_export [[nodiscard]] constexpr bool bound_check(std::integral auto index, std::integral auto lower, std::integral auto upper) noexcept
57{
58 using value_type = common_integer_t<decltype(index), decltype(lower), decltype(upper)>;
59
60 auto index_ = static_cast<value_type>(index);
61 auto lower_ = static_cast<value_type>(lower);
62 auto upper_ = static_cast<value_type>(upper);
63
64#ifndef NDEBUG
65 if (not(lower_ < upper_)) {
66 hi_debug_abort("bound_check() lower is greater than upper.");
67 }
68#else
69 hi_assume(lower_ < upper_);
70#endif
71
72 return index_ >= lower_ and index_ < upper_;
73}
74
75template<typename Context>
76concept bound_check_range_helper = requires(Context&& range) {
77 {
78 std::ranges::size(range)
79 } -> std::unsigned_integral;
80};
81
88hi_export [[nodiscard]] constexpr bool bound_check(std::integral auto index, bound_check_range_helper auto&& range) noexcept
89{
90 static_assert(sizeof(index) <= sizeof(size_t));
91
92 if constexpr (std::is_signed_v<std::decay_t<decltype(index)>>) {
93 if (index < 0) {
94 return false;
95 }
96 }
97
98 return static_cast<size_t>(index) < std::ranges::size(range);
99}
100
101
102}} // namespace hi::v1
103
104hi_warning_pop();
DOXYGEN BUG.
Definition algorithm.hpp:16
geometry/margins.hpp
Definition lookahead_iterator.hpp:5
hi_export constexpr bool bound_check(std::unsigned_integral auto index, std::unsigned_integral auto upper) noexcept
Check if an unsigned index is less than the bound.
Definition assert.hpp:31
constexpr Out narrow_cast(In const &rhs) noexcept
Cast numeric values without loss of precision.
Definition cast.hpp:377
Definition assert.hpp:76