File: pycomp.cpp

package info (click to toggle)
libdnf 0.75.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 10,468 kB
  • sloc: cpp: 48,297; xml: 1,638; python: 1,537; ansic: 1,223; sql: 227; sh: 54; makefile: 39
file content (68 lines) | stat: -rw-r--r-- 2,197 bytes parent folder | download | duplicates (4)
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
/*
 * Copyright (C) 2012-2013 Red Hat, Inc.
 *
 * Licensed under the GNU Lesser General Public License Version 2.1
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

#include <Python.h>
#include "pycomp.hpp"

/**
 * unicode string in Python 2/3 to c string converter,
 * you need to call Py_XDECREF(tmp_py_str) after usage of returned string
 */
static char *
pycomp_get_string_from_unicode(PyObject *str_u, PyObject **tmp_py_str)
{
    *tmp_py_str = PyUnicode_AsEncodedString(str_u, "utf-8", "replace");
    if (*tmp_py_str) {
        return PyBytes_AsString(*tmp_py_str);
    } else {
        return NULL;
    }
}

PycompString::PycompString(PyObject * str)
{
    if (PyUnicode_Check(str)) {
        PyObject * pyString;
        auto cString = pycomp_get_string_from_unicode(str, &pyString);
        if (cString) {
            cppString = cString;
            isNull = false;
        }
        Py_XDECREF(pyString);
#if PY_MAJOR_VERSION < 3
    } else if (PyString_Check(str)) {
        auto cString = PyString_AsString(str);
        if (cString) {
            cppString = cString;
            isNull = false;
        }
    } else
        PyErr_SetString(PyExc_TypeError, "Expected a string or a unicode object");
#else
    } else if (PyBytes_Check(str)) {
        auto cString = PyBytes_AsString(str);
        if (cString) {
            cppString = cString;
            isNull = false;
        }
    } else
        PyErr_SetString(PyExc_TypeError, "Expected a string or a unicode object");
#endif
}