-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathoptional_index.hh
72 lines (58 loc) · 1.61 KB
/
optional_index.hh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// Copyright (c) 2022 Mikael Simonsson <https://mikaelsimonsson.com>.
// SPDX-License-Identifier: BSL-1.0
// # Optional index
#pragma once
#include "snn-core/exception.hh"
#include "snn-core/generic/error.hh"
namespace snn
{
// ## Classes
// ### optional_index
class optional_index final
{
public:
constexpr optional_index(const usize index) noexcept
: index_{index}
{
}
// Optional assignment is error-prone and therefore disabled.
// The implicit copy/move assignment operator can still be used.
template <typename U>
void operator=(const U&) = delete;
constexpr explicit operator bool() const noexcept
{
return has_value();
}
[[nodiscard]] constexpr bool has_value() const noexcept
{
return index_ != constant::npos;
}
[[nodiscard]] constexpr usize value() const
{
if (has_value())
{
return index_;
}
throw_or_abort(generic::error::no_value);
}
[[nodiscard]] constexpr usize value(promise::has_value_t) const noexcept
{
snn_assert(has_value());
return index_;
}
[[nodiscard]] constexpr usize value_or(const usize alt) const noexcept
{
if (has_value())
{
return index_;
}
return alt;
}
[[nodiscard]] constexpr usize value_or_npos() const noexcept
{
return index_;
}
private:
usize index_;
};
}