chiark / gitweb /
buffer.c: Funnel control through a common exit point.
[catacomb-python] / bytestring.c
1 /* -*-c-*-
2  *
3  * Byte strings
4  *
5  * (c) 2004 Straylight/Edgeware
6  */
7
8 /*----- Licensing notice --------------------------------------------------*
9  *
10  * This file is part of the Python interface to Catacomb.
11  *
12  * Catacomb/Python is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 2 of the License, or
15  * (at your option) any later version.
16  *
17  * Catacomb/Python is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with Catacomb/Python; if not, write to the Free Software Foundation,
24  * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
25  */
26
27 /*----- Header files ------------------------------------------------------*/
28
29 #include "catacomb-python.h"
30
31 /*----- Main code ---------------------------------------------------------*/
32
33 static PyTypeObject *bytestring_pytype;
34
35 static PyObject *empty, *bytev[256];
36
37 static PyObject *allocate(PyTypeObject *ty, size_t n)
38 {
39   BINOBJ *x;
40   x = (BINOBJ *)ty->tp_alloc(ty, n);
41   x->ob_sval[n] = 0;
42 #if defined(CACHE_HASH) || PY_VERSION_HEX >= 0x02030000
43   x->ob_shash = -1;
44 #endif
45   x->ob_sstate = SSTATE_NOT_INTERNED;
46   return ((PyObject *)x);
47 }
48
49 static PyObject *dowrap(PyTypeObject *ty, const void *p, size_t n)
50 {
51   PyObject *x;
52   int ch;
53
54   if (p && ty == bytestring_pytype) {
55     if (!n) {
56       if (!empty) empty = allocate(ty, 0);
57       Py_INCREF(empty); return (empty);
58     } else if (n == 1 && (ch = *(unsigned char *)p) < sizeof(bytev)) {
59       if (!bytev[ch])
60         { bytev[ch] = allocate(ty, 1); *BIN_PTR(bytev[ch]) = ch; }
61       Py_INCREF(bytev[ch]); return (bytev[ch]);
62     }
63   }
64
65   x = allocate(ty, n);
66   if (p) memcpy(BIN_PTR(x), p, n);
67   return (x);
68 }
69
70 PyObject *bytestring_pywrap(const void *p, size_t n)
71   { return (dowrap(bytestring_pytype, p, n)); }
72
73 PyObject *bytestring_pywrapbuf(buf *b)
74   { return (dowrap(bytestring_pytype, BCUR(b), BLEFT(b))); }
75
76 static PyObject *bytestring_pynew(PyTypeObject *ty,
77                                   PyObject *arg, PyObject *kw)
78 {
79   struct bin in;
80   static const char *const kwlist[] = { "data", 0 };
81   if (!PyArg_ParseTupleAndKeywords(arg, kw, "O&:new", KWLIST, convbin, &in))
82     return (0);
83   return (dowrap(ty, in.p, in.sz));
84 }
85
86 static PyObject *meth_ctstreq(PyObject *me, PyObject *arg)
87 {
88   struct bin s0, s1;
89   if (!PyArg_ParseTuple(arg, "O&O&:ctstreq", convbin, &s0 , convbin, &s1))
90     goto end;
91   if (s0.sz == s1.sz && ct_memeq(s0.p, s1.p, s0.sz)) RETURN_TRUE;
92   else RETURN_FALSE;
93 end:
94   return (0);
95 }
96
97 static PyObject *bymeth_zero(PyObject *me, PyObject *arg)
98 {
99   size_t sz;
100   PyObject *rc = 0;
101   if (!PyArg_ParseTuple(arg, "O&:zero", convszt, &sz)) goto end;
102   rc = bytestring_pywrap(0, sz);
103   memset(BIN_PTR(rc), 0, sz);
104 end:
105   return (rc);
106 }
107
108 static PyObject *bytestring_pyrichcompare(PyObject *me,
109                                           PyObject *you, int op)
110 {
111   struct bin s0, s1;
112   int b;
113   Py_ssize_t minlen;
114
115   s0.p = BIN_PTR(me); s0.sz = BIN_LEN(me);
116   if (!convbin(you, &s1)) { PyErr_Clear(); RETURN_NOTIMPL; }
117
118   switch (op) {
119     case Py_EQ:
120       b = s0.sz == s1.sz && ct_memeq(s0.p, s1.p, s1.sz);
121       break;
122     case Py_NE:
123       b = s0.sz != s1.sz || !ct_memeq(s0.p, s1.p, s1.sz);
124       break;
125     default:
126       minlen = s0.sz < s1.sz ? s0.sz : s1.sz;
127       b = memcmp(s0.p, s1.p, minlen);
128       if (!b) b = s0.sz < s1.sz ? -1 : s0.sz > s1.sz ? +1 : 0;
129       switch (op) {
130         case Py_LT: b = b <  0; break;
131         case Py_LE: b = b <= 0; break;
132         case Py_GE: b = b >= 0; break;
133         case Py_GT: b = b >  0; break;
134         default: abort();
135       }
136   }
137   if (b) RETURN_TRUE;
138   else RETURN_FALSE;
139 }
140
141 static PyObject *bytestring_pyconcat(PyObject *x, PyObject *y)
142 {
143   struct bin xx, yy;
144   PyObject *z = 0; char *zp; size_t zsz;
145
146   if (!convbin(x, &xx) || !convbin(y, &yy)) goto end;
147   zsz = (size_t)xx.sz + (size_t)yy.sz;
148   if (xx.sz < 0 || yy.sz < 0 || zsz < xx.sz) VALERR("too long");
149   z = bytestring_pywrap(0, zsz); zp = BIN_PTR(z);
150   memcpy(zp, xx.p, xx.sz); memcpy(zp + xx.sz, yy.p, yy.sz);
151 end:
152   return (z);
153 }
154
155 static PyObject *bytestring_pyrepeat(PyObject *me, Py_ssize_t n)
156 {
157   const unsigned char *xp; size_t xsz;
158   PyObject *z = 0; char *zp; size_t zsz;
159
160   xp = (const unsigned char *)BIN_PTR(me);
161   xsz = BIN_LEN(me);
162   if (n < 0 || (n && xsz >= (size_t)-1/n)) VALERR("too long");
163   zsz = n*xsz; z = bytestring_pywrap(0, zsz); zp = BIN_PTR(z);
164   if (xsz == 1) memset(zp, *xp, zsz);
165   else while (zsz) { memcpy(zp, xp, xsz); zp += xsz; zsz -= xsz; }
166 end:
167   return (z);
168 }
169
170 static PyObject *bytestring_pyitem(PyObject *me, Py_ssize_t i)
171 {
172   PyObject *rc = 0;
173
174   if (i < 0 || i >= BIN_LEN(me)) IXERR("out of range");
175   rc = bytestring_pywrap(BIN_PTR(me) + i, 1);
176 end:
177   return (rc);
178 }
179
180 static PyObject *bytestring_pyslice(PyObject *me, Py_ssize_t i, Py_ssize_t j)
181 {
182   PyObject *rc = 0;
183   size_t n = BIN_LEN(me);
184
185   if (i < 0) i = 0;
186   if (j < 0) j = 0;
187   else if (j > n) j = n;
188   if (j < i) i = j = 0;
189   if (i == 0 && j == n && Py_TYPE(me) == bytestring_pytype)
190     { Py_INCREF(me); rc = me; goto end; }
191   rc = bytestring_pywrap(BIN_PTR(me) + i, j - i);
192 end:
193   return (rc);
194 }
195
196 static PyObject *bytestring_pysubscript(PyObject *me, PyObject *ix)
197 {
198   Py_ssize_t i, j, k, n;
199   const unsigned char *p;
200   unsigned char *q;
201   PyObject *rc = 0;
202
203   if (PyIndex_Check(ix)) {
204     i = PyNumber_AsSsize_t(ix, PyExc_IndexError);
205     if (i == -1 && PyErr_Occurred()) return (0);
206     if (i < 0) i += BIN_LEN(me);
207     rc = bytestring_pyitem(me, i);
208   } else if (PySlice_Check(ix)) {
209     if (PySlice_GetIndicesEx((PySliceObject *)ix, BIN_LEN(me),
210                              &i, &j, &k, &n))
211       return (0);
212     if (k == 1) return bytestring_pyslice(me, i, j);
213     rc = bytestring_pywrap(0, n);
214     p = (unsigned char *)BIN_PTR(me) + i;
215     q = (unsigned char *)BIN_PTR(rc);
216     while (n--) { *q++ = *p; p += k; }
217   } else
218     TYERR("wanted integer or slice");
219 end:
220   return (rc);
221 }
222
223 #define BINOP(name, op)                                                 \
224   static PyObject *bytestring_py##name(PyObject *x, PyObject *y) {      \
225     struct bin xx, yy;                                                  \
226     const unsigned char *xp, *yp;                                       \
227     unsigned char *zp;                                                  \
228     int i;                                                              \
229     PyObject *rc = 0;                                                   \
230     if (!convbin(x, &xx) || !convbin(y, &yy)) goto end;                 \
231     if (xx.sz != yy.sz) VALERR("length mismatch");                      \
232     rc = bytestring_pywrap(0, xx.sz);                                   \
233     xp = xx.p; yp = yy.p; zp = (unsigned char *)BIN_PTR(rc);            \
234     for (i = xx.sz; i > 0; i--) *zp++ = *xp++ op *yp++;                 \
235   end:                                                                  \
236     return (rc);                                                        \
237   }
238 BINOP(and, &)
239 BINOP(or, |)
240 BINOP(xor, ^)
241
242 #define UNOP(name, op)                                                  \
243   static PyObject *bytestring_py##name(PyObject *x) {                   \
244     struct bin xx;                                                      \
245     const unsigned char *xp;                                            \
246     unsigned char *zp;                                                  \
247     int i;                                                              \
248     PyObject *rc = 0;                                                   \
249     if (!convbin(x, &xx)) goto end;                                     \
250     rc = bytestring_pywrap(0, xx.sz);                                   \
251     xp = xx.p; zp = (unsigned char *)BIN_PTR(rc);                       \
252     for (i = xx.sz; i > 0; i--) *zp++ = op *xp++;                       \
253   end:                                                                  \
254     return (rc);                                                        \
255   }
256 UNOP(not, ~)
257
258 static const PyMethodDef bytestring_pymethods[] = {
259 #define METHNAME(name) bymeth_##name
260   SMTH  (zero,          "zero(N) -> 0000...00")
261 #undef METHNAME
262   { 0 }
263 };
264
265 static const PyNumberMethods bytestring_pynumber = {
266   0,                                    /* @nb_add@ */
267   0,                                    /* @nb_subtract@ */
268   0,                                    /* @nb_multiply@ */
269   0,                                    /* @nb_divide@ */
270   0,                                    /* @nb_remainder@ */
271   0,                                    /* @nb_divmod@ */
272   0,                                    /* @nb_power@ */
273   0,                                    /* @nb_negative@ */
274   0,                                    /* @nb_positive@ */
275   0,                                    /* @nb_absolute@ */
276   0,                                    /* @nb_nonzero@ */
277   bytestring_pynot,                     /* @nb_invert@ */
278   0,                                    /* @nb_lshift@ */
279   0,                                    /* @nb_rshift@ */
280   bytestring_pyand,                     /* @nb_and@ */
281   bytestring_pyxor,                     /* @nb_xor@ */
282   bytestring_pyor,                      /* @nb_or@ */
283   0,                                    /* @nb_coerce@ */
284   0,                                    /* @nb_int@ */
285   0,                                    /* @nb_long@ */
286   0,                                    /* @nb_float@ */
287   0,                                    /* @nb_oct@ */
288   0,                                    /* @nb_hex@ */
289 };
290
291 static const PySequenceMethods bytestring_pysequence = {
292   0,                                    /* @sq_length@ */
293   bytestring_pyconcat,                  /* @sq_concat@ */
294   bytestring_pyrepeat,                  /* @sq_repeat@ */
295   bytestring_pyitem,                    /* @sq_item@ */
296   bytestring_pyslice,                   /* @sq_slice@ */
297   0,                                    /* @sq_ass_item@ */
298   0,                                    /* @sq_ass_slice@ */
299   0,                                    /* @sq_contains@ */
300   0,                                    /* @sq_inplace_concat@ */
301   0,                                    /* @sq_inplace_repeat@ */
302 };
303
304 static const PyMappingMethods bytestring_pymapping = {
305   0,                                    /* @mp_length@ */
306   bytestring_pysubscript,               /* @mp_subscript@ */
307   0,                                    /* @mp_ass_subscript@ */
308 };
309
310 static const PyTypeObject bytestring_pytype_skel = {
311   PyVarObject_HEAD_INIT(0, 0)           /* Header */
312   "ByteString",                         /* @tp_name@ */
313   0,                                    /* @tp_basicsize@ */
314   0,                                    /* @tp_itemsize@ */
315
316   0,                                    /* @tp_dealloc@ */
317   0,                                    /* @tp_print@ */
318   0,                                    /* @tp_getattr@ */
319   0,                                    /* @tp_setattr@ */
320   0,                                    /* @tp_compare@ */
321   0,                                    /* @tp_repr@ */
322   PYNUMBER(bytestring),                 /* @tp_as_number@ */
323   PYSEQUENCE(bytestring),               /* @tp_as_sequence@ */
324   PYMAPPING(bytestring),                /* @tp_as_mapping@ */
325   0,                                    /* @tp_hash@ */
326   0,                                    /* @tp_call@ */
327   0,                                    /* @tp_str@ */
328   0,                                    /* @tp_getattro@ */
329   0,                                    /* @tp_setattro@ */
330   0,                                    /* @tp_as_buffer@ */
331   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
332     Py_TPFLAGS_CHECKTYPES |
333     Py_TPFLAGS_BASETYPE,
334
335   /* @tp_doc@ */
336   "ByteString(STR): byte string class.",
337
338   0,                                    /* @tp_traverse@ */
339   0,                                    /* @tp_clear@ */
340   bytestring_pyrichcompare,             /* @tp_richcompare@ */
341   0,                                    /* @tp_weaklistoffset@ */
342   0,                                    /* @tp_iter@ */
343   0,                                    /* @tp_iternext@ */
344   PYMETHODS(bytestring),                /* @tp_methods@ */
345   0,                                    /* @tp_members@ */
346   0,                                    /* @tp_getset@ */
347   0,                                    /* @tp_base@ */
348   0,                                    /* @tp_dict@ */
349   0,                                    /* @tp_descr_get@ */
350   0,                                    /* @tp_descr_set@ */
351   0,                                    /* @tp_dictoffset@ */
352   0,                                    /* @tp_init@ */
353   PyType_GenericAlloc,                  /* @tp_alloc@ */
354   bytestring_pynew,                     /* @tp_new@ */
355   0,                                    /* @tp_free@ */
356   0                                     /* @tp_is_gc@ */
357 };
358
359 /*----- Initialization ----------------------------------------------------*/
360
361 static const PyMethodDef methods[] = {
362 #define METHNAME(func) meth_##func
363   METH  (ctstreq,       "ctstreq(S, T) -> BOOL")
364 #undef METHNAME
365   { 0 }
366 };
367
368 #define string_pytype &BIN_TYPE
369 void bytestring_pyinit(void)
370 {
371   INITTYPE(bytestring, string);
372   addmethods(methods);
373 }
374
375 void bytestring_pyinsert(PyObject *mod)
376 {
377   INSERT("ByteString", bytestring_pytype);
378 }
379
380 /*----- That's all, folks -------------------------------------------------*/