summaryrefslogtreecommitdiff
path: root/_dbus_bindings/bytes-impl.h
blob: c9753a3de89fa8c360849c3d576fbc936d19aec2 (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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
/* D-Bus Byte and ByteArray types.
 *
 * Copyright (C) 2006 Collabora Ltd.
 *
 * Licensed under the Academic Free License version 2.1
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 */

static PyTypeObject ByteType, ByteArrayType;

static inline int Byte_Check(PyObject *o)
{
    return (o->ob_type == &ByteType)
           || PyObject_IsInstance(o, (PyObject *)&ByteType);
}

static inline int ByteArray_Check(PyObject *o)
{
    return (o->ob_type == &ByteArrayType)
           || PyObject_IsInstance(o, (PyObject *)&ByteArrayType);
}

PyDoc_STRVAR(Byte_tp_doc,
"Byte(integer or str of length 1)\n"
"\n"
"Byte is a subtype of str, restricted to length exactly 1.\n"
"\n"
"A Byte b also supports the following operations:\n"
"\n"
"* int(b) == long(b) == float(b) == ord(b)\n"
"\n"
"* oct(b), hex(b)\n"
);

static inline unsigned char
Byte_as_uchar(PyObject *self)
{
    return (unsigned char) (PyString_AS_STRING (self)[0]);
}

PyObject *allocated_bytes[256] = {NULL};

static PyObject *
Byte_from_uchar(unsigned char data)
{
    PyObject *ret;
    ret = allocated_bytes[data];
    if (!ret) {
        char c[] = { (char)data, '\0' };
        PyObject *tuple = Py_BuildValue("(s#)", c, 1);
        DBG("Allocating a new Byte of value \\x%02x", data);

        if (!tuple) return NULL;

        ret = PyString_Type.tp_new(&ByteType, tuple, NULL);
        Py_DECREF(tuple);
        tuple = NULL;

#ifdef USING_DBG
        fprintf(stderr, "New Byte of value \\x%02x: ", data);
        PyObject_Print(ret, stderr, 0);
        fprintf(stderr, "\n");
#endif

        Py_INCREF(ret);
        allocated_bytes[data] = ret;
      }
    Py_INCREF(ret);
    return ret;
}

static PyObject *
Byte_new(PyTypeObject *cls, PyObject *args, PyObject *kwargs)
{
    PyObject *arg;
    PyObject *string;
    PyObject *tuple;

    if (PyTuple_Size(args) != 1 || (kwargs && PyDict_Size(kwargs) != 0)) {
        PyErr_SetString(PyExc_TypeError, "Byte constructor takes exactly one "
                        "positional argument");
        return NULL;
    }

    /* arg is only a borrowed ref for the moment */
    arg = PyTuple_GetItem(args, 0);

    if (PyString_Check(arg)) {
        /* string of length 1, we hope */
        if (PyString_GET_SIZE(arg) != 1) {
            goto bad_arg;
        }
        if (arg->ob_type == &ByteType) {
            Py_INCREF(arg);
            return arg;
        }
        if (cls == &ByteType) {
            /* we know that the Byte type is the same as a string
             * internally, so fast-track it */
            return Byte_from_uchar((unsigned char)(PyString_AS_STRING(arg)[0]));
        }
        /* only a borrowed reference so far, take ownership */
        Py_INCREF(arg);
    }
    else if (PyInt_Check(arg)) {
        long i = PyInt_AS_LONG(arg);

        if (i < 0 || i > 255) goto bad_range;
        /* make a byte object, which is a length-1 string - now it's a new
        reference */
        arg = Byte_from_uchar((unsigned char)i);
        if (!arg) return NULL;
        /* if that's the type we wanted, there's nothing more to do */
        if (cls == &ByteType) return arg;
    }
    else {
        goto bad_arg;
    }

    /* so here's the complicated case: we're trying to instantiate a subclass
    so we can't just allocate a Byte and go "it'll all be fine".

    By now, we do have a string-of-length-1 to use as an argument to the c'tor
    */
    tuple = Py_BuildValue("(O)", arg);
    if (!tuple) return NULL;
    Py_DECREF(arg);
    arg = NULL;

    string = PyString_Type.tp_new(cls, tuple, NULL);
    Py_DECREF(tuple);
    tuple = NULL;
    return string;

bad_arg:
    PyErr_SetString(PyExc_TypeError, "Expected a string of length 1, "
                    "or an int in the range 0-255");
    return NULL;
bad_range:
    PyErr_SetString(PyExc_ValueError, "Integer outside range 0-255");
    return NULL;
}

static PyObject *Byte_nb_int (PyObject *self)
{
    return PyInt_FromLong(Byte_as_uchar(self));
}

static PyObject *Byte_nb_float (PyObject *self)
{
    return PyFloat_FromDouble(Byte_as_uchar(self));
}

static PyObject *Byte_nb_long (PyObject *self)
{
    return PyLong_FromLong(Byte_as_uchar(self));
}

static PyObject *Byte_nb_oct (PyObject *self)
{
    PyObject *i = PyInt_FromLong(Byte_as_uchar(self));
    if (!i) return NULL;
    PyObject *s = (i->ob_type->tp_as_number->nb_oct) (i);
    Py_XDECREF (i);
    return s;
}

static PyObject *Byte_nb_hex (PyObject *self)
{
    PyObject *i = PyInt_FromLong(Byte_as_uchar(self));
    if (!i) return NULL;
    PyObject *s = (i->ob_type->tp_as_number->nb_hex) (i);
    Py_XDECREF (i);
    return s;
}

static PyNumberMethods Byte_tp_as_number = {
        0,                                      /* nb_add */
        0,                                      /* nb_subtract */
        0,                                      /* nb_multiply */
        0,                                      /* nb_divide */
        0,                                      /* nb_remainder */
        0,                                      /* nb_divmod */
        0,                                      /* nb_power */
        0,                                      /* nb_negative */
        0,                                      /* nb_positive */
        0,                                      /* nb_absolute */
        0,                                      /* nb_nonzero */
        0,                                      /* nb_invert */
        0,                                      /* nb_lshift */
        0,                                      /* nb_rshift */
        0,                                      /* nb_and */
        0,                                      /* nb_xor */
        0,                                      /* nb_or */
        0,                                      /* nb_coerce */
        (unaryfunc)Byte_nb_int,                 /* nb_int */
        (unaryfunc)Byte_nb_long,                /* nb_long */
        (unaryfunc)Byte_nb_float,               /* nb_float */
        (unaryfunc)Byte_nb_oct,                 /* nb_oct */
        (unaryfunc)Byte_nb_hex,                 /* nb_hex */
        0,                                      /* nb_inplace_add */
        0,                                      /* nb_inplace_subtract */
        0,                                      /* nb_inplace_multiply */
        0,                                      /* nb_inplace_divide */
        0,                                      /* nb_inplace_remainder */
        0,                                      /* nb_inplace_power */
        0,                                      /* nb_inplace_lshift */
        0,                                      /* nb_inplace_rshift */
        0,                                      /* nb_inplace_and */
        0,                                      /* nb_inplace_xor */
        0,                                      /* nb_inplace_or */
        0,                                      /* nb_floor_divide */
        0,                                      /* nb_true_divide */
        0,                                      /* nb_inplace_floor_divide */
        0,                                      /* nb_inplace_true_divide */
};

static PyTypeObject ByteType = {
        PyObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type))
        0,
        "dbus.Byte",
        0,
        0,
        0,                                      /* tp_dealloc */
        0,                                      /* tp_print */
        0,                                      /* tp_getattr */
        0,                                      /* tp_setattr */
        0,                                      /* tp_compare */
        str_subclass_tp_repr,                   /* tp_repr */
        &Byte_tp_as_number,
        0,                                      /* tp_as_sequence */
        0,                                      /* tp_as_mapping */
        0,                                      /* tp_hash */
        0,                                      /* tp_call */
        0,                                      /* tp_str */
        0,                                      /* tp_getattro */
        0,                                      /* tp_setattro */
        0,                                      /* tp_as_buffer */
        Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
        Byte_tp_doc,                            /* tp_doc */
        0,                                      /* tp_traverse */
        0,                                      /* tp_clear */
        0,                                      /* tp_richcompare */
        0,                                      /* tp_weaklistoffset */
        0,                                      /* tp_iter */
        0,                                      /* tp_iternext */
        0,                                      /* tp_methods */
        0,                                      /* tp_members */
        0,                                      /* tp_getset */
        DEFERRED_ADDRESS(&PyString_Type),       /* tp_base */
        0,                                      /* tp_dict */
        0,                                      /* tp_descr_get */
        0,                                      /* tp_descr_set */
        0,                                      /* tp_dictoffset */
        0,                                      /* tp_init */
        0,                                      /* tp_alloc */
        Byte_new,                               /* tp_new */
};

PyDoc_STRVAR(ByteArray_tp_doc,
"ByteArray(str)\n"
"\n"
"ByteArray is a subtype of str which can be used when you want an\n"
"efficient immutable representation of a D-Bus byte array (signature 'ay').\n"
"\n"
"The subscript operation byte_array[i] returns Byte instances. Otherwise,\n"
"it's just a string.\n"
);

static inline unsigned char *
ByteArray_as_ucharptr(PyObject *self)
{
    return (unsigned char *)PyString_AsString(self);
}

static inline PyObject *
ByteArray_from_uchars(const unsigned char *data, int size)
{
    return PyObject_CallFunction((PyObject *)&ByteArrayType, "(s#)",
                                 (char *)data, size);
}

static PyObject *
ByteArray_sq_item (PyObject *self, int i)
{
    unsigned char c;
    if (i < 0 || i >= PyString_GET_SIZE(self)) {
        PyErr_SetString(PyExc_IndexError, "ByteArray index out of range");
        return NULL;
    }
    c = ((unsigned char *)PyString_AS_STRING(self))[i];
    return Byte_from_uchar(c);
}

static PyObject *
ByteArray_mp_subscript(PyObject *self, PyObject *other)
{
    long i;
    if (PyInt_Check(other)) {
        i = PyInt_AS_LONG(other);
        if (i < 0) i += PyString_GET_SIZE (self);
        return ByteArray_sq_item(self, i);
    }
    else if (PyLong_Check(other)) {
        i = PyLong_AsLong(other);
        if (i == -1 && PyErr_Occurred()) return NULL;
        if (i < 0) i += PyString_GET_SIZE(self);
        return ByteArray_sq_item(self, i);
    }
    else {
        /* slices just return strings */
        return (PyString_Type.tp_as_mapping->mp_subscript)(self, other);
    }
}

static PyMappingMethods ByteArray_tp_as_mapping = {
    0, /* mp_length */
    ByteArray_mp_subscript, /* mp_subscript */
    0, /* mp_ass_subscript */
};

static PySequenceMethods ByteArray_tp_as_sequence = {
    0, /* sq_length */
    0, /* sq_concat */
    0, /* sq_repeat */
    ByteArray_sq_item, /* sq_item */
    0, /* sq_slice */
    0, /* sq_ass_item */
    0, /* sq_ass_slice */
    0, /* sq_contains */
};

static PyTypeObject ByteArrayType = {
        PyObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type))
        0,
        "dbus.ByteArray",
        0,
        0,
        0,                                      /* tp_dealloc */
        0,                                      /* tp_print */
        0,                                      /* tp_getattr */
        0,                                      /* tp_setattr */
        0,                                      /* tp_compare */
        str_subclass_tp_repr,                   /* tp_repr */
        0,                                      /* tp_as_number */
        &ByteArray_tp_as_sequence,              /* tp_as_sequence */
        &ByteArray_tp_as_mapping,               /* tp_as_mapping */
        0,                                      /* tp_hash */
        0,                                      /* tp_call */
        0,                                      /* tp_str */
        0,                                      /* tp_getattro */
        0,                                      /* tp_setattro */
        0,                                      /* tp_as_buffer */
        Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
        ByteArray_tp_doc,                       /* tp_doc */
        0,                                      /* tp_traverse */
        0,                                      /* tp_clear */
        0,                                      /* tp_richcompare */
        0,                                      /* tp_weaklistoffset */
        0,                                      /* tp_iter */
        0,                                      /* tp_iternext */
        0,                                      /* tp_methods */
        0,                                      /* tp_members */
        0,                                      /* tp_getset */
        DEFERRED_ADDRESS(&PyString_Type),       /* tp_base */
        0,                                      /* tp_dict */
        0,                                      /* tp_descr_get */
        0,                                      /* tp_descr_set */
        0,                                      /* tp_dictoffset */
        0,                                      /* tp_init */
        0,                                      /* tp_alloc */
        0,                                      /* tp_new */
};

static inline int
init_byte_types(void)
{
    ByteType.tp_base = &PyString_Type;
    if (PyType_Ready(&ByteType) < 0) return 0;
    /* disable the tp_print copied from PyString_Type, so tp_repr gets called as
    desired */
    ByteType.tp_print = NULL;

    ByteArrayType.tp_base = &PyString_Type;
    if (PyType_Ready(&ByteArrayType) < 0) return 0;
    ByteArrayType.tp_print = NULL;

    return 1;
}

static inline int
insert_byte_types(PyObject *this_module)
{
    Py_INCREF(&ByteType);
    if (PyModule_AddObject(this_module, "Byte",
                           (PyObject *)&ByteType) < 0) return 0;
    Py_INCREF(&ByteArrayType);
    if (PyModule_AddObject(this_module, "ByteArray",
                           (PyObject *)&ByteArrayType) < 0) return 0;

    return 1;
}

/* vim:set ft=c cino< sw=4 sts=4 et: */