NeoFOAM
WIP Prototype of a modern OpenFOAM core
Loading...
Searching...
No Matches
span.hpp
Go to the documentation of this file.
1// SPDX-License-Identifier: MIT
2// SPDX-FileCopyrightText: 2025 NeoFOAM authors
3#pragma once
4
5#include <limits>
6
7#include <span>
8
9namespace NeoFOAM
10{
11
12/* @class Span
13 *
14 * @brief A wrapper class for std::span which allows to check whether the index access is in range
15 * The Span can be initialized like a regular std::span or from an existing std::span
16 *
17 * @ingroup core
18 *
19 */
20template<typename ValueType>
21class Span : public std::span<ValueType>
22{
23public:
24
25 /* A flag to control whether the program should terminate on invalid memory access or throw.
26 * Kokkos prefers to terminate, but for testing purpose the failureIndex is preferred
27 */
28 bool abort = true;
29
30 /* a member to store the first out of range data access. This assumes a span has
31 * at least a size of 1. A value of zero signals success. This is required we cannot
32 * throw from a device function.
33 */
34 mutable size_t failureIndex = 0;
35
36 using std::span<ValueType>::span; // Inherit constructors from std::span
37
38 /* Constructor from existing std::span
39 */
40 Span(std::span<ValueType> in) : Span(in.begin(), in.end()) {}
41
42 constexpr ValueType& operator[](std::size_t index) const
43 {
44#ifdef NF_DEBUG
45 if (index >= this->size())
46 {
47 // TODO: currently this is failing on our AWS workflow, once we have clang>16 there
48 // this should work again.
49 // const std::string msg {"Index is out of range. Index: "} + to_string(index);
50 if (abort)
51 {
52 Kokkos::abort("Index is out of range");
53 }
54 else
55 {
56 // NOTE: throwing from a device function does not work
57 // throw std::invalid_argument("Index is out of range");
58 if (failureIndex == 0)
59 {
60 failureIndex = index;
61 }
62 return std::span<ValueType>::operator[](index);
63 }
64 }
65#endif
66 return std::span<ValueType>::operator[](index);
67 }
68};
69
70
71} // namespace NeoFOAM
Span(std::span< ValueType > in)
Definition span.hpp:40
size_t failureIndex
Definition span.hpp:34
constexpr ValueType & operator[](std::size_t index) const
Definition span.hpp:42
bool abort
Definition span.hpp:28