blob: 79beba364711abaedda1573b92a989aae6625ad9 (
plain) (
blame)
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
|
#include "node.h"
#include <library/cpp/yson/node/node.h>
#include <library/cpp/pybind/cast.h>
#include <Python.h>
namespace NYT {
PyObject* BuildPyObject(const TNode& node) {
switch (node.GetType()) {
case TNode::Bool:
return NPyBind::BuildPyObject(node.AsBool());
case TNode::Int64:
return NPyBind::BuildPyObject(node.AsInt64());
case TNode::Uint64:
return NPyBind::BuildPyObject(node.AsUint64());
case TNode::Double:
return NPyBind::BuildPyObject(node.AsDouble());
case TNode::String:
return NPyBind::BuildPyObject(node.AsString());
case TNode::List:
return NPyBind::BuildPyObject(node.AsList());
case TNode::Map:
return NPyBind::BuildPyObject(node.AsMap());
case TNode::Null:
Py_RETURN_NONE;
case TNode::Undefined:
ythrow TNode::TTypeError() << "BuildPyObject called for undefined TNode";
}
}
} // namespace NYT
namespace NPyBind {
template <>
bool FromPyObject(PyObject* obj, NYT::TNode& res) {
if (obj == Py_None) {
res = NYT::TNode::CreateEntity();
return true;
}
if (PyBool_Check(obj)) {
res = false;
return FromPyObject(obj, res.As<bool>());
}
if (PyFloat_Check(obj)) {
res = 0.0;
return FromPyObject(obj, res.As<double>());
}
#if PY_MAJOR_VERSION < 3
if (PyString_Check(obj)) {
res = TString();
return FromPyObject(obj, res.As<TString>());
}
#else
if (PyUnicode_Check(obj)) {
res = TString();
return FromPyObject(obj, res.As<TString>());
}
if (PyBytes_Check(obj)) {
res = TString();
return FromPyObject(obj, res.As<TString>());
}
#endif
if (PyList_Check(obj)) {
res = NYT::TNode::CreateList();
return FromPyObject(obj, res.AsList());
}
if (PyDict_Check(obj)) {
res = NYT::TNode::CreateMap();
return FromPyObject(obj, res.AsMap());
}
#if PY_MAJOR_VERSION < 3
if (PyInt_Check(obj)) {
auto valAsLong = PyInt_AsLong(obj);
if (valAsLong == -1 && PyErr_Occurred()) {
return false;
}
res = valAsLong;
return true;
}
#endif
if (PyLong_Check(obj)) {
int overflow = 0;
auto valAsLong = PyLong_AsLongAndOverflow(obj, &overflow);
if (!overflow) {
if (valAsLong == -1 && PyErr_Occurred()) {
return false;
}
res = valAsLong;
return true;
}
auto valAsULong = PyLong_AsUnsignedLong(obj);
if (valAsULong == static_cast<decltype(valAsULong)>(-1) && PyErr_Occurred()) {
return false;
}
res = valAsULong;
return true;
}
return false;
}
} // namespace NPyBind
|