chiark / gitweb /
catacomb.c, ec.c, group.c, mp.c: Count base/exponent pairs with `size_t'.
[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 #ifdef PY2
46   x->ob_sstate = SSTATE_NOT_INTERNED;
47 #endif
48   return ((PyObject *)x);
49 }
50
51 static PyObject *dowrap(PyTypeObject *ty, const void *p, size_t n)
52 {
53   PyObject *x;
54   int ch;
55
56   if (p && ty == bytestring_pytype) {
57     if (!n) {
58       if (!empty) empty = allocate(ty, 0);
59       Py_INCREF(empty); return (empty);
60     } else if (n == 1 && (ch = *(unsigned char *)p) < sizeof(bytev)) {
61       if (!bytev[ch])
62         { bytev[ch] = allocate(ty, 1); *BIN_PTR(bytev[ch]) = ch; }
63       Py_INCREF(bytev[ch]); return (bytev[ch]);
64     }
65   }
66
67   x = allocate(ty, n);
68   if (p) memcpy(BIN_PTR(x), p, n);
69   return (x);
70 }
71
72 PyObject *bytestring_pywrap(const void *p, size_t n)
73   { return (dowrap(bytestring_pytype, p, n)); }
74
75 PyObject *bytestring_pywrapbuf(buf *b)
76   { return (dowrap(bytestring_pytype, BCUR(b), BLEFT(b))); }
77
78 static PyObject *bytestring_pynew(PyTypeObject *ty,
79                                   PyObject *arg, PyObject *kw)
80 {
81   struct bin in;
82   static const char *const kwlist[] = { "data", 0 };
83   if (!PyArg_ParseTupleAndKeywords(arg, kw, "O&:new", KWLIST, convbin, &in))
84     return (0);
85   return (dowrap(ty, in.p, in.sz));
86 }
87
88 static PyObject *meth_ctstreq(PyObject *me, PyObject *arg)
89 {
90   struct bin s0, s1;
91   if (!PyArg_ParseTuple(arg, "O&O&:ctstreq", convbin, &s0 , convbin, &s1))
92     goto end;
93   if (s0.sz == s1.sz && ct_memeq(s0.p, s1.p, s0.sz)) RETURN_TRUE;
94   else RETURN_FALSE;
95 end:
96   return (0);
97 }
98
99 static PyObject *bymeth_zero(PyObject *me, PyObject *arg)
100 {
101   size_t sz;
102   PyObject *rc = 0;
103   if (!PyArg_ParseTuple(arg, "O&:zero", convszt, &sz)) goto end;
104   rc = bytestring_pywrap(0, sz);
105   memset(BIN_PTR(rc), 0, sz);
106 end:
107   return (rc);
108 }
109
110 static PyObject *bytestring_pyrichcompare(PyObject *me,
111                                           PyObject *you, int op)
112 {
113   struct bin s0, s1;
114   int b;
115   Py_ssize_t minlen;
116
117   s0.p = BIN_PTR(me); s0.sz = BIN_LEN(me);
118   if (!convbin(you, &s1)) { PyErr_Clear(); RETURN_NOTIMPL; }
119
120   switch (op) {
121     case Py_EQ:
122       b = s0.sz == s1.sz && ct_memeq(s0.p, s1.p, s1.sz);
123       break;
124     case Py_NE:
125       b = s0.sz != s1.sz || !ct_memeq(s0.p, s1.p, s1.sz);
126       break;
127     default:
128       minlen = s0.sz < s1.sz ? s0.sz : s1.sz;
129       b = memcmp(s0.p, s1.p, minlen);
130       if (!b) b = s0.sz < s1.sz ? -1 : s0.sz > s1.sz ? +1 : 0;
131       switch (op) {
132         case Py_LT: b = b <  0; break;
133         case Py_LE: b = b <= 0; break;
134         case Py_GE: b = b >= 0; break;
135         case Py_GT: b = b >  0; break;
136         default: abort();
137       }
138   }
139   if (b) RETURN_TRUE;
140   else RETURN_FALSE;
141 }
142
143 static PyObject *bytestring_pyconcat(PyObject *x, PyObject *y)
144 {
145   struct bin xx, yy;
146   PyObject *z = 0; char *zp; size_t zsz;
147
148   if (!convbin(x, &xx) || !convbin(y, &yy)) goto end;
149   zsz = (size_t)xx.sz + (size_t)yy.sz;
150   if (xx.sz < 0 || yy.sz < 0 || zsz < xx.sz) VALERR("too long");
151   z = bytestring_pywrap(0, zsz); zp = BIN_PTR(z);
152   memcpy(zp, xx.p, xx.sz); memcpy(zp + xx.sz, yy.p, yy.sz);
153 end:
154   return (z);
155 }
156
157 static PyObject *bytestring_pyrepeat(PyObject *me, Py_ssize_t n)
158 {
159   const unsigned char *xp; size_t xsz;
160   PyObject *z = 0; char *zp; size_t zsz;
161
162   xp = (const unsigned char *)BIN_PTR(me);
163   xsz = BIN_LEN(me);
164   if (n < 0 || (n && xsz >= (size_t)-1/n)) VALERR("too long");
165   zsz = n*xsz; z = bytestring_pywrap(0, zsz); zp = BIN_PTR(z);
166   if (xsz == 1) memset(zp, *xp, zsz);
167   else while (zsz) { memcpy(zp, xp, xsz); zp += xsz; zsz -= xsz; }
168 end:
169   return (z);
170 }
171
172 static PyObject *bytestring_pyitem(PyObject *me, Py_ssize_t i)
173 {
174   PyObject *rc = 0;
175
176   if (i < 0 || i >= BIN_LEN(me)) IXERR("out of range");
177 #ifdef PY3
178   rc = getulong(BIN_PTR(me)[i]&0xff);
179 #else
180   rc = bytestring_pywrap(BIN_PTR(me) + i, 1);
181 #endif
182 end:
183   return (rc);
184 }
185
186 static PyObject *bytestring_pyslice(PyObject *me, Py_ssize_t i, Py_ssize_t j)
187 {
188   PyObject *rc = 0;
189   size_t n = BIN_LEN(me);
190
191   if (i < 0) i = 0;
192   if (j < 0) j = 0;
193   else if (j > n) j = n;
194   if (j < i) i = j = 0;
195   if (i == 0 && j == n && Py_TYPE(me) == bytestring_pytype)
196     { Py_INCREF(me); rc = me; goto end; }
197   rc = bytestring_pywrap(BIN_PTR(me) + i, j - i);
198 end:
199   return (rc);
200 }
201
202 static PyObject *bytestring_pysubscript(PyObject *me, PyObject *ix)
203 {
204   Py_ssize_t i, j, k, n;
205   const unsigned char *p;
206   unsigned char *q;
207   PyObject *rc = 0;
208
209   if (PyIndex_Check(ix)) {
210     i = PyNumber_AsSsize_t(ix, PyExc_IndexError);
211     if (i == -1 && PyErr_Occurred()) return (0);
212     if (i < 0) i += BIN_LEN(me);
213     rc = bytestring_pyitem(me, i);
214   } else if (PySlice_Check(ix)) {
215     if (PySlice_GetIndicesEx(PY23((PySliceObject *), NOTHING)ix,
216                              BIN_LEN(me), &i, &j, &k, &n))
217       return (0);
218     if (k == 1) return bytestring_pyslice(me, i, j);
219     rc = bytestring_pywrap(0, n);
220     p = (unsigned char *)BIN_PTR(me) + i;
221     q = (unsigned char *)BIN_PTR(rc);
222     while (n--) { *q++ = *p; p += k; }
223   } else
224     TYERR("wanted integer or slice");
225 end:
226   return (rc);
227 }
228
229 #define BINOP(name, op)                                                 \
230   static PyObject *bytestring_py##name(PyObject *x, PyObject *y) {      \
231     struct bin xx, yy;                                                  \
232     const unsigned char *xp, *yp;                                       \
233     unsigned char *zp;                                                  \
234     int i;                                                              \
235     PyObject *rc = 0;                                                   \
236     if (!convbin(x, &xx) || !convbin(y, &yy)) goto end;                 \
237     if (xx.sz != yy.sz) VALERR("length mismatch");                      \
238     rc = bytestring_pywrap(0, xx.sz);                                   \
239     xp = xx.p; yp = yy.p; zp = (unsigned char *)BIN_PTR(rc);            \
240     for (i = xx.sz; i > 0; i--) *zp++ = *xp++ op *yp++;                 \
241   end:                                                                  \
242     return (rc);                                                        \
243   }
244 BINOP(and, &)
245 BINOP(or, |)
246 BINOP(xor, ^)
247
248 #define UNOP(name, op)                                                  \
249   static PyObject *bytestring_py##name(PyObject *x) {                   \
250     struct bin xx;                                                      \
251     const unsigned char *xp;                                            \
252     unsigned char *zp;                                                  \
253     int i;                                                              \
254     PyObject *rc = 0;                                                   \
255     if (!convbin(x, &xx)) goto end;                                     \
256     rc = bytestring_pywrap(0, xx.sz);                                   \
257     xp = xx.p; zp = (unsigned char *)BIN_PTR(rc);                       \
258     for (i = xx.sz; i > 0; i--) *zp++ = op *xp++;                       \
259   end:                                                                  \
260     return (rc);                                                        \
261   }
262 UNOP(not, ~)
263
264 static const PyMethodDef bytestring_pymethods[] = {
265 #define METHNAME(name) bymeth_##name
266   SMTH  (zero,          "zero(N) -> 0000...00")
267 #undef METHNAME
268   { 0 }
269 };
270
271 static const PyNumberMethods bytestring_pynumber = {
272   0,                                    /* @nb_add@ */
273   0,                                    /* @nb_subtract@ */
274   0,                                    /* @nb_multiply@ */
275 #ifdef PY2
276   0,                                    /* @nb_divide@ */
277 #endif
278   0,                                    /* @nb_remainder@ */
279   0,                                    /* @nb_divmod@ */
280   0,                                    /* @nb_power@ */
281   0,                                    /* @nb_negative@ */
282   0,                                    /* @nb_positive@ */
283   0,                                    /* @nb_absolute@ */
284   0,                                    /* @nb_nonzero@ */
285   bytestring_pynot,                     /* @nb_invert@ */
286   0,                                    /* @nb_lshift@ */
287   0,                                    /* @nb_rshift@ */
288   bytestring_pyand,                     /* @nb_and@ */
289   bytestring_pyxor,                     /* @nb_xor@ */
290   bytestring_pyor,                      /* @nb_or@ */
291   0,                                    /* @nb_coerce@ */
292   0,                                    /* @nb_int@ */
293   0,                                    /* @nb_long@ */
294   0,                                    /* @nb_float@ */
295   0,                                    /* @nb_oct@ */
296   0,                                    /* @nb_hex@ */
297 };
298
299 static const PySequenceMethods bytestring_pysequence = {
300   0,                                    /* @sq_length@ */
301   bytestring_pyconcat,                  /* @sq_concat@ */
302   bytestring_pyrepeat,                  /* @sq_repeat@ */
303   bytestring_pyitem,                    /* @sq_item@ */
304   bytestring_pyslice,                   /* @sq_slice@ */
305   0,                                    /* @sq_ass_item@ */
306   0,                                    /* @sq_ass_slice@ */
307   0,                                    /* @sq_contains@ */
308   0,                                    /* @sq_inplace_concat@ */
309   0,                                    /* @sq_inplace_repeat@ */
310 };
311
312 static const PyMappingMethods bytestring_pymapping = {
313   0,                                    /* @mp_length@ */
314   bytestring_pysubscript,               /* @mp_subscript@ */
315   0,                                    /* @mp_ass_subscript@ */
316 };
317
318 static const PyTypeObject bytestring_pytype_skel = {
319   PyVarObject_HEAD_INIT(0, 0)           /* Header */
320   "ByteString",                         /* @tp_name@ */
321   0,                                    /* @tp_basicsize@ */
322   0,                                    /* @tp_itemsize@ */
323
324   0,                                    /* @tp_dealloc@ */
325   0,                                    /* @tp_print@ */
326   0,                                    /* @tp_getattr@ */
327   0,                                    /* @tp_setattr@ */
328   0,                                    /* @tp_compare@ */
329   0,                                    /* @tp_repr@ */
330   PYNUMBER(bytestring),                 /* @tp_as_number@ */
331   PYSEQUENCE(bytestring),               /* @tp_as_sequence@ */
332   PYMAPPING(bytestring),                /* @tp_as_mapping@ */
333   0,                                    /* @tp_hash@ */
334   0,                                    /* @tp_call@ */
335   0,                                    /* @tp_str@ */
336   0,                                    /* @tp_getattro@ */
337   0,                                    /* @tp_setattro@ */
338   0,                                    /* @tp_as_buffer@ */
339   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
340     Py_TPFLAGS_CHECKTYPES |
341     Py_TPFLAGS_BASETYPE,
342
343   /* @tp_doc@ */
344   "ByteString(STR): byte string class.",
345
346   0,                                    /* @tp_traverse@ */
347   0,                                    /* @tp_clear@ */
348   bytestring_pyrichcompare,             /* @tp_richcompare@ */
349   0,                                    /* @tp_weaklistoffset@ */
350   0,                                    /* @tp_iter@ */
351   0,                                    /* @tp_iternext@ */
352   PYMETHODS(bytestring),                /* @tp_methods@ */
353   0,                                    /* @tp_members@ */
354   0,                                    /* @tp_getset@ */
355   0,                                    /* @tp_base@ */
356   0,                                    /* @tp_dict@ */
357   0,                                    /* @tp_descr_get@ */
358   0,                                    /* @tp_descr_set@ */
359   0,                                    /* @tp_dictoffset@ */
360   0,                                    /* @tp_init@ */
361   PyType_GenericAlloc,                  /* @tp_alloc@ */
362   bytestring_pynew,                     /* @tp_new@ */
363   0,                                    /* @tp_free@ */
364   0                                     /* @tp_is_gc@ */
365 };
366
367 /*----- Initialization ----------------------------------------------------*/
368
369 static const PyMethodDef methods[] = {
370 #define METHNAME(func) meth_##func
371   METH  (ctstreq,       "ctstreq(S, T) -> BOOL")
372 #undef METHNAME
373   { 0 }
374 };
375
376 #define string_pytype &BIN_TYPE
377 void bytestring_pyinit(void)
378 {
379   INITTYPE(bytestring, string);
380   addmethods(methods);
381 }
382
383 void bytestring_pyinsert(PyObject *mod)
384 {
385   INSERT("ByteString", bytestring_pytype);
386 }
387
388 /*----- That's all, folks -------------------------------------------------*/