StormByte 3.0.0
C++26 foundation of the StormByte suite
Loading...
Searching...
No Matches
optional.hxx
Go to the documentation of this file.
1/*
2 * Copyright (C) 2024-2026 David C. Manuelda (StormBytePP)
3 *
4 * This is the base for StormByte Suite libraries.
5 *
6 * StormByte original source is dual-licensed:
7 *
8 * 1. GNU Lesser General Public License v3.0 (or later)
9 * You may redistribute and/or modify this file under the terms of the
10 * GNU Lesser General Public License as published by the Free Software
11 * Foundation, either version 3 of the License, or (at your option)
12 * any later version.
13 *
14 * 2. Commercial license
15 * Alternatively, this file may be used under the terms of a commercial
16 * license agreement with the copyright holder
17 * (David C. Manuelda <StormByte@gmail.com>).
18 *
19 * Both licenses apply only to original StormByte source in this repository.
20 * They do not cover other StormByte modules or any third-party material
21 * shipped with this repository (including everything under thirdparty/),
22 * which remains under its own license.
23 *
24 * Neither license grants any patent rights. Any patent licenses required
25 * to use this software or third-party components must be obtained separately
26 * from the patent holders.
27 *
28 * StormByte is distributed in the hope that it will be useful,
29 * but WITHOUT ANY WARRANTY; without even the implied warranty of
30 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
31 * GNU Lesser General Public License for more details.
32 *
33 * You should have received a copy of the GNU Lesser General Public License
34 * version 3 along with StormByte. If not, see
35 * <https://www.gnu.org/licenses/lgpl-3.0.html>.
36 *
37 * SPDX-License-Identifier: LGPL-3.0-or-later OR LicenseRef-StormByte-Commercial
38 */
39
40#pragma once
41
47
48#include <compare>
49#include <cstddef>
50#include <cstdint>
51#include <functional>
52#include <initializer_list>
53#include <optional>
54#include <span>
55#include <utility>
56
61namespace StormByte {
66 namespace Safe {
71 namespace Detail {
76 template<class R>
77 concept SafeOptionalResult = Type::SafeComponent<R> && requires(const R& result) {
78 { result.has_value() } -> Type::ConvertibleTo<bool>;
79 };
80 }
81
89 template<Type::SafeComponent T>
91 public:
92 using value_type = T;
93 using iterator = T*;
94 using const_iterator = const T*;
95 using reference = T&;
96 using const_reference = const T&;
97
101 Optional() noexcept;
102
107 Optional(std::nullopt_t value) noexcept;
108
116 template<class... Args>
117 requires Type::ConstructibleFrom<T, Args...>
118 explicit Optional(std::in_place_t tag, Args&&... args): Optional() {
119 (void)tag;
120 emplace(std::forward<Args>(args)...);
121 }
122
132 template<class U, class... Args>
134 explicit Optional(std::in_place_t tag, std::initializer_list<U> values, Args&&... args): Optional() {
135 (void)tag;
136 emplace(values, std::forward<Args>(args)...);
137 }
138
144 Optional(const T& value);
145
152
159 template<class U>
160 requires (!Type::SameAs<U, Optional>) &&
165 emplace(std::forward<U>(value));
166 }
167
173 Optional(const std::optional<T>& value);
174
180 Optional(std::optional<T>&& value);
181
188 template<class U>
190 explicit((!Type::ConvertibleTo<const U&, T>)) Optional(const std::optional<U>& value): Optional() {
191 if (value)
192 emplace(T(*value));
193 }
194
201 template<class U>
203 explicit((!Type::ConvertibleTo<U, T>)) Optional(std::optional<U>&& value): Optional() {
204 if (value)
205 emplace(T(std::move(*value)));
206 }
207
213 Optional(const Optional& other);
214
219 Optional(Optional&& other) noexcept;
220
224 ~Optional() noexcept;
225
232 Optional& operator=(const Optional& other);
233
239 Optional& operator=(Optional&& other) noexcept;
240
247 Optional& operator=(const T& value);
248
255 Optional& operator=(T&& value);
256
264 template<class U>
265 requires (!Type::SameAs<U, Optional>) &&
266 (!Type::SameAs<U, std::nullopt_t>) &&
267 Type::ConstructibleFrom<T, U>
268 Optional& operator=(U&& value) {
269 emplace(std::forward<U>(value));
270 return *this;
271 }
272
278 Optional& operator=(std::nullopt_t value) noexcept;
279
286 Optional& operator=(const std::optional<T>& value);
287
294 Optional& operator=(std::optional<T>&& value);
295
300 void swap(Optional& other) noexcept;
301
307 friend void swap(Optional& left, Optional& right) noexcept { left.swap(right); }
308
313 bool has_value() const noexcept { return m_value != nullptr; }
314
319 explicit operator bool() const noexcept { return has_value(); }
320
325 iterator begin() noexcept { return m_value; }
326
331 iterator end() noexcept { return m_value == nullptr ? nullptr : m_value + 1; }
332
337 const_iterator begin() const noexcept { return m_value; }
338
343 const_iterator end() const noexcept { return m_value == nullptr ? nullptr : m_value + 1; }
344
349 const_iterator cbegin() const noexcept { return begin(); }
350
355 const_iterator cend() const noexcept { return end(); }
356
362 T& value() &;
363
369 const T& value() const &;
370
376 T&& value() &&;
377
383 const T&& value() const &&;
384
391 template<class U>
392 requires Type::ConvertibleTo<U, T>
393 T value_or(U&& fallback) const & {
394 return has_value() ? *m_value : T(std::forward<U>(fallback));
395 }
396
403 template<class U>
405 T value_or(U&& fallback) && {
406 return has_value() ? T(std::move(*m_value)) : T(std::forward<U>(fallback));
407 }
408
414 T& operator*() &;
415
421 const T& operator*() const &;
422
428 T&& operator*() &&;
429
435 const T&& operator*() const &&;
436
442 T* operator->();
443
449 const T* operator->() const;
450
456 bool operator==(const Optional& other) const requires Type::EqualityComparable<T> {
457 return has_value() == other.has_value() && (!has_value() || *m_value == *other.m_value);
458 }
459
465 bool operator!=(const Optional& other) const requires Type::EqualityComparable<T> {
466 return !(*this == other);
467 }
468
473 bool operator==(std::nullopt_t) const noexcept { return !has_value(); }
474
480 friend bool operator==(std::nullopt_t, const Optional& self) noexcept { return !self.has_value(); }
481
486 STORMBYTE_FORCE_INLINE std::strong_ordering operator<=>(std::nullopt_t) const noexcept {
487 return has_value() ? std::strong_ordering::greater : std::strong_ordering::equivalent;
488 }
489
496 template<class U>
499 requires(const T& left, const U& right) { { left == right } -> Type::ConvertibleTo<bool>; }
500 bool operator==(const U& value) const {
501 return has_value() && *m_value == value;
502 }
503
511 template<class U>
514 requires(const U& left, const T& right) { { left == right } -> Type::ConvertibleTo<bool>; }
515 friend bool operator==(const U& value, const Optional& self) {
516 return self.has_value() && value == *self.m_value;
517 }
518
525 template<class U>
528 requires(const T& left, const U& right) { left <=> right; }
530 using Result = std::common_comparison_category_t<decltype(std::declval<const T&>() <=> std::declval<const U&>())>;
531 if (!has_value())
532 return Result::less;
533 return static_cast<Result>(*m_value <=> value);
534 }
535
542 using Result = std::common_comparison_category_t<decltype(std::declval<const T&>() <=> std::declval<const T&>())>;
543 if (has_value() && other.has_value())
544 return static_cast<Result>(*m_value <=> *other.m_value);
545 if (has_value())
546 return Result::greater;
547 if (other.has_value())
548 return Result::less;
549 return Result::equivalent;
550 }
551
558 template<class U>
559 requires requires(const T& left, const U& right) { { left == right } -> Type::ConvertibleTo<bool>; }
560 bool operator==(const std::optional<U>& other) const {
561 return has_value() == other.has_value() && (!has_value() || *m_value == *other);
562 }
563
571 template<class U>
572 requires requires(const U& left, const T& right) { { left == right } -> Type::ConvertibleTo<bool>; }
573 friend bool operator==(const std::optional<U>& other, const Optional& self) {
574 return self == other;
575 }
576
583 template<class U>
584 requires requires(const T& left, const U& right) { left <=> right; }
585 STORMBYTE_FORCE_INLINE auto operator<=>(const std::optional<U>& other) const {
586 using Result = std::common_comparison_category_t<decltype(std::declval<const T&>() <=> std::declval<const U&>())>;
587 if (has_value() && other.has_value())
588 return static_cast<Result>(*m_value <=> *other);
589 if (has_value())
590 return Result::greater;
591 if (other.has_value())
592 return Result::less;
593 return Result::equivalent;
594 }
595
602 template<class F>
604 auto and_then(F&& function) & {
605 using Result = std::remove_cvref_t<std::invoke_result_t<F, T&>>;
606 if (!has_value())
607 return Result{};
608 return std::invoke(std::forward<F>(function), *m_value);
609 }
610
617 template<class F>
619 auto and_then(F&& function) const & {
620 using Result = std::remove_cvref_t<std::invoke_result_t<F, const T&>>;
621 if (!has_value())
622 return Result{};
623 return std::invoke(std::forward<F>(function), static_cast<const T&>(*m_value));
624 }
625
632 template<class F>
634 auto and_then(F&& function) && {
635 using Result = std::remove_cvref_t<std::invoke_result_t<F, T&&>>;
636 if (!has_value())
637 return Result{};
638 return std::invoke(std::forward<F>(function), std::move(*m_value));
639 }
640
647 template<class F>
649 auto transform(F&& function) & {
650 using Result = std::remove_cvref_t<std::invoke_result_t<F, T&>>;
651 if (!has_value())
652 return Optional<Result>{};
653 return Optional<Result>(std::invoke(std::forward<F>(function), *m_value));
654 }
655
662 template<class F>
664 auto transform(F&& function) const & {
665 using Result = std::remove_cvref_t<std::invoke_result_t<F, const T&>>;
666 if (!has_value())
667 return Optional<Result>{};
668 return Optional<Result>(std::invoke(std::forward<F>(function), static_cast<const T&>(*m_value)));
669 }
670
677 template<class F>
679 auto transform(F&& function) && {
680 using Result = std::remove_cvref_t<std::invoke_result_t<F, T&&>>;
681 if (!has_value())
682 return Optional<Result>{};
683 return Optional<Result>(std::invoke(std::forward<F>(function), std::move(*m_value)));
684 }
685
692 template<class F>
694 Optional or_else(F&& function) const & {
695 if (has_value())
696 return *this;
697 return std::invoke(std::forward<F>(function));
698 }
699
706 template<class F>
708 Optional or_else(F&& function) && {
709 if (has_value())
710 return std::move(*this);
711 return std::invoke(std::forward<F>(function));
712 }
713
721 template<class... Args>
722 T& emplace(Args&&... args) {
723 T* created = Make(std::forward<Args>(args)...);
724 Release();
725 m_value = created;
726 return *m_value;
727 }
728
738 template<class U, class... Args>
739 T& emplace(std::initializer_list<U> values, Args&&... args) {
740 T* created = Make(values, std::forward<Args>(args)...);
741 Release();
742 m_value = created;
743 return *m_value;
744 }
745
749 void reset() noexcept;
750
755 STORMBYTE_FORCE_INLINE explicit operator std::optional<T>() const {
756 if (!has_value())
757 return std::nullopt;
758 return std::optional<T>(*m_value);
759 }
760
761 private:
769 template<class... Args>
770 static T* Make(Args&&... args) {
771 void* block = Heap::Allocate(sizeof(T));
772 try {
773 return new (block) T(std::forward<Args>(args)...);
774 } catch (...) {
775 Heap::Free(block);
776 throw;
777 }
778 }
779
783 void Release() noexcept;
784
785 T* m_value;
786 };
787 }
788
793 namespace Type {
798 template<SafeComponent T>
799 requires Type::IsSafe<T>::value
800 struct IsSafe<Safe::Optional<T>>: std::true_type {};
801
806 template<SafeComponent T>
807 requires Type::MaybeSafe<T>
808 struct IsMaybeSafe<Safe::Optional<T>>: std::true_type {};
809
814 template<SafeComponent T>
815 struct IsSafeOptional<Safe::Optional<T>>: std::true_type {};
816
821 template<SafeComponent T>
822 struct IsSafeValue<Safe::Optional<T>>: std::true_type {};
823 }
824}
825
830template<StormByte::Type::SafeComponent T>
837 STORMBYTE_FORCE_INLINE std::size_t operator()(const StormByte::Safe::Optional<T>& value) const noexcept {
838 if (!value.has_value())
839 return Hash<std::uint8_t>{}(0);
840 return HashCombine(Hash<std::uint8_t>{}(1), Hash<T>{}(*value));
841 }
842};
843
848template<StormByte::Type::SafeComponent T>
849struct std::hash<StormByte::Safe::Optional<T>> {
855 std::size_t operator()(const StormByte::Safe::Optional<T>& value) const noexcept {
857 }
858};
859
std::optional stored on Base's heap.
Definition optional.hxx:90
T value_type
Contained type.
Definition optional.hxx:92
Optional & operator=(std::optional< T > &&value)
Move-assign a caller-owned STL optional.
T & value() &
Return the contained value.
Optional(std::optional< U > &&value)
Move a caller-owned STL optional of a convertible value.
Definition optional.hxx:203
friend void swap(Optional &left, Optional &right) noexcept
Exchange two optionals.
Definition optional.hxx:307
~Optional() noexcept
Destroy a held value and release its Base block.
T value_or(U &&fallback) const &
Return the contained value or a fallback.
Definition optional.hxx:393
void swap(Optional &other) noexcept
Exchange contained blocks.
bool operator!=(const Optional &other) const
Compare states and, when present, values.
Definition optional.hxx:465
T & operator*() &
Access the contained value.
Optional(const std::optional< T > &value)
Copy a caller-owned STL optional into Base storage.
Optional or_else(F &&function) const &
Return this optional when engaged, otherwise invoke a fallback.
Definition optional.hxx:694
auto transform(F &&function) &
Map the contained value to another Safe component.
Definition optional.hxx:649
Optional(U &&value)
Construct T from a value that can construct it.
Definition optional.hxx:164
T & reference
Mutable contained value.
Definition optional.hxx:95
auto transform(F &&function) &&
Map an rvalue contained value to another Safe component.
Definition optional.hxx:679
friend bool operator==(std::nullopt_t, const Optional &self) noexcept
Compare the empty tag with this optional.
Definition optional.hxx:480
const_iterator cend() const noexcept
Return the end read-only iterator.
Definition optional.hxx:355
T & emplace(std::initializer_list< U > values, Args &&... args)
Construct or replace T from an initializer list.
Definition optional.hxx:739
auto and_then(F &&function) &&
Invoke a function on an rvalue value and return its optional result.
Definition optional.hxx:634
Optional(std::optional< T > &&value)
Move a caller-owned STL optional into Base storage.
T value_or(U &&fallback) &&
Return the contained value or a fallback from an rvalue.
Definition optional.hxx:405
STORMBYTE_FORCE_INLINE auto operator<=>(const U &value) const
Order against a Safe component.
Definition optional.hxx:529
Optional(const Optional &other)
Copy the contained value into a new Base block.
STORMBYTE_FORCE_INLINE std::strong_ordering operator<=>(std::nullopt_t) const noexcept
Order empty before engaged.
Definition optional.hxx:486
Optional(const T &value)
Copy a value into Base storage.
bool operator==(const U &value) const
Compare the contained value with a Safe component.
Definition optional.hxx:500
Optional(std::in_place_t tag, std::initializer_list< U > values, Args &&... args)
Construct T from an initializer list and trailing arguments.
Definition optional.hxx:134
Optional(const std::optional< U > &value)
Copy a caller-owned STL optional of a convertible value.
Definition optional.hxx:190
auto and_then(F &&function) &
Invoke a function on the value and return its optional result.
Definition optional.hxx:604
const T * const_iterator
Read-only iterator over the single value, or end when empty.
Definition optional.hxx:94
iterator end() noexcept
Return the end mutable iterator.
Definition optional.hxx:331
const T & value() const &
Return the contained value.
STORMBYTE_FORCE_INLINE auto operator<=>(const Optional &other) const
Order empty before engaged, then order the values.
Definition optional.hxx:541
Optional() noexcept
Construct an empty optional.
Optional & operator=(const std::optional< T > &value)
Copy-assign a caller-owned STL optional.
T & emplace(Args &&... args)
Construct or replace the contained value.
Definition optional.hxx:722
friend bool operator==(const std::optional< U > &other, const Optional &self)
Compare a caller-owned STL optional with this optional.
Definition optional.hxx:573
auto and_then(F &&function) const &
Invoke a function on the value and return its optional result.
Definition optional.hxx:619
Optional(Optional &&other) noexcept
Take the contained block.
auto transform(F &&function) const &
Map the contained value to another Safe component.
Definition optional.hxx:664
Optional or_else(F &&function) &&
Return this rvalue optional, or invoke a fallback.
Definition optional.hxx:708
const_iterator end() const noexcept
Return the end read-only iterator.
Definition optional.hxx:343
void reset() noexcept
Destroy a held value and release its block.
STORMBYTE_FORCE_INLINE auto operator<=>(const std::optional< U > &other) const
Order against a caller-owned STL optional.
Definition optional.hxx:585
const T & const_reference
Read-only contained value.
Definition optional.hxx:96
const_iterator begin() const noexcept
Return the read-only iterator, or end when empty.
Definition optional.hxx:337
friend bool operator==(const U &value, const Optional &self)
Compare a Safe component with this optional.
Definition optional.hxx:515
Optional & operator=(std::nullopt_t value) noexcept
Reset this optional.
bool has_value() const noexcept
Test whether a value is held.
Definition optional.hxx:313
Optional(T &&value)
Move a value into Base storage.
const_iterator cbegin() const noexcept
Return the read-only iterator.
Definition optional.hxx:349
iterator begin() noexcept
Return the mutable iterator, or end when empty.
Definition optional.hxx:325
T * iterator
Mutable iterator over the single value, or end when empty.
Definition optional.hxx:93
const T & operator*() const &
Access the contained value.
bool operator==(const std::optional< U > &other) const
Compare with a caller-owned STL optional.
Definition optional.hxx:560
bool operator==(std::nullopt_t) const noexcept
Compare with the empty tag.
Definition optional.hxx:473
Recognizes a monadic result that can report an empty state.
Definition optional.hxx:77
Type constructible from Args (std::constructible_from).
Definition object_semantics.hxx:356
From is implicitly convertible to To (std::is_convertible).
Definition conversions.hxx:74
Type whose == and != both yield something convertible to bool.
Definition comparison.hxx:81
Regularly invocable with argument types Args (std::invocable).
Definition relations.hxx:94
Recognizes a conditional Safe component after stripping cv and references.
Definition safe.hxx:301
std::optional<U> or a Safe optional wrapper.
Definition wrappers.hxx:152
Recognized Safe component after stripping cv and references.
Definition safe.hxx:311
Same type after stripping cv and references from both sides.
Definition relations.hxx:139
Type whose <=> operator is well-formed.
Definition comparison.hxx:97
Private Base heap used by StormByte::Safe::Shared, StormByte::Safe::Unique and StormByte::Safe::Clona...
Private helpers.
void * Allocate(std::size_t bytes)
Allocate bytes on Base's heap.
Owned values that cross a DLL without the caller's CRT.
STORMBYTE_FORCE_INLINE std::size_t HashCombine(std::size_t seed, std::size_t next) noexcept
Mix an existing hash with another.
Definition hash.hxx:83
@ Release
Release.
Definition memory_order.hxx:64
Root namespace of the StormByte suite.
Octet count. Defined in byte_size.hxx. Forwarded so Type::Numeral can name it.
STL namespace.
#define STORMBYTE_FORCE_INLINE
Definition platform.h:134
STORMBYTE_FORCE_INLINE std::size_t operator()(const StormByte::Safe::Optional< T > &value) const noexcept
Hash value.
Definition optional.hxx:837
Cross-module hash.
Definition hash.hxx:95
Recognizes types whose DLL-boundary safety depends on documented provider requirements.
Definition safe.hxx:262
Identifies Safe optional wrappers.
Definition safe.hxx:329
Recognizes collection values with Base-controlled lifetime.
Definition safe.hxx:347
Recognizes Base Safe components, not universal ABI compatibility.
Definition safe.hxx:138
std::size_t operator()(const StormByte::Safe::Optional< T > &value) const noexcept
Hash value.
Definition optional.hxx:855
#define STORMBYTE_PUBLIC_TYPE
Definition visibility.h:57