Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-12-01 09:18:56

0001 // This file is part of the ACTS project.
0002 //
0003 // Copyright (C) 2016 CERN for the benefit of the ACTS project
0004 //
0005 // This Source Code Form is subject to the terms of the Mozilla Public
0006 // License, v. 2.0. If a copy of the MPL was not distributed with this
0007 // file, You can obtain one at https://mozilla.org/MPL/2.0/.
0008 
0009 #pragma once
0010 
0011 #include <concepts>
0012 #include <optional>
0013 #include <sstream>
0014 #include <system_error>
0015 #include <type_traits>
0016 #include <utility>
0017 #include <variant>
0018 
0019 namespace Acts {
0020 
0021 /// Class which encapsulates either a valid result, or an error
0022 /// @tparam T The valid result value
0023 /// @tparam E The error, defaults to `std::error_code`
0024 ///
0025 template <typename T, typename E = std::error_code>
0026 class [[nodiscard]] Result {
0027   /// Private constructor which accepts an external variant.
0028   /// This is used by the factory static methods to set up
0029   /// the variant unambiguously in all cases.
0030   explicit Result(std::variant<T, E>&& var) : m_var(std::move(var)) {}
0031 
0032  public:
0033   /// Type alias for the value type contained in successful result
0034   using ValueType = T;
0035   /// Type alias for the error type contained in failed result
0036   using ErrorType = E;
0037 
0038   /// Default construction is disallowed.
0039   Result() = delete;
0040 
0041   /// Copy construction is disallowed
0042   Result(const Result<T, E>& other) = delete;
0043 
0044   /// Assignment is disallowed
0045   Result<T, E>& operator=(const Result<T, E>& other) = delete;
0046 
0047   /// Move construction is allowed
0048   /// @param other The other result instance to move from
0049   Result(Result<T, E>&& other) = default;
0050 
0051   /// Move assignment is allowed
0052   /// @param other The other result instance, rvalue reference
0053   /// @return The assigned instance
0054   Result<T, E>& operator=(Result<T, E>&& other) = default;
0055 
0056   /// @brief Constructor from arbitrary value
0057   /// This constructor allows construction from any value. This constructor is
0058   /// only enabled if T and E are unambiguous, meaning they cannot be implicitly
0059   /// converted and there is T cannot be constructed from E and vice-versa.
0060   /// This means that when this is invoked, the value can be propagated to the
0061   /// underlying variant, and the assignment will be correct, and error will be
0062   /// an error, and a value will be a value.
0063   /// @note If T and E are ambiguous, use the `success` and `failure` static
0064   /// factory methods.
0065   /// @tparam T2 Type of the potential assignment
0066   /// @param value The potential value, could be an actual valid value or an
0067   /// error.
0068   template <typename T2>
0069   Result(T2 value) noexcept  // NOLINT(google-explicit-constructor)
0070                              // ^ Conversion here is crucial for ergonomics
0071     requires(!std::same_as<T, E> && !std::constructible_from<T, E> &&
0072              !std::convertible_to<T, E> && !std::constructible_from<E, T> &&
0073              !std::convertible_to<E, T> &&
0074              !(std::convertible_to<T2, T> && std::convertible_to<T2, E>))
0075       : m_var(std::conditional_t<std::is_convertible_v<T2, T>, T, E>{
0076             std::move(value)}) {}
0077 
0078   /// @brief Assignment operator from arbitrary value
0079   /// This operator allows construction from any value. The same rules as for
0080   /// the `Result(T2 value)` constructor apply.
0081   /// * @tparam T2 Type of the potential assignment
0082   /// @param value The potential value, could be an actual valid value or an
0083   /// error.
0084   /// @return The assigned instance
0085   template <typename T2>
0086   Result<T, E>& operator=(T2 value) noexcept
0087     requires(!std::same_as<T, E> && !std::constructible_from<T, E> &&
0088              !std::convertible_to<T, E> && !std::constructible_from<E, T> &&
0089              !std::convertible_to<E, T> &&
0090              !(std::convertible_to<T2, T> && std::convertible_to<T2, E>))
0091   {
0092     m_var = std::move(std::conditional_t<std::is_convertible_v<T2, T>, T, E>{
0093         std::move(value)});
0094     return *this;
0095   }
0096 
0097   /// Static helper factory which forces assignment as valid value.
0098   /// @param value The valid value to assign. Will not be converted to E.
0099   /// @return Initialized result object
0100   static Result<T, E> success(T value) {
0101     return Result<T, E>(
0102         std::variant<T, E>{std::in_place_index<0>, std::move(value)});
0103   }
0104 
0105   /// Static helper factory which forces assignment as an error.
0106   /// @param error The error to assign. Will not be converted to T.
0107   /// @return Initialized result object
0108   static Result<T, E> failure(E error) {
0109     return Result<T, E>(
0110         std::variant<T, E>{std::in_place_index<1>, std::move(error)});
0111   }
0112 
0113   /// Checks whether this result contains a valid value, and no error.
0114   /// @return bool Whether result contains an error or not.
0115   bool ok() const noexcept { return m_var.index() == 0; }
0116 
0117   /// Returns a reference into the variant to the valid value.
0118   /// @note If `!res.ok()`, this method will abort (noexcept)
0119   /// @return Reference to value stored in the variant.
0120   T& operator*() noexcept { return std::get<T>(m_var); }
0121 
0122   /// Returns a reference into the variant to the valid value.
0123   /// @note If `!res.ok()`, this method will abort (noexcept)
0124   /// @return Reference to value stored in the variant.
0125   const T& operator*() const noexcept { return std::get<T>(m_var); }
0126 
0127   /// Allows to access members of the stored object with `res->foo`
0128   /// similar to `std::optional`.
0129   /// @note If `!res.ok()`, this method will abort (noexcept)
0130   /// @return Pointer to value stored in the variant.
0131   T* operator->() noexcept { return &std::get<T>(m_var); }
0132 
0133   /// Allows to access members of the stored object with `res->foo`
0134   /// similar to `std::optional`.
0135   /// @note If `!res.ok()`, this method will abort (noexcept)
0136   /// @return Pointer to value stored in the variant.
0137   const T* operator->() const noexcept { return &std::get<T>(m_var); }
0138 
0139   /// Returns a reference to the error stored in the result.
0140   /// @note If `res.ok()` this method will abort (noexcept)
0141   /// @return Reference to the error
0142   E& error() & noexcept { return std::get<E>(m_var); }
0143 
0144   /// Returns a reference to the error stored in the result.
0145   /// @note If `res.ok()` this method will abort (noexcept)
0146   /// @return Reference to the error
0147   const E& error() const& noexcept { return std::get<E>(m_var); }
0148 
0149   /// Returns the error by-value.
0150   /// @note If `res.ok()` this method will abort (noexcept)
0151   /// @return The error
0152   E error() && noexcept { return std::move(std::get<E>(m_var)); }
0153 
0154   /// Retrieves the valid value from the result object.
0155   /// @note This is the lvalue version, returns a reference to the value
0156   /// @return The valid value as a reference
0157   T& value() & {
0158     checkValueAccess();
0159     return std::get<T>(m_var);
0160   }
0161 
0162   /// Retrieves the valid value from the result object.
0163   /// @note This is the lvalue version, returns a reference to the value
0164   /// @return The valid value as a reference
0165   const T& value() const& {
0166     checkValueAccess();
0167     return std::get<T>(m_var);
0168   }
0169 
0170   /// @cond
0171   /// Retrieves the valid value from the result object.
0172   /// @note This is the rvalue version, returns the value
0173   /// by-value and moves out of the variant.
0174   /// @return The valid value by value (moved)
0175   T value() && {
0176     checkValueAccess();
0177     return std::move(std::get<T>(m_var));
0178   }
0179   /// @endcond
0180 
0181   /// Retrieves the valid value from the result object, or returns a default
0182   /// value if no valid value exists.
0183   ///
0184   /// @param[in] v The default value to use if no valid value exists.
0185   /// @note This is the lvalue version.
0186   /// @note This function always returns by value.
0187   /// @return Either the valid value, or the given substitute.
0188   template <typename U>
0189   std::conditional_t<std::is_reference_v<U>, const T&, T> value_or(U&& v) const&
0190     requires(std::same_as<std::decay_t<U>, T>)
0191   {
0192     if (ok()) {
0193       return value();
0194     } else {
0195       return std::forward<U>(v);
0196     }
0197   }
0198 
0199   /// @cond
0200   /// Retrieves the valid value from the result object, or returns a default
0201   /// value if no valid value exists.
0202   ///
0203   /// @param[in] v The default value to use if no valid value exists.
0204   /// @return The valid value if present, otherwise the default value
0205   /// @note This is the rvalue version which moves the value out.
0206   /// @note This function always returns by value.
0207   template <typename U>
0208   T value_or(U&& v) &&
0209     requires(std::same_as<std::decay_t<U>, T>)
0210   {
0211     if (ok()) {
0212       return std::move(*this).value();
0213     } else {
0214       return std::forward<U>(v);
0215     }
0216   }
0217   /// @endcond
0218 
0219   /// Transforms the value contained in this result.
0220   ///
0221   /// Applying a function `f` to a valid value `x` returns `f(x)`, while
0222   /// applying `f` to an invalid value returns another invalid value.
0223   ///
0224   /// @param[in] callable The transformation function to apply.
0225   /// @note This is the lvalue version.
0226   /// @note This functions is `fmap` on the functor in `A` of `Result<A, E>`.
0227   /// @return The modified valid value if exists, or an error otherwise.
0228   template <typename C>
0229   auto transform(C&& callable) const&
0230     requires std::invocable<C, const T&>
0231   {
0232     using CallableReturnType = decltype(std::declval<C>()(std::declval<T>()));
0233     using R = Result<std::decay_t<CallableReturnType>, E>;
0234     if (ok()) {
0235       return R::success(callable(value()));
0236     } else {
0237       return R::failure(error());
0238     }
0239   }
0240 
0241   /// Transforms the value contained in this result.
0242   ///
0243   /// Applying a function `f` to a valid value `x` returns `f(x)`, while
0244   /// applying `f` to an invalid value returns another invalid value.
0245   ///
0246   /// @param[in] callable The transformation function to apply.
0247   /// @note This is the rvalue version.
0248   /// @note This functions is `fmap` on the functor in `A` of `Result<A, E>`.
0249   /// @return The modified valid value if exists, or an error otherwise.
0250   template <typename C>
0251   auto transform(C&& callable) &&
0252     requires std::invocable<C, T&&>
0253   {
0254     using CallableReturnType = decltype(std::declval<C>()(std::declval<T>()));
0255     using R = Result<std::decay_t<CallableReturnType>, E>;
0256     if (ok()) {
0257       return R::success(callable(std::move(*this).value()));
0258     } else {
0259       return R::failure(std::move(*this).error());
0260     }
0261   }
0262 
0263   /// Bind a function to this result monadically.
0264   ///
0265   /// This function takes a function `f` and, if this result contains a valid
0266   /// value `x`, returns `f(x)`. If the type of `x` is `T`, then `f` is
0267   /// expected to accept type `T` and return `Result<U>`. In this case,
0268   /// `transform` would return the unhelpful type `Result<Result<U>>`, so
0269   /// `and_then` strips away the outer layer to return `Result<U>`. If the
0270   /// value is invalid, this returns an invalid value in `Result<U>`.
0271   ///
0272   /// @param[in] callable The transformation function to apply.
0273   /// @note This is the lvalue version.
0274   /// @note This functions is `>>=` on the functor in `A` of `Result<A, E>`.
0275   /// @return The modified valid value if exists, or an error otherwise.
0276   template <typename C>
0277   auto and_then(C&& callable) const&
0278     requires std::invocable<C, const T&>
0279   {
0280     using R = decltype(std::declval<C>()(std::declval<T>()));
0281 
0282     static_assert(std::same_as<typename R::ErrorType, ErrorType>,
0283                   "bind must take a callable with the same error type");
0284 
0285     if (ok()) {
0286       return callable(value());
0287     } else {
0288       return R::failure(error());
0289     }
0290   }
0291 
0292   /// Bind a function to this result monadically.
0293   ///
0294   /// This function takes a function `f` and, if this result contains a valid
0295   /// value `x`, returns `f(x)`. If the type of `x` is `T`, then `f` is
0296   /// expected to accept type `T` and return `Result<U>`. In this case,
0297   /// `transform` would return the unhelpful type `Result<Result<U>>`, so
0298   /// `and_then` strips away the outer layer to return `Result<U>`. If the
0299   /// value is invalid, this returns an invalid value in `Result<U>`.
0300   ///
0301   /// @param[in] callable The transformation function to apply.
0302   /// @note This is the rvalue version.
0303   /// @note This functions is `>>=` on the functor in `A` of `Result<A, E>`.
0304   /// @return The modified valid value if exists, or an error otherwise.
0305   template <typename C>
0306   auto and_then(C&& callable) &&
0307     requires std::invocable<C, T&&>
0308   {
0309     using R = decltype(std::declval<C>()(std::declval<T>()));
0310 
0311     static_assert(std::same_as<typename R::ErrorType, ErrorType>,
0312                   "bind must take a callable with the same error type");
0313 
0314     if (ok()) {
0315       return callable(std::move(*this).value());
0316     } else {
0317       return R::failure(std::move(*this).error());
0318     }
0319   }
0320 
0321  private:
0322   std::variant<T, E> m_var;
0323 
0324   void checkValueAccess() const {
0325     if (m_var.index() != 0) {
0326       if constexpr (std::is_same_v<E, std::error_code>) {
0327         std::stringstream ss;
0328         const auto& e = std::get<E>(m_var);
0329         ss << "Value called on error value: " << e.category().name() << ": "
0330            << e.message() << " [" << e.value() << "]";
0331         throw std::runtime_error(ss.str());
0332       } else {
0333         throw std::runtime_error("Value called on error value");
0334       }
0335     }
0336   }
0337 };
0338 
0339 /// Template specialization for the void case.
0340 /// This specialization handles the case where there is no actual return value,
0341 /// but
0342 /// an error might be returned. Returning the error directly would make handling
0343 /// different from other functions using the `Result<T, E>` mechanism.
0344 /// `Result<void, E>` does not have the dereference operator, and value methods.
0345 /// The static `success` factory does not accept a value.
0346 /// @note To ease usage, this `Result<void, E>` is default constructible in the
0347 /// *ok*
0348 /// state, whereas `Result<T, E>` is not.
0349 /// @tparam E The type of the error
0350 /// @{
0351 template <typename E>
0352 class [[nodiscard]] Result<void, E> {
0353  public:
0354   /// Type alias for the value type (void) in successful result
0355   using ValueType = void;
0356   /// Type alias for the error type contained in failed result
0357   using ErrorType = E;
0358 
0359   /// Default constructor which initializes the result in the ok state.
0360   Result() = default;
0361 
0362   /// Copy constructor.
0363   /// @param other The other result instance to copy from
0364   Result(const Result<void, E>& other) = default;
0365 
0366   /// Copy assignment operator.
0367   /// @param other The other result instance to assign from
0368   /// @return Reference to this result instance
0369   Result<void, E>& operator=(const Result<void, E>& other) = default;
0370 
0371   /// Move constructor
0372   /// @param other The other result object, rvalue ref
0373   Result(Result<void, E>&& other) = default;
0374 
0375   /// Move assignment operator
0376   /// @param other The other result object, rvalue ref
0377   /// @return Reference to this result for assignment chaining
0378   Result<void, E>& operator=(Result<void, E>&& other) = default;
0379 
0380   /// Constructor from error. This implicitly requires E2 to be convertible to
0381   /// E.
0382   /// @tparam E2 The type of the actual error
0383   /// @param error The instance of the actual error
0384   template <typename E2>
0385   Result(E2 error) noexcept  // NOLINT(google-explicit-constructor)
0386                              // ^ Conversion here is crucial for ergonomics
0387       : m_opt(std::move(error)) {}
0388 
0389   /// Assignment operator from an error.
0390   /// @tparam E2 The type of the actual error
0391   /// @param error The instance of the actual error
0392   /// @return The assigned instance
0393   template <typename E2>
0394   Result<void, E>& operator=(E2 error) {
0395     m_opt = std::move(error);
0396     return *this;
0397   }
0398 
0399   /// Static factory function to initialize the result in the ok state.
0400   /// @return Result object, in ok state
0401   static Result<void, E> success() { return Result<void, E>(); }
0402 
0403   /// Static factory function to initialize the result in the error state.
0404   /// @param error The error to initialize with.
0405   /// @return Result object, in error state.
0406   static Result<void, E> failure(E error) {
0407     return Result<void, E>(std::move(error));
0408   }
0409 
0410   /// Checks whether this result is in the ok state, and no error.
0411   /// @return bool Whether result contains an error or not.
0412   bool ok() const noexcept { return !m_opt; }
0413 
0414   /// Returns a reference to the error stored in the result.
0415   /// @note If `res.ok()` this method will abort (noexcept)
0416   /// @return Reference to the error
0417   E& error() & noexcept { return m_opt.value(); }
0418 
0419   /// Returns a reference to the error stored in the result.
0420   /// @note If `res.ok()` this method will abort (noexcept)
0421   /// @return Reference to the error
0422   const E& error() const& noexcept { return m_opt.value(); }
0423 
0424   /// Returns the error by-value.
0425   /// @note If `res.ok()` this method will abort (noexcept)
0426   /// @return The error by value
0427   E error() && noexcept { return std::move(m_opt.value()); }
0428 
0429   /// Validates this void result and throws if an error is present
0430   ///
0431   /// This method checks if the result contains an error and throws an exception
0432   /// if one is found. For void results, there is no value to return - this
0433   /// method only performs validation.
0434   ///
0435   /// @throws std::runtime_error if the result contains an error
0436   void value() const { checkValueAccess(); }
0437 
0438  private:
0439   std::optional<E> m_opt;
0440 
0441   void checkValueAccess() const {
0442     if (m_opt.has_value()) {
0443       if constexpr (std::is_same_v<E, std::error_code>) {
0444         std::stringstream ss;
0445         const auto& e = m_opt.value();
0446         ss << "Value called on error value: " << e.category().name() << ": "
0447            << e.message() << " [" << e.value() << "]";
0448         throw std::runtime_error(ss.str());
0449       } else {
0450         throw std::runtime_error("Value called on error value");
0451       }
0452     }
0453   }
0454 };
0455 /// @}
0456 
0457 }  // namespace Acts