-
Notifications
You must be signed in to change notification settings - Fork 153
/
nb_list.h
82 lines (57 loc) · 2.19 KB
/
nb_list.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/*
nanobind/stl/detail/nb_list.h: base class of list casters
Copyright (c) 2022 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 <nanobind/nanobind.h>
NAMESPACE_BEGIN(NB_NAMESPACE)
NAMESPACE_BEGIN(detail)
template <typename List, typename Entry> struct list_caster {
NB_TYPE_CASTER(List, const_name(NB_TYPING_LIST "[") +
make_caster<Entry>::Name + const_name("]"));
using Caster = make_caster<Entry>;
template <typename T> using has_reserve = decltype(std::declval<T>().reserve(0));
bool from_python(handle src, uint8_t flags, cleanup_list *cleanup) noexcept {
size_t size;
PyObject *temp;
/* Will initialize 'size' and 'temp'. All return values and
return parameters are zero/NULL in the case of a failure. */
PyObject **o = seq_get(src.ptr(), &size, &temp);
value.clear();
if constexpr (is_detected_v<has_reserve, List>)
value.reserve(size);
Caster caster;
bool success = o != nullptr;
if (is_base_caster_v<Caster> && !std::is_pointer_v<Entry>)
flags |= (uint8_t) cast_flags::none_disallowed;
for (size_t i = 0; i < size; ++i) {
if (!caster.from_python(o[i], flags, cleanup)) {
success = false;
break;
}
value.push_back(caster.operator cast_t<Entry>());
}
Py_XDECREF(temp);
return success;
}
template <typename T>
static handle from_cpp(T &&src, rv_policy policy, cleanup_list *cleanup) {
object ret = steal(PyList_New(src.size()));
if (ret.is_valid()) {
Py_ssize_t index = 0;
for (auto &&value : src) {
handle h = Caster::from_cpp(forward_like<T>(value), policy, cleanup);
if (!h.is_valid()) {
ret.reset();
break;
}
NB_LIST_SET_ITEM(ret.ptr(), index++, h.ptr());
}
}
return ret.release();
}
};
NAMESPACE_END(detail)
NAMESPACE_END(NB_NAMESPACE)