]> git.ipfire.org Git - people/ms/libloc.git/blob - src/python/as.c
python: Only use global loc context
[people/ms/libloc.git] / src / python / as.c
1 /*
2 libloc - A library to determine the location of someone on the Internet
3
4 Copyright (C) 2017 IPFire Development Team <info@ipfire.org>
5
6 This library is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Lesser General Public
8 License as published by the Free Software Foundation; either
9 version 2.1 of the License, or (at your option) any later version.
10
11 This library is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
15 */
16
17 #include <Python.h>
18
19 #include <loc/libloc.h>
20 #include <loc/as.h>
21 #include <loc/stringpool.h>
22
23 #include "locationmodule.h"
24 #include "as.h"
25
26 static PyObject* AS_new(PyTypeObject* type, PyObject* args, PyObject* kwds) {
27 // Create stringpool
28 struct loc_stringpool* pool;
29 int r = loc_stringpool_new(loc_ctx, &pool);
30 if (r)
31 return NULL;
32
33 ASObject* self = (ASObject*)type->tp_alloc(type, 0);
34 if (self) {
35 self->ctx = loc_ref(loc_ctx);
36 self->pool = pool;
37 }
38
39 return (PyObject*)self;
40 }
41
42 static void AS_dealloc(ASObject* self) {
43 if (self->as)
44 loc_as_unref(self->as);
45
46 if (self->pool)
47 loc_stringpool_unref(self->pool);
48
49 if (self->ctx)
50 loc_unref(self->ctx);
51
52 Py_TYPE(self)->tp_free((PyObject* )self);
53 }
54
55 static int AS_init(ASObject* self, PyObject* args, PyObject* kwargs) {
56 uint32_t number = 0;
57
58 if (!PyArg_ParseTuple(args, "i", &number))
59 return -1;
60
61 // Create the AS object
62 int r = loc_as_new(self->ctx, self->pool, &self->as, number);
63 if (r)
64 return -1;
65
66 return 0;
67 }
68
69 static PyObject* AS_get_number(ASObject* self) {
70 uint32_t number = loc_as_get_number(self->as);
71
72 return PyLong_FromLong(number);
73 }
74
75 static PyObject* AS_get_name(ASObject* self) {
76 const char* name = loc_as_get_name(self->as);
77
78 return PyUnicode_FromString(name);
79 }
80
81 static struct PyGetSetDef AS_getsetters[] = {
82 {
83 "name",
84 (getter)AS_get_name,
85 NULL,
86 NULL,
87 NULL,
88 },
89 {
90 "number",
91 (getter)AS_get_number,
92 NULL,
93 NULL,
94 NULL,
95 },
96 { NULL },
97 };
98
99 PyTypeObject ASType = {
100 PyVarObject_HEAD_INIT(NULL, 0)
101 tp_name: "location.AS",
102 tp_basicsize: sizeof(ASObject),
103 tp_flags: Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
104 tp_new: AS_new,
105 tp_dealloc: (destructor)AS_dealloc,
106 tp_init: (initproc)AS_init,
107 tp_doc: "AS object",
108 tp_getset: AS_getsetters,
109 };