12#include "detail/common.h"
13#include "detail/type_caster_base.h"
27 template <
typename T2>
29 test_comparable(
decltype(std::declval<const T2 &>() == std::declval<const T2 &>()) *);
30 template <
typename T2>
32 template <
typename T2>
33 static std::true_type
test_value(
typename T2::value_type *);
34 template <
typename T2>
36 template <
typename T2>
37 static std::true_type
test_pair(
typename T2::first_type *,
typename T2::second_type *);
38 template <
typename T2>
42 = std::is_same<std::true_type, decltype(test_comparable<T>(
nullptr))>::value;
43 static constexpr const bool is_pair
44 = std::is_same<std::true_type, decltype(test_pair<T>(
nullptr,
nullptr))>::value;
46 = std::is_same<std::true_type, decltype(test_value<T>(
nullptr))>::value;
51template <
typename T,
typename SFINAE =
void>
76template <
typename,
typename,
typename... Args>
78template <
typename,
typename,
typename... Args>
80template <
typename,
typename,
typename... Args>
82template <
typename,
typename,
typename... Args>
85template <
typename Vector,
typename Class_>
87 cl.def(init<const Vector &>(),
"Copy constructor");
90template <
typename Vector,
typename Class_>
92 using T =
typename Vector::value_type;
99 [](
const Vector &v,
const T &x) {
return std::count(v.begin(), v.end(), x); },
101 "Return the number of times ``x`` appears in the list");
105 [](Vector &v,
const T &x) {
106 auto p = std::find(v.begin(), v.end(), x);
114 "Remove the first item from the list whose value is x. "
115 "It is an error if there is no such item.");
119 [](
const Vector &v,
const T &x) {
return std::find(v.begin(), v.end(), x) != v.end(); },
121 "Return true the container contains ``x``");
127template <
typename Vector,
typename Class_>
130 using T =
typename Vector::value_type;
131 using SizeType =
typename Vector::size_type;
132 using DiffType =
typename Vector::difference_type;
134 auto wrap_i = [](DiffType i, SizeType n) {
138 if (i < 0 || (SizeType) i >= n) {
146 [](Vector &v,
const T &value) { v.push_back(value); },
148 "Add an item to the end of the list");
151 auto v = std::unique_ptr<Vector>(
new Vector());
154 v->push_back(h.cast<T>());
160 "clear", [](Vector &v) { v.clear(); },
"Clear the contents");
164 [](Vector &v,
const Vector &src) { v.insert(v.end(), src.begin(), src.end()); },
166 "Extend the list by appending all the items in the given list");
171 const size_t old_size = v.size();
175 v.push_back(h.cast<T>());
177 }
catch (
const cast_error &) {
178 v.erase(v.begin() +
static_cast<typename Vector::difference_type
>(old_size),
182 }
catch (
const std::exception &) {
189 "Extend the list by appending all the items in the given list");
193 [](Vector &v, DiffType i,
const T &x) {
198 if (i < 0 || (SizeType) i > v.size()) {
201 v.insert(v.begin() + i, x);
205 "Insert an item at a given position.");
213 T t = std::move(v.back());
217 "Remove and return the last item");
221 [wrap_i](Vector &v, DiffType i) {
222 i = wrap_i(i, v.size());
223 T t = std::move(v[(SizeType) i]);
224 v.erase(std::next(v.begin(), i));
228 "Remove and return the item at index ``i``");
230 cl.def(
"__setitem__", [wrap_i](Vector &v, DiffType i,
const T &t) {
231 i = wrap_i(i, v.size());
238 [](
const Vector &v,
const slice &
slice) -> Vector * {
239 size_t start = 0, stop = 0, step = 0, slicelength = 0;
241 if (!
slice.
compute(v.size(), &start, &stop, &step, &slicelength)) {
245 auto *seq =
new Vector();
246 seq->reserve((
size_t) slicelength);
248 for (
size_t i = 0; i < slicelength; ++i) {
249 seq->push_back(v[start]);
255 "Retrieve list elements using a slice object");
259 [](Vector &v,
const slice &
slice,
const Vector &value) {
260 size_t start = 0, stop = 0, step = 0, slicelength = 0;
261 if (!
slice.
compute(v.size(), &start, &stop, &step, &slicelength)) {
265 if (slicelength != value.size()) {
266 throw std::runtime_error(
267 "Left and right hand size of slice assignment have different sizes!");
270 for (
size_t i = 0; i < slicelength; ++i) {
275 "Assign list elements using a slice object");
279 [wrap_i](Vector &v, DiffType i) {
280 i = wrap_i(i, v.size());
281 v.erase(v.begin() + i);
283 "Delete the list elements at index ``i``");
288 size_t start = 0, stop = 0, step = 0, slicelength = 0;
290 if (!
slice.
compute(v.size(), &start, &stop, &step, &slicelength)) {
294 if (step == 1 &&
false) {
295 v.erase(v.begin() + (DiffType) start, v.begin() + DiffType(start + slicelength));
297 for (
size_t i = 0; i < slicelength; ++i) {
298 v.erase(v.begin() + DiffType(start));
303 "Delete list elements using a slice object");
308template <
typename Vector>
311 typename Vector::value_type &>>;
314template <
typename Vector,
typename Class_>
316 using T =
typename Vector::value_type;
317 using SizeType =
typename Vector::size_type;
318 using DiffType =
typename Vector::difference_type;
319 using ItType =
typename Vector::iterator;
321 auto wrap_i = [](DiffType i, SizeType n) {
325 if (i < 0 || (SizeType) i >= n) {
333 [wrap_i](Vector &v, DiffType i) -> T & {
334 i = wrap_i(i, v.size());
335 return v[(SizeType) i];
343 return make_iterator<return_value_policy::reference_internal, ItType, ItType, T &>(
351template <
typename Vector,
typename Class_>
353 using T =
typename Vector::value_type;
354 using SizeType =
typename Vector::size_type;
355 using DiffType =
typename Vector::difference_type;
356 using ItType =
typename Vector::iterator;
357 cl.def(
"__getitem__", [](
const Vector &v, DiffType i) -> T {
358 if (i < 0 && (i += v.size()) < 0) {
361 if ((SizeType) i >= v.size()) {
364 return v[(SizeType) i];
370 return make_iterator<return_value_policy::copy, ItType, ItType, T>(v.begin(), v.end());
376template <
typename Vector,
typename Class_>
378 ->
decltype(std::declval<std::ostream &>() << std::declval<typename Vector::value_type>(),
380 using size_type =
typename Vector::size_type;
385 std::ostringstream s;
387 for (size_type i = 0; i < v.size(); ++i) {
389 if (i != v.size() - 1) {
396 "Return the canonical string representation of this list.");
402template <
typename Vector,
typename =
void>
404template <
typename Vector>
407 enable_if_t<
std::is_same<decltype(format_descriptor<typename Vector::value_type>::format(),
408 std::declval<Vector>().data()),
409 typename Vector::value_type *>::value>> : std::true_type {};
414template <
typename... Args>
416 return detail::any_of<std::is_same<Args, buffer_protocol>...>::value;
423template <
typename Vector,
typename Class_,
typename... Args>
425 using T =
typename Vector::value_type;
428 "There is not an appropriate format descriptor for this vector");
436 static_cast<ssize_t>(
sizeof(T)),
445 if (info.ndim != 1 || info.strides[0] %
static_cast<ssize_t>(
sizeof(T))) {
446 throw type_error(
"Only valid 1D buffers can be copied to a vector");
448 if (!detail::compare_buffer_info<T>::compare(info)
449 || (
ssize_t)
sizeof(T) != info.itemsize) {
450 throw type_error(
"Format mismatch (Python: " + info.format
451 +
" C++: " + format_descriptor<T>::format() +
")");
454 T *p =
static_cast<T *
>(info.ptr);
456 T *end = p + info.shape[0] * step;
458 return Vector(p, end);
461 vec.reserve((
size_t) info.shape[0]);
462 for (; p != end; p += step) {
471template <
typename Vector,
typename Class_,
typename... Args>
474template <
typename Vector,
typename Class_,
typename... Args>
477 cl, detail::any_of<std::is_same<Args, buffer_protocol>...>{});
485template <
typename Vector,
typename holder_type = std::unique_ptr<Vector>,
typename... Args>
491 using vtype =
typename Vector::value_type;
492 auto *vtype_info = detail::get_type_info(
typeid(vtype));
493 bool local = !vtype_info || vtype_info->module_local;
495 Class_ cl(
scope,
name.c_str(), pybind11::module_local(local), std::forward<Args>(
args)...);
498 detail::vector_buffer<Vector, Class_, Args...>(cl);
503 detail::vector_if_copy_constructible<Vector, Class_>(cl);
506 detail::vector_if_equal_operator<Vector, Class_>(cl);
509 detail::vector_if_insertion_operator<Vector, Class_>(cl,
name);
512 detail::vector_modifiers<Vector, Class_>(cl);
515 detail::vector_accessor<Vector, Class_>(cl);
519 [](
const Vector &v) ->
bool {
return !v.empty(); },
520 "Check whether the list is nonempty");
522 cl.def(
"__len__", &Vector::size);
526 cl.def(init<size_type>());
529 (
void (Vector::*) (size_type count)) & Vector::resize,
530 "changes the number of elements stored");
533 [](Vector &v, SizeType i) {
536 v.erase(v.begin() + i);
537 },
"erases element at index ``i``");
539 cl.def(
"empty", &Vector::empty,
"checks whether the container is empty");
540 cl.def(
"size", &Vector::size,
"returns the number of elements");
541 cl.def(
"push_back", (
void (Vector::*)(
const T&)) &Vector::push_back,
"adds an element to the end");
542 cl.def(
"pop_back", &Vector::pop_back,
"removes the last element");
544 cl.def(
"max_size", &Vector::max_size,
"returns the maximum possible number of elements");
545 cl.def(
"reserve", &Vector::reserve,
"reserves storage");
546 cl.def(
"capacity", &Vector::capacity,
"returns the number of elements that can be held in currently allocated storage");
547 cl.def(
"shrink_to_fit", &Vector::shrink_to_fit,
"reduces memory usage by freeing unused memory");
549 cl.def(
"clear", &Vector::clear,
"clears the contents");
550 cl.def(
"swap", &Vector::swap,
"swaps the contents");
552 cl.def(
"front", [](Vector &v) {
553 if (v.size())
return v.front();
554 else throw index_error();
555 },
"access the first element");
557 cl.def(
"back", [](Vector &v) {
558 if (v.size())
return v.back();
559 else throw index_error();
560 },
"access the last element ");
574template <
typename,
typename,
typename... Args>
576template <
typename,
typename,
typename... Args>
580template <
typename Map,
typename Class_>
583 using KeyType =
typename Map::key_type;
584 using MappedType =
typename Map::mapped_type;
586 cl.def(
"__setitem__", [](Map &m,
const KeyType &k,
const MappedType &v) {
598template <
typename Map,
typename Class_>
602 using KeyType =
typename Map::key_type;
603 using MappedType =
typename Map::mapped_type;
605 cl.def(
"__setitem__", [](Map &m,
const KeyType &k,
const MappedType &v) {
607 auto r = m.emplace(k, v);
617template <
typename Map,
typename Class_>
619 ->
decltype(std::declval<std::ostream &>() << std::declval<typename Map::key_type>()
620 << std::declval<typename Map::mapped_type>(),
626 std::ostringstream s;
629 for (
auto const &kv : m) {
633 s << kv.first <<
": " << kv.second;
639 "Return the canonical string representation of this map.");
642template <
typename KeyType>
651template <
typename MappedType>
658template <
typename KeyType,
typename MappedType>
665template <
typename Map,
typename KeysView>
668 size_t len()
override {
return map.size(); }
670 bool contains(
const typename Map::key_type &k)
override {
return map.find(k) !=
map.end(); }
671 bool contains(
const object &)
override {
return false; }
675template <
typename Map,
typename ValuesView>
678 size_t len()
override {
return map.size(); }
683template <
typename Map,
typename ItemsView>
686 size_t len()
override {
return map.size(); }
693template <
typename Map,
typename holder_type = std::unique_ptr<Map>,
typename... Args>
695 using KeyType =
typename Map::key_type;
696 using MappedType =
typename Map::mapped_type;
697 using StrippedKeyType = detail::remove_cvref_t<KeyType>;
698 using StrippedMappedType = detail::remove_cvref_t<MappedType>;
699 using KeysView = detail::keys_view<StrippedKeyType>;
700 using ValuesView = detail::values_view<StrippedMappedType>;
701 using ItemsView = detail::items_view<StrippedKeyType, StrippedMappedType>;
707 auto *tinfo = detail::get_type_info(
typeid(MappedType));
708 bool local = !tinfo || tinfo->module_local;
710 tinfo = detail::get_type_info(
typeid(KeyType));
711 local = !tinfo || tinfo->module_local;
714 Class_ cl(
scope,
name.c_str(), pybind11::module_local(local), std::forward<Args>(
args)...);
717 std::string key_type_name(key_type_descr.text), mapped_type_name(mapped_type_descr.text);
720 if (key_type_name ==
"%") {
721 key_type_name = detail::type_info_description(
typeid(KeyType));
724 if (mapped_type_name ==
"%") {
725 mapped_type_name = detail::type_info_description(
typeid(MappedType));
729 if (!detail::get_type_info(
typeid(KeysView))) {
731 scope, (
"KeysView[" + key_type_name +
"]").
c_str(), pybind11::module_local(local));
732 keys_view.def(
"__len__", &KeysView::len);
738 static_cast<bool (KeysView::*)(
const KeyType &)
>(&KeysView::contains));
741 static_cast<bool (KeysView::*)(
const object &)
>(&KeysView::contains));
744 if (!detail::get_type_info(
typeid(ValuesView))) {
746 (
"ValuesView[" + mapped_type_name +
"]").
c_str(),
747 pybind11::module_local(local));
755 if (!detail::get_type_info(
typeid(ItemsView))) {
758 (
"ItemsView[" + key_type_name +
", ").append(mapped_type_name +
"]").
c_str(),
759 pybind11::module_local(local));
770 detail::map_if_insertion_operator<Map, Class_>(cl,
name);
774 [](
const Map &m) ->
bool {
return !m.empty(); },
775 "Check whether the map is nonempty");
786 return std::unique_ptr<KeysView>(
new detail::KeysViewImpl<Map, KeysView>(m));
794 return std::unique_ptr<ValuesView>(
new detail::ValuesViewImpl<Map, ValuesView>(m));
802 return std::unique_ptr<ItemsView>(
new detail::ItemsViewImpl<Map, ItemsView>(m));
809 [](Map &m,
const KeyType &k) -> MappedType & {
819 cl.def(
"__contains__", [](Map &m,
const KeyType &k) ->
bool {
827 cl.def(
"__contains__", [](Map &,
const object &) ->
bool {
return false; });
830 detail::map_assignment<Map, Class_>(cl);
832 cl.def(
"__delitem__", [](Map &m,
const KeyType &k) {
840 cl.def(
"__len__", &Map::size);
buffer_info request(bool writable=false) const
Fetch and hold an error which was already set in Python.
\rst Holds a reference to a Python object (no reference counting)
\rst Wraps a Python iterator so that it can also be used as a C++ input iterator
bool compute(size_t length, size_t *start, size_t *stop, size_t *step, size_t *slicelength) const
static constexpr auto name
size_t len_hint(handle h)
Get the length hint of a Python object.
typename std::enable_if< B, T >::type enable_if_t
from cpp_future import (convenient aliases from C++14/17)
#define PYBIND11_NAMESPACE_END(name)
#define PYBIND11_NAMESPACE_BEGIN(name)
@ reference_internal
This policy only applies to methods and properties.
const char * c_str(Args &&...args)
Constructs a std::string with the given arguments, stores it in internals, and returns its c_str().
iterator make_value_iterator(Iterator first, Sentinel last, Extra &&...extra)
Makes a python iterator over the values (.second) of a iterator over pairs from a first and past-the-...
detail::initimpl::constructor< Args... > init()
Binds an existing constructor taking arguments Args...
iterator make_key_iterator(Iterator first, Sentinel last, Extra &&...extra)
Makes a python iterator over the keys (.first) of a iterator over pairs from a first and past-the-end...
iterator make_iterator(Iterator first, Sentinel last, Extra &&...extra)
Makes a python iterator from a first and past-the-end C++ InputIterator.
class_< Vector, holder_type > bind_vector(handle scope, std::string const &name, Args &&...args)
void vector_buffer_impl(Class_ &cl, std::true_type)
void vector_if_equal_operator(const Args &...)
void vector_accessor(enable_if_t<!vector_needs_copy< Vector >::value, Class_ > &cl)
constexpr bool args_any_are_buffer()
void vector_if_copy_constructible(const Args &...)
void vector_buffer(Class_ &cl)
void map_assignment(const Args &...)
class_< Map, holder_type > bind_map(handle scope, const std::string &name, Args &&...args)
void vector_modifiers(const Args &...)
void vector_if_insertion_operator(const Args &...)
void map_if_insertion_operator(const Args &...)
bool contains(const typename Map::key_type &k) override
bool contains(const object &) override
Annotation for arguments.
Information record describing a Python buffer object.
static std::true_type test_value(typename T2::value_type *)
static constexpr const bool is_pair
static std::true_type test_comparable(decltype(std::declval< const T2 & >()==std::declval< const T2 & >()) *)
static constexpr const bool is_element
static std::true_type test_pair(typename T2::first_type *, typename T2::second_type *)
static constexpr const bool is_vector
static std::false_type test_value(...)
static std::false_type test_comparable(...)
static std::false_type test_pair(...)
virtual iterator iter()=0
virtual ~items_view()=default
Keep patient alive while nurse lives.
virtual bool contains(const object &k)=0
virtual ~keys_view()=default
virtual bool contains(const KeyType &k)=0
virtual iterator iter()=0
Annotation for function names.
Annotation for parent scope.
virtual ~values_view()=default
virtual iterator iter()=0