File: pybuffer.pyx

package info (click to toggle)
music 1.2.1-0.7
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 5,596 kB
  • sloc: cpp: 26,805; sh: 5,674; python: 510; makefile: 406; ansic: 224
file content (66 lines) | stat: -rw-r--r-- 1,714 bytes parent folder | download
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
#
# distutils: language = c++
#

# Compatible with Python >= 2.6, Cython
# Not PYPY apparently

from libc.stdlib cimport malloc, free

from mpi4py import MPI

###########################################################

cdef dict TypeDict = {
    "?" : MPI.C_BOOL,
    "c" : MPI.CHAR,
    "b" : MPI.SIGNED_CHAR,
    "h" : MPI.SHORT,
    "i" : MPI.INT,
    "l" : MPI.LONG,
    "q" : MPI.LONG_LONG,
    "p" : MPI.AINT,
    "B" : MPI.UNSIGNED_CHAR,
    "H" : MPI.UNSIGNED_SHORT,
    "I" : MPI.UNSIGNED,
    "L" : MPI.UNSIGNED_LONG,
    "Q" : MPI.UNSIGNED_LONG_LONG,
    "f" : MPI.FLOAT,
    "d" : MPI.DOUBLE,
    "g" : MPI.LONG_DOUBLE,
    "Zf": MPI.C_FLOAT_COMPLEX,
    "Zd": MPI.C_DOUBLE_COMPLEX,
    "Zg": MPI.C_LONG_DOUBLE_COMPLEX,
    "F" : MPI.C_FLOAT_COMPLEX,
    "D" : MPI.C_DOUBLE_COMPLEX,
    "G" : MPI.C_LONG_DOUBLE_COMPLEX,
}

cdef object getformat(Py_buffer* pybuf):
    cdef object obj = <object> pybuf.obj

    # numpy.ndarray
    try: return obj.dtype.char
    except (AttributeError, TypeError): pass

    # array.array
    try: return obj.typecode
    except (AttributeError, TypeError): pass

    if pybuf.format is NULL: return "B"
    return PyUnicodeString_FromString(pybuf.format)

cdef int bufflags = PyBUF_ANY_CONTIGUOUS | PyBUF_WRITABLE | PyBUF_FORMAT

cdef class Buffer(object):
    def __cinit__(self, object data):
        if not PyObject_CheckBuffer(data):
            raise TypeError("object does not present buffer interface")

        cdef Py_buffer* pybuf = &self.pybuf
        PyObject_GetBuffer(data, pybuf, bufflags)
        self.dtype = TypeDict[getformat(pybuf)]
        self.items = pybuf.len // pybuf.itemsize

    def __dealloc__(self):
        PyBuffer_Release(&self.pybuf)