Skip to content

Commit

Permalink
Merge pull request #13 from jakirkham/simp_array_init
Browse files Browse the repository at this point in the history
Simplify initialization of `cybuffer` with a builtin `array`
  • Loading branch information
jakirkham committed Nov 24, 2018
2 parents 3a3d414 + ae9f899 commit 302de15
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 15 deletions.
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

0 comments on commit 302de15

Please sign in to comment.