Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Simplify initialization of cybuffer with a builtin array #13

Merged
merged 9 commits into from
Nov 24, 2018
7 changes: 7 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import array
import glob
import os
import sys
Expand Down Expand Up @@ -68,6 +69,12 @@ def run_tests(self):
"DEF PY2K = " + str(sys.version_info.major == 2) + "\n",
"DEF PY3K = " + str(sys.version_info.major == 3) + "\n"
])
if sys.version_info.major < 4: # pragma: no branch
Py_UNICODE_SIZE = array.array('u').itemsize
f.writelines([
"DEF Py_UNICODE_SIZE = " + str(Py_UNICODE_SIZE) + "\n",
])

with open("src/version.pxi", "w") as f:
f.writelines([
"__version__ = " + "\"" + str(version) + "\""
Expand Down
24 changes: 9 additions & 15 deletions src/cybuffer.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,6 @@ include "version.pxi"


cdef extern from "Python.h":
size_t Py_UNICODE_SIZE

object PyMemoryView_FromObject(object obj)


Expand Down Expand Up @@ -162,26 +160,22 @@ cdef class cybuffer(object):
# Workaround some special cases with the builtin array
cdef size_t len_nd_b
cdef int n_1
if isinstance(self.obj, array):
# Fix-up typecode
if (PY2K or PY3K) and isinstance(self.obj, array):
# Cast to appropriate format with given itemsize
typecode = self.obj.typecode
if typecode == "B":
return
elif PY2K and typecode == "c":
self._format = UBYTE_TC
return
elif (PY2K or PY3K) and typecode == "u":
if typecode == "u":
if PY2K:
self.itemsize = Py_UNICODE_SIZE
if Py_UNICODE_SIZE == 2:
self._format = UCS2_TC
elif Py_UNICODE_SIZE == 4:
self._format = UCS4_TC
elif PY2K:
self._format = typecode

# Adjust itemsize, shape, and strides based on casting
if PY2K:
elif PY2K and typecode not in "Bc":
self.itemsize = self.obj.itemsize
self._format = typecode

# Adjust shape and strides based on casting
if PY2K and self.itemsize != 1:
len_nd_b = self._buf.ndim * sizeof(Py_ssize_t)
self._shape = <Py_ssize_t*>cpython.mem.PyMem_Malloc(len_nd_b)
self._strides = <Py_ssize_t*>cpython.mem.PyMem_Malloc(len_nd_b)
Expand Down