summaryrefslogtreecommitdiffstats
path: root/python/generic.h
blob: 60f95318ba67fcbe9cf67accd786bdb096d75a9d (plain)
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
// -*- mode: cpp; mode: fold -*-
// Description								/*{{{*/
// $Id: generic.h,v 1.4 2002/03/10 05:45:34 mdz Exp $
/* ######################################################################

   generic - Some handy functions to make integration a tad simpler

   Python needs this little _HEAD tacked onto the front of the object..
   This complicates the integration with C++. We use some templates to
   make that quite transparent to us. It would have been nice if Python
   internally used a page from the C++ ref counting book to hide its little
   header from the world, but it doesn't.

   The CppPyObject has the target object and the Python header, this is
   needed to ensure proper alignment.
   GetCpp returns the C++ object from a PyObject.
   CppPyObject_NEW creates the Python object and then uses placement new
     to init the C++ class.. This is good for simple situations and as an
     example on how to do it in other more specific cases.
   CppPyObject_Dealloc should be used in the Type as the destructor
     function.
   HandleErrors converts errors from the internal _error stack into Python
     exceptions and makes sure the _error stack is empty.

   ##################################################################### */
									/*}}}*/
#ifndef GENERIC_H
#define GENERIC_H

#include <Python.h>
#include <string>
#include <iostream>
#include <new>
#include <langinfo.h>

/**
 * Exception class for almost all Python errors
 */
extern PyObject *PyAptError;
extern PyObject *PyAptWarning;
/**
 * Exception class for invalidated cache objects.
 */
extern PyObject *PyAptCacheMismatchError;

#if PYTHON_API_VERSION < 1013
typedef int Py_ssize_t;
#endif

/* Define compatibility for Python 3.
 *
 * We will use the names PyString_* to refer to the default string type
 * of the current Python version (PyString on 2.X, PyUnicode on 3.X).
 *
 * When we really need unicode strings, we will use PyUnicode_* directly, as
 * long as it exists in Python 2 and Python 3.
 *
 * When we want bytes in Python 3, we use PyBytes*_ instead of PyString_* and
 * define aliases from PyBytes_* to PyString_* for Python 2.
 */

#if PY_MAJOR_VERSION >= 3
#define PyString_Check PyUnicode_Check
#define PyString_FromString PyUnicode_FromString
#define PyString_FromStringAndSize PyUnicode_FromStringAndSize
#define PyString_AsString PyUnicode_AsString
#define PyString_FromFormat PyUnicode_FromFormat
#define PyString_Type PyUnicode_Type
#define PyInt_Check PyLong_Check
#define PyInt_AsLong PyLong_AsLong
#define PyInt_FromLong PyLong_FromLong
#endif

static inline const char *PyUnicode_AsString(PyObject *op) {
    // Convert to bytes object, using the default encoding.
#if PY_MAJOR_VERSION >= 3 && PY_MINOR_VERSION >= 3
    return PyUnicode_AsUTF8(op);
#else
    // Use Python-internal API, there is no other way to do this
    // without a memory leak.
    PyObject *bytes = _PyUnicode_AsDefaultEncodedString(op, 0);
    return bytes ? PyBytes_AS_STRING(bytes) : 0;
#endif
}

// Convert any type of string based object to a const char.
#if PY_MAJOR_VERSION < 3
static inline const char *PyObject_AsString(PyObject *object) {
    if (PyBytes_Check(object))
        return PyBytes_AsString(object);
    else if (PyUnicode_Check(object))
        return PyUnicode_AsString(object);
    else
        PyErr_SetString(PyExc_TypeError, "Argument must be str.");
    return 0;
}
#else
static inline const char *PyObject_AsString(PyObject *object) {
    if (PyUnicode_Check(object) == 0) {
        PyErr_SetString(PyExc_TypeError, "Argument must be str.");
        return 0;
    }
    return PyUnicode_AsString(object);
}
#endif

template <class T> struct CppPyObject : public PyObject
{
   // We are only using CppPyObject and friends as dumb structs only, ie the
   // c'tor is never called.
   // However if T doesn't have a default c'tor C++ doesn't generate one for
   // CppPyObject (since it can't know how it should initialize Object).
   //
   // This causes problems then in CppPyObject, for which C++ can't create
   // a c'tor that calls the base class c'tor (which causes a compilation
   // error).
   // So basically having the c'tor here removes the need for T to have a
   // default c'tor, which is not always desireable.
   CppPyObject() { };

   // The owner of the object. The object keeps a reference to it during its
   // lifetime.
   PyObject *Owner;

   // Flag which causes the underlying object to not be deleted.
   bool NoDelete;

   // The underlying C++ object.
   T Object;
};

template <class T>
inline T &GetCpp(PyObject *Obj)
{
   return ((CppPyObject<T> *)Obj)->Object;
}

template <class T>
inline PyObject *GetOwner(PyObject *Obj)
{
   return ((CppPyObject<T> *)Obj)->Owner;
}


template <class T>
inline CppPyObject<T> *CppPyObject_NEW(PyObject *Owner,PyTypeObject *Type)
{
   #ifdef ALLOC_DEBUG
   std::cerr << "=== ALLOCATING " << Type->tp_name << "+ ===\n";
   #endif
   CppPyObject<T> *New = (CppPyObject<T>*)Type->tp_alloc(Type, 0);
   new (&New->Object) T;
   New->Owner = Owner;
   Py_XINCREF(Owner);
   return New;
}

template <class T,class A>
inline CppPyObject<T> *CppPyObject_NEW(PyObject *Owner, PyTypeObject *Type,A const &Arg)
{
   #ifdef ALLOC_DEBUG
   std::cerr << "=== ALLOCATING " << Type->tp_name << "+ ===\n";
   #endif
   CppPyObject<T> *New = (CppPyObject<T>*)Type->tp_alloc(Type, 0);
   new (&New->Object) T(Arg);
   New->Owner = Owner;
   Py_XINCREF(Owner);
   return New;
}

// Traversal and Clean for  objects
template <class T>
int CppTraverse(PyObject *self, visitproc visit, void* arg) {
    Py_VISIT(((CppPyObject<T> *)self)->Owner);
    return 0;
}

template <class T>
int CppClear(PyObject *self) {
    Py_CLEAR(((CppPyObject<T> *)self)->Owner);
    return 0;
}

template <class T>
void CppDealloc(PyObject *iObj)
{
   #ifdef ALLOC_DEBUG
   std::cerr << "=== DEALLOCATING " << iObj->ob_type->tp_name << "+ ===\n";
   #endif
   if (iObj->ob_type->tp_flags & Py_TPFLAGS_HAVE_GC)
       PyObject_GC_UnTrack(iObj);
   CppPyObject<T> *Obj = (CppPyObject<T> *)iObj;
   if (!((CppPyObject<T>*)Obj)->NoDelete)
      Obj->Object.~T();
   CppClear<T>(iObj);
   iObj->ob_type->tp_free(iObj);
}


template <class T>
void CppDeallocPtr(PyObject *iObj)
{
   #ifdef ALLOC_DEBUG
   std::cerr << "=== DEALLOCATING " << iObj->ob_type->tp_name << "*+ ===\n";
   #endif
   if (iObj->ob_type->tp_flags & Py_TPFLAGS_HAVE_GC)
       PyObject_GC_UnTrack(iObj);
   CppPyObject<T> *Obj = (CppPyObject<T> *)iObj;
   if (!((CppPyObject<T>*)Obj)->NoDelete)  {
      delete Obj->Object;
      Obj->Object = NULL;
   }
   CppClear<T>(iObj);
   iObj->ob_type->tp_free(iObj);
}

inline PyObject *CppPyString(const std::string &Str)
{
   return PyString_FromStringAndSize(Str.c_str(),Str.length());
}

inline PyObject *CppPyString(const char *Str)
{
   if (Str == 0)
      return PyString_FromString("");
   return PyString_FromString(Str);
}

inline PyObject *CppPyLocaleString(const std::string &Str)
{
   char const * const codeset = nl_langinfo(CODESET);
   return PyUnicode_Decode(Str.c_str(), Str.length(), codeset, "replace");
}

#if PY_MAJOR_VERSION >= 3
static inline PyObject *CppPyPath(const std::string &path)
{
    return PyUnicode_DecodeFSDefaultAndSize(path.c_str(), path.length());
}

static inline PyObject *CppPyPath(const char *path)
{
   if (path == nullptr)
      path = "";
   return PyUnicode_DecodeFSDefault(path);
}
#else
template<typename T> static inline PyObject *CppPyPath(T path) {
   return CppPyString(path);
}
#endif

// Convert _error into Python exceptions
PyObject *HandleErrors(PyObject *Res = 0);

// Convert a list of strings to a char **
const char **ListToCharChar(PyObject *List,bool NullTerm = false);
PyObject *CharCharToList(const char **List,unsigned long Size = 0);

/* Happy number conversion, thanks to overloading */
inline PyObject *MkPyNumber(unsigned long long o) { return PyLong_FromUnsignedLongLong(o); }
inline PyObject *MkPyNumber(unsigned long o) { return PyLong_FromUnsignedLong(o); }
inline PyObject *MkPyNumber(unsigned int o) { return PyLong_FromUnsignedLong(o); }
inline PyObject *MkPyNumber(unsigned short o) { return PyInt_FromLong(o); }
inline PyObject *MkPyNumber(unsigned char o) { return PyInt_FromLong(o); }

inline PyObject *MkPyNumber(long long o) { return PyLong_FromLongLong(o); }
inline PyObject *MkPyNumber(long o) { return PyInt_FromLong(o); }
inline PyObject *MkPyNumber(int o) { return PyInt_FromLong(o); }
inline PyObject *MkPyNumber(short o) { return PyInt_FromLong(o); }
inline PyObject *MkPyNumber(signed char o) { return PyInt_FromLong(o); }

inline PyObject *MkPyNumber(double o) { return PyFloat_FromDouble(o); }

#  define _PyAptObject_getattro 0


/**
 * Magic class for file name handling
 *
 * This manages decoding file names from Python objects; bytes and unicode
 * objects. On Python 2, this does the same conversion as PyObject_AsString,
 * on Python3, it uses PyUnicode_EncodeFSDefault for unicode objects.
 */
class PyApt_Filename {
public:
   PyObject *object;
   const char *path;

   PyApt_Filename() {
      object = NULL;
      path = NULL;
   }

   int init(PyObject *object);

   ~PyApt_Filename() {
      Py_XDECREF(object);
   }

   static int Converter(PyObject *object, void *out) {
      return static_cast<PyApt_Filename *>(out)->init(object);
   }

   operator const char *() {
      return path;
   }
   operator const std::string() {
      return path;
   }

   const char *operator=(const char *path) {
      return this->path = path;
   }
};


/**
 * Basic smart pointer to hold initial objects.
 *
 * This is like a std::unique_ptr<PyObject, decltype(&Py_DecRef)> to some extend,
 * but it is for initialization only, and hence will also clear out any members
 * in case it deletes the instance (the error case).
 */
template <class T, bool clear=true> struct PyApt_UniqueObject {
    T *self;
    explicit PyApt_UniqueObject(T *self) : self(self) { }
    ~PyApt_UniqueObject() { reset(NULL); }
    void reset(T *newself) { if (clear && self && Py_TYPE(self)->tp_clear) Py_TYPE(self)->tp_clear(self); Py_XDECREF(self); self = newself; }
    PyApt_UniqueObject<T> operator =(PyApt_UniqueObject<T>) = delete;
    bool operator ==(void *other) { return self == other; }
    T *operator ->() { return self; }
    T *get() { return self; }
    T *release() { T *ret = self; self = NULL; return ret; }
};
#endif