Skip to content

Commit

Permalink
Merge pull request #18 from jakirkham/use_c_str_cmp_array
Browse files Browse the repository at this point in the history
Handle array format fixes with C strings
  • Loading branch information
jakirkham committed Nov 24, 2018
2 parents a3249f1 + 4abde07 commit 97ad376
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 20 deletions.
5 changes: 0 additions & 5 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,11 +69,6 @@ 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([
Expand Down
36 changes: 21 additions & 15 deletions src/cybuffer.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -38,17 +38,19 @@ cdef extern from "Python.h":

cdef extern from *:
"""
#define UCS2_TC "H"
#define UCS4_TC "I"
#define UINT8_TC "B"
#define UINT16_TC "H"
#define UINT32_TC "I"
#define PyList_SET_ITEM_INC(l, i, o) \
Py_INCREF(o); PyList_SET_ITEM(l, i, o)
#define PyTuple_SET_ITEM_INC(l, i, o) \
Py_INCREF(o); PyTuple_SET_ITEM(l, i, o)
"""

char* UCS2_TC
char* UCS4_TC
char* UINT8_TC
char* UINT16_TC
char* UINT32_TC

void PyList_SET_ITEM_INC(object, Py_ssize_t, object)
void PyTuple_SET_ITEM_INC(object, Py_ssize_t, object)
Expand Down Expand Up @@ -176,19 +178,23 @@ cdef class cybuffer(object):
self.contiguous = self.c_contiguous or self.f_contiguous

# Workaround some special cases with the builtin array
IF PY2K or PY3K:
cdef char fmt
if (PY2K or PY3K) and isinstance(self.obj, array):
# Cast to appropriate format with given itemsize
typecode = self.obj.typecode
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 and typecode not in "Bc":
# Correct itemsize and format on Python 2
if PY2K:
self.itemsize = self.obj.itemsize
self._format = typecode
self._format = self.obj.typecode

# Recast text formats
fmt = self._format[0]
if PY2K and fmt == 'c':
self._format = UINT8_TC
elif fmt == 'u' or fmt == 'w':
if self.itemsize == 2:
self._format = UINT16_TC
elif self.itemsize == 4:
self._format = UINT32_TC

# Adjust shape and strides based on casting
if PY2K and self.itemsize != 1:
Expand Down

0 comments on commit 97ad376

Please sign in to comment.