core-adapters 0.1.1
Third-party adapters for snicholls-core: nanobind helpers, nlohmann/json hooks, the snicholls_core Python package
Loading...
Searching...
No Matches
optional.hpp
Go to the documentation of this file.
1//
2// optional.hpp
3// core-adapters
4//
5// Copyright 2010-2026 Saxon Herschel Nicholls
6//
7
49
50#ifndef snicholls_core_adapters_nanobind_optional_hpp
51#define snicholls_core_adapters_nanobind_optional_hpp
52
53#include <nanobind/nanobind.h>
54#include <nanobind/stl/optional.h>
55
56#include <snicholls/core/result.hpp>
58
59#include <exception>
60#include <type_traits>
61#include <utility>
62
63namespace nanobind::detail {
64
66template <class V, class E>
67struct type_caster<snicholls::result<V, E>>
68{
69 using Value = snicholls::result<V, E>;
70 static constexpr auto Name = [] {
71 if constexpr (std::is_void_v<V>)
72 return const_name("None");
73 else
74 return make_caster<V>::Name;
75 }();
76 template <typename T_>
77 using Cast = movable_cast_t<T_>;
78 template <typename T_>
79 static constexpr bool can_cast()
80 {
81 return false;
82 }
83
84 bool from_python(handle, uint32_t, cleanup_list*) noexcept { return false; } // never an argument
85
86 template <typename T_>
87 static handle from_cpp(T_&& r, rv_policy policy, cleanup_list* cleanup) noexcept
88 {
89 if (r.is_err()) {
90 try {
91 snicholls::python::raise_error(r.unwrap_err_unchecked());
92 } catch (...) {
93 snicholls::python::set_python_error(std::current_exception());
94 }
95 return {};
96 }
97 if constexpr (std::is_void_v<V>)
98 return none().release();
99 else
100 return make_caster<V>::from_cpp(std::forward<T_>(r).unwrap_unchecked(), policy, cleanup);
101 }
102};
104
105} // namespace nanobind::detail
106
107#endif /* snicholls_core_adapters_nanobind_optional_hpp */
C++ errors to Python exceptions: core's result / traced errors to the snicholls_core....
void set_python_error(const std::exception_ptr &p) noexcept
Sets the Python error for a C++ exception, by the file's table. For type casters, which return a null...
Definition errors.hpp:286
void raise_error(const E &e)
Throws e as the C++ exception that maps to the right Python class.
Definition errors.hpp:252