Merge pull request #268 from b3b/empty_bytearray

bytearray: fix #267 operations on empty arrays
This commit is contained in:
Mathieu Virbel 2017-08-22 10:27:33 +02:00 committed by GitHub
commit 406dd2099f
4 changed files with 30 additions and 12 deletions

View File

@ -13,7 +13,6 @@ cdef python_op(int op, object a, object b):
return a != b
cdef class ByteArray:
cdef LocalRef _jobject
cdef long _size
@ -43,7 +42,8 @@ cdef class ByteArray:
self._jobject.create(env, obj)
self._size = size
self._buf = <unsigned char *><signed char *>buf
self._arr = <unsigned char[:size]>self._buf
if size:
self._arr = <unsigned char[:size]>self._buf
def __str__(self):
return '<ByteArray size={} at 0x{}>'.format(
@ -56,17 +56,20 @@ cdef class ByteArray:
cdef long xx
if isinstance(index, slice):
val = []
(start, stop, step) = index.indices(len(self._arr))
for x in range(start, stop, step):
xx = x
val.append(self._arr[xx])
if self._size:
(start, stop, step) = index.indices(len(self._arr))
for x in range(start, stop, step):
xx = x
val.append(self._arr[xx])
return val
else:
xx = index
return self._arr[xx]
def __getslice__(self, long i, long j):
return self._arr[i:j]
if self._size:
return self._arr[i:j]
return []
def __richcmp__(self, other, op):
cdef ByteArray b_other

View File

@ -40,7 +40,8 @@ cdef class ByteArray:
self._jobject.create(env, obj)
self._size = size
self._buf = <unsigned char *><signed char *>buf
self._arr = <unsigned char[:size]>self._buf
if size:
self._arr = <unsigned char[:size]>self._buf
def __str__(self):
return '<ByteArray size={} at 0x{}>'.format(
@ -53,10 +54,11 @@ cdef class ByteArray:
cdef long xx
if isinstance(index, slice):
val = []
(start, stop, step) = index.indices(len(self._arr))
for x in range(start, stop, step):
xx = x
val.append(self._arr[xx])
if self._size:
(start, stop, step) = index.indices(len(self._arr))
for x in range(start, stop, step):
xx = x
val.append(self._arr[xx])
return val
else:
xx = index

View File

@ -175,6 +175,10 @@ public class BasicsTest {
x[2] = -127;
}
public byte[] methodReturnEmptyByteArray() {
return new byte[0];
}
public boolean testFieldSetZ() {
return (fieldSetZ == true);
}

View File

@ -39,3 +39,12 @@ class StringArgumentForByteArrayTest(unittest.TestCase):
self.assertEquals(nis.read(barr, 0, 256), 256)
self.assertEquals(barr[:256], s[:256])
def test_empty_bytearray(self):
Test = autoclass('org.jnius.BasicsTest')()
arr = Test.methodReturnEmptyByteArray()
self.assertEquals(len(arr), 0)
with self.assertRaises(IndexError):
arr[0]
self.assertEquals(arr, [])
self.assertEquals(arr[:1], [])
self.assertEquals(arr.tostring(), b'')