chiark / gitweb /
shared: switch our hash table implementation over to SipHash
[elogind.git] / src / python-systemd / pyutil.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3 /***
4   This file is part of systemd.
5
6   Copyright 2013 Zbigniew JÄ™drzejewski-Szmek <zbyszek@in.waw.pl>
7
8   systemd is free software; you can redistribute it and/or modify it
9   under the terms of the GNU Lesser General Public License as published by
10   the Free Software Foundation; either version 2.1 of the License, or
11   (at your option) any later version.
12
13   systemd is distributed in the hope that it will be useful, but
14   WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16   Lesser General Public License for more details.
17
18   You should have received a copy of the GNU Lesser General Public License
19   along with systemd; If not, see <http://www.gnu.org/licenses/>.
20 ***/
21
22 #include <Python.h>
23 #include "pyutil.h"
24
25 void cleanup_Py_DECREFp(PyObject **p) {
26         if (!*p)
27                 return;
28
29         Py_DECREF(*p);
30 }
31
32 PyObject* absolute_timeout(uint64_t t) {
33         if (t == (uint64_t) -1)
34                 return PyLong_FromLong(-1);
35         else {
36                 struct timespec ts;
37                 uint64_t n;
38                 int msec;
39
40                 clock_gettime(CLOCK_MONOTONIC, &ts);
41                 n = (uint64_t) ts.tv_sec * 1000000 + ts.tv_nsec / 1000;
42                 msec = t > n ? (int) ((t - n + 999) / 1000) : 0;
43
44                 return PyLong_FromLong(msec);
45         }
46 }
47
48 int set_error(int r, const char* path, const char* invalid_message) {
49         if (r >= 0)
50                 return r;
51         if (r == -EINVAL && invalid_message)
52                 PyErr_SetString(PyExc_ValueError, invalid_message);
53         else if (r == -ENOMEM)
54                 PyErr_SetString(PyExc_MemoryError, "Not enough memory");
55         else {
56                 errno = -r;
57                 PyErr_SetFromErrnoWithFilename(PyExc_OSError, path);
58         }
59         return -1;
60 }
61
62 #if PY_MAJOR_VERSION >=3 && PY_MINOR_VERSION >= 1
63 int Unicode_FSConverter(PyObject* obj, void *_result) {
64         PyObject **result = _result;
65
66         assert(result);
67
68         if (!obj)
69                 /* cleanup: we don't return Py_CLEANUP_SUPPORTED, so
70                  * we can assume that it was PyUnicode_FSConverter. */
71                 return PyUnicode_FSConverter(obj, result);
72
73         if (obj == Py_None) {
74                 *result = NULL;
75                 return 1;
76         }
77
78         return PyUnicode_FSConverter(obj, result);
79 }
80 #endif