core-adapters 0.1.3
Third-party adapters for snicholls-core: nanobind helpers, nlohmann/json hooks, the snicholls_core Python package
Loading...
Searching...
No Matches
optional.hpp File Reference

Values that may be missing: std::optional both ways, and a returned snicholls::result as value-or-raise. More...

#include <nanobind/nanobind.h>
#include <nanobind/stl/optional.h>
#include <snicholls/core/result.hpp>
#include <snicholls/core_adapters/nanobind/errors.hpp>
#include <exception>
#include <type_traits>
#include <utility>

Go to the source code of this file.

Detailed Description

Values that may be missing: std::optional both ways, and a returned snicholls::result as value-or-raise.

Overview
  • std::optional<T> is T | None in both directions (nanobind's caster, included here so one include covers the family's two "maybe" types). Core uses std::optional where absence is not an error: a parse that may fail, uint256 arithmetic, uuid text.
  • snicholls::result<V, E> as a return type is V (None for result<void, E>): an error result raises, through snicholls::python::raise_error (errors.hpp) - a traced error as TracedError with its location, anything else as ResultError or as the standard exception it already is. A binding can therefore return core's results directly, with no unwrap in sight. A result is never accepted as an argument.
// std::optional: None when absent, both ways
m.def("canonical_decimal", [](const std::string& text) -> std::optional<std::string> {
const auto d = snicholls::decimal::parse(text, snicholls::decimal_syntax::plain);
if (!d)
return std::nullopt;
return d->to_string();
}, "text"_a);
// snicholls::result: the value, or the error raised - no unwrap in the binding
m.def("parse_decimal", [](const std::string& text) -> snicholls::result<std::string, std::string> {
const auto d = snicholls::decimal::parse(text);
if (!d)
return snicholls::err("not canonical decimal text: " + text);
return snicholls::ok(d->to_string());
}, "text"_a);
Relationships
Guarantees and contracts
  • The result caster converts the value with V's own caster and return-value policy; it never throws (it sets the Python error and returns a null handle, as nanobind requires).
Errors
See errors.hpp: the Python class follows the error type.
Performance
No cost beyond V's own conversion on success.
Tests and demos
  • Tests: tests/nanobind/optional_test.cpp (the test module), tests/nanobind/optional_test.py.
  • Demo: demos/nanobind/optional_demo.cpp, demos/nanobind/optional_demo.py; scripts/demos/optional_demo.sh.
Dependencies
CMake target snicholls::core_nanobind; core's result.hpp.
Known issues and gotchas
  • The stubs show a result<V, E> function as returning V; document what it raises in the docstring.
Status
Experimental, pre-1.0.

Definition in file optional.hpp.