/* pybind11/stl.h: Transparent conversion for STL data types Copyright (c) 2016 Wenzel Jakob All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. */ #pragma once #include "pybind11.h" #include #include #include #include #include #include #include #if defined(_MSC_VER) #pragma warning(push) #pragma warning(disable: 4127) // warning C4127: Conditional expression is constant #endif #ifdef __has_include // std::optional (but including it in c++14 mode isn't allowed) # if defined(PYBIND11_CPP17) && __has_include() # include # define PYBIND11_HAS_OPTIONAL 1 # endif // std::experimental::optional (but not allowed in c++11 mode) # if defined(PYBIND11_CPP14) && __has_include() # include # define PYBIND11_HAS_EXP_OPTIONAL 1 # endif // std::variant # if defined(PYBIND11_CPP17) && __has_include() # include # define PYBIND11_HAS_VARIANT 1 # endif #elif defined(_MSC_VER) && defined(PYBIND11_CPP17) # include # include # define PYBIND11_HAS_OPTIONAL 1 # define PYBIND11_HAS_VARIANT 1 #endif NAMESPACE_BEGIN(pybind11) NAMESPACE_BEGIN(detail) template struct set_caster { using type = Type; using key_conv = make_caster; bool load(handle src, bool convert) { if (!isinstance(src)) return false; auto s = reinterpret_borrow(src); value.clear(); for (auto entry : s) { key_conv conv; if (!conv.load(entry, convert)) return false; value.insert(cast_op(std::move(conv))); } return true; } static handle cast(const type &src, return_value_policy policy, handle parent) { pybind11::set s; for (auto const &value: src) { auto value_ = reinterpret_steal(key_conv::cast(value, policy, parent)); if (!value_ || !s.add(value_)) return handle(); } return s.release(); } PYBIND11_TYPE_CASTER(type, _("Set[") + key_conv::name() + _("]")); }; template struct map_caster { using key_conv = make_caster; using value_conv = make_caster; bool load(handle src, bool convert) { if (!isinstance(src)) return false; auto d = reinterpret_borrow(src); value.clear(); for (auto it : d) { key_conv kconv; value_conv vconv; if (!kconv.load(it.first.ptr(), convert) || !vconv.load(it.second.ptr(), convert)) return false; value.emplace(cast_op(std::move(kconv)), cast_op(std::move(vconv))); } return true; } static handle cast(const Type &src, return_value_policy policy, handle parent) { dict d; for (auto const &kv: src) { auto key = reinterpret_steal(key_conv::cast(kv.first, policy, parent)); auto value = reinterpret_steal(value_conv::cast(kv.second, policy, parent)); if (!key || !value) return handle(); d[key] = value; } return d.release(); } PYBIND11_TYPE_CASTER(Type, _("Dict[") + key_conv::name() + _(", ") + value_conv::name() + _("]")); }; template struct list_caster { using value_conv = make_caster; bool load(handle src, bool convert) { if (!isinstance(src)) return false; auto s = reinterpret_borrow(src); value.clear(); reserve_maybe(s, &value); for (auto it : s) { value_conv conv; if (!conv.load(it, convert)) return false; value.push_back(cast_op(std::move(conv))); } return true; } private: template ().reserve(0)), void>::value, int> = 0> void reserve_maybe(sequence s, Type *) { value.reserve(s.size()); } void reserve_maybe(sequence, void *) { } public: static handle cast(const Type &src, return_value_policy policy, handle parent) { list l(src.size()); size_t index = 0; for (auto const &value: src) { auto value_ = reinterpret_steal(value_conv::cast(value, policy, parent)); if (!value_) return handle(); PyList_SET_ITEM(l.ptr(), (ssize_t) index++, value_.release().ptr()); // steals a reference } return l.release(); } PYBIND11_TYPE_CASTER(Type, _("List[") + value_conv::name() + _("]")); }; template struct type_caster> : list_caster, Type> { }; template struct type_caster> : list_caster, Type> { }; template struct array_caster { using value_conv = make_caster; private: template bool require_size(enable_if_t size) { if (value.size() != size) value.resize(size); return true; } template bool require_size(enable_if_t size) { return size == Size; } public: bool load(handle src, bool convert) { if (!isinstance(src)) return false; auto l = reinterpret_borrow(src); if (!require_size(l.size())) return false; size_t ctr = 0; for (auto it : l) { value_conv conv; if (!conv.load(it, convert)) return false; value[ctr++] = cast_op(std::move(conv)); } return true; } static handle cast(const ArrayType &src, return_value_policy policy, handle parent) { list l(src.size()); size_t index = 0; for (auto const &value: src) { auto value_ = reinterpret_steal(value_conv::cast(value, policy, parent)); if (!value_) return handle(); PyList_SET_ITEM(l.ptr(), (ssize_t) index++, value_.release().ptr()); // steals a reference } return l.release(); } PYBIND11_TYPE_CASTER(ArrayType, _("List[") + value_conv::name() + _(_(""), _("[") + _() + _("]")) + _("]")); }; template struct type_caster> : array_caster, Type, false, Size> { }; template struct type_caster> : array_caster, Type, true> { }; template struct type_caster> : set_caster, Key> { }; template struct type_caster> : set_caster, Key> { }; template struct type_caster> : map_caster, Key, Value> { }; template struct type_caster> : map_caster, Key, Value> { }; // This type caster is intended to be used for std::optional and std::experimental::optional template struct optional_caster { using value_conv = make_caster; static handle cast(const T& src, return_value_policy policy, handle parent) { if (!src) return none().inc_ref(); return value_conv::cast(*src, policy, parent); } bool load(handle src, bool convert) { if (!src) { return false; } else if (src.is_none()) { return true; // default-constructed value is already empty } value_conv inner_caster; if (!inner_caster.load(src, convert)) return false; value.emplace(cast_op(std::move(inner_caster))); return true; } PYBIND11_TYPE_CASTER(T, _("Optional[") + value_conv::name() + _("]")); }; #if PYBIND11_HAS_OPTIONAL template struct type_caster> : public optional_caster> {}; template<> struct type_caster : public void_caster {}; #endif #if PYBIND11_HAS_EXP_OPTIONAL template struct type_caster> : public optional_caster> {}; template<> struct type_caster : public void_caster {}; #endif /// Visit a variant and cast any found type to Python struct variant_caster_visitor { return_value_policy policy; handle parent; template handle operator()(T &&src) const { return make_caster::cast(std::forward(src), policy, parent); } }; /// Helper class which abstracts away variant's `visit` function. `std::variant` and similar /// `namespace::variant` types which provide a `namespace::visit()` function are handled here /// automatically using argument-dependent lookup. Users can provide specializations for other /// variant-like classes, e.g. `boost::variant` and `boost::apply_visitor`. template class Variant> struct visit_helper { template static auto call(Args &&...args) -> decltype(visit(std::forward(args)...)) { return visit(std::forward(args)...); } }; /// Generic variant caster template struct variant_caster; template class V, typename... Ts> struct variant_caster> { static_assert(sizeof...(Ts) > 0, "Variant must consist of at least one alternative."); template bool load_alternative(handle src, bool convert, type_list) { auto caster = make_caster(); if (caster.load(src, convert)) { value = cast_op(caster); return true; } return load_alternative(src, convert, type_list{}); } bool load_alternative(handle, bool, type_list<>) { return false; } bool load(handle src, bool convert) { // Do a first pass without conversions to improve constructor resolution. // E.g. `py::int_(1).cast>()` needs to fill the `int` // slot of the variant. Without two-pass loading `double` would be filled // because it appears first and a conversion is possible. if (convert && load_alternative(src, false, type_list{})) return true; return load_alternative(src, convert, type_list{}); } template static handle cast(Variant &&src, return_value_policy policy, handle parent) { return visit_helper::call(variant_caster_visitor{policy, parent}, std::forward(src)); } using Type = V; PYBIND11_TYPE_CASTER(Type, _("Union[") + detail::concat(make_caster::name()...) + _("]")); }; #if PYBIND11_HAS_VARIANT template struct type_caster> : variant_caster> { }; #endif NAMESPACE_END(detail) inline std::ostream &operator<<(std::ostream &os, const handle &obj) { os << (std::string) str(obj); return os; } NAMESPACE_END(pybind11) #if defined(_MSC_VER) #pragma warning(pop) #endif