7 # (c) 2005 Straylight/Edgeware
10 #----- Licensing notice -----------------------------------------------------
12 # This file is part of the Python interface to mLib.
14 # mLib/Python is free software; you can redistribute it and/or modify
15 # it under the terms of the GNU General Public License as published by
16 # the Free Software Foundation; either version 2 of the License, or
17 # (at your option) any later version.
19 # mLib/Python is distributed in the hope that it will be useful,
20 # but WITHOUT ANY WARRANTY; without even the implied warranty of
21 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 # GNU General Public License for more details.
24 # You should have received a copy of the GNU General Public License
25 # along with mLib/Python; if not, write to the Free Software Foundation,
26 # Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
28 cdef class PacketBuffer:
32 def __new__(me, packetproc = None, eofproc = None, *hunoz, **hukairz):
33 pkbuf_init(&me.pk, _pkfunc, <void *>me)
34 me._packet = _checkcallable(packetproc, 'packet proc')
35 me._eof = _checkcallable(eofproc, 'eof proc')
40 return _tobool(me.pk.f & PKBUF_ENABLE)
44 def __set__(me, want):
46 raise TypeError, 'want must be positive'
47 pkbuf_want(&me.pk, pk)
51 def __set__(me, proc):
52 me._line = _checkcallable(proc, 'packet proc')
58 def __set__(me, proc):
59 me._eof = _checkcallable(proc, 'eof proc')
63 if me.pk.f & PKBUF_ENABLE:
64 raise ValueError, 'already enabled'
65 me.pk.f = me.pk.f | PKBUF_ENABLE
69 if not (me.pk.f & PKBUF_ENABLE):
70 raise ValueError, 'already disabled'
71 me.pk.f = me.pk.f & ~PKBUF_ENABLE
75 if not (me.pk.f & PKBUF_ENABLE):
76 raise ValueError, 'buffer disabled'
82 return pkbuf_free(&me.pk, &p)
88 PyObject_AsReadBuffer(str, <void **>&p, &len)
90 n = pkbuf_free(&me.pk, &q)
96 if not (me.pk.f & PKBUF_ENABLE):
98 pkbuf_flush(&me.pk, q, n)
99 return PyString_FromStringAndSize(<char *>p, len)
105 return _maybecall(me._packet, (pk,))
107 return _maybecall(me._eof, ())
109 cdef void _pkfunc(unsigned char *p, size_t n, pkbuf *pk,
110 size_t *keep, void *arg):
114 pb = <PacketBuffer>arg
118 r = pb.packet(PyString_FromStringAndSize(<char *>p, n))
120 PyObject_AsReadBuffer(r, &rp, &rn)
122 raise ValueError, 'remaining buffer too large'
124 memcpy(p + n - rn, rp, rn)
127 #----- That's all, folks ----------------------------------------------------