gh-90751: memoryview now supports half-float (#96738)

Co-authored-by: Antoine Pitrou <antoine@python.org>
This commit is contained in:
Dong-hee Na 2022-09-11 05:44:10 +09:00 committed by GitHub
parent c4e57fb6df
commit 8d75a13fde
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 60 additions and 10 deletions

View file

@ -64,7 +64,7 @@ NATIVE = {
'?':0, 'c':0, 'b':0, 'B':0,
'h':0, 'H':0, 'i':0, 'I':0,
'l':0, 'L':0, 'n':0, 'N':0,
'f':0, 'd':0, 'P':0
'e':0, 'f':0, 'd':0, 'P':0
}
# NumPy does not have 'n' or 'N':
@ -89,7 +89,8 @@ STANDARD = {
'i':(-(1<<31), 1<<31), 'I':(0, 1<<32),
'l':(-(1<<31), 1<<31), 'L':(0, 1<<32),
'q':(-(1<<63), 1<<63), 'Q':(0, 1<<64),
'f':(-(1<<63), 1<<63), 'd':(-(1<<1023), 1<<1023)
'e':(-65519, 65520), 'f':(-(1<<63), 1<<63),
'd':(-(1<<1023), 1<<1023)
}
def native_type_range(fmt):
@ -98,6 +99,8 @@ def native_type_range(fmt):
lh = (0, 256)
elif fmt == '?':
lh = (0, 2)
elif fmt == 'e':
lh = (-65519, 65520)
elif fmt == 'f':
lh = (-(1<<63), 1<<63)
elif fmt == 'd':
@ -125,7 +128,10 @@ if struct:
for fmt in fmtdict['@']:
fmtdict['@'][fmt] = native_type_range(fmt)
# Format codes suppported by the memoryview object
MEMORYVIEW = NATIVE.copy()
# Format codes suppported by array.array
ARRAY = NATIVE.copy()
for k in NATIVE:
if not k in "bBhHiIlLfd":
@ -164,7 +170,7 @@ def randrange_fmt(mode, char, obj):
x = b'\x01'
if char == '?':
x = bool(x)
if char == 'f' or char == 'd':
if char in 'efd':
x = struct.pack(char, x)
x = struct.unpack(char, x)[0]
return x
@ -2246,7 +2252,7 @@ class TestBufferProtocol(unittest.TestCase):
###
### Fortran output:
### ---------------
### >>> fortran_buf = nd.tostring(order='F')
### >>> fortran_buf = nd.tobytes(order='F')
### >>> fortran_buf
### b'\x00\x04\x08\x01\x05\t\x02\x06\n\x03\x07\x0b'
###
@ -2289,7 +2295,7 @@ class TestBufferProtocol(unittest.TestCase):
self.assertEqual(memoryview(y), memoryview(nd))
if numpy_array:
self.assertEqual(b, na.tostring(order='C'))
self.assertEqual(b, na.tobytes(order='C'))
# 'F' request
if f == 0: # 'C' to 'F'
@ -2312,7 +2318,7 @@ class TestBufferProtocol(unittest.TestCase):
self.assertEqual(memoryview(y), memoryview(nd))
if numpy_array:
self.assertEqual(b, na.tostring(order='F'))
self.assertEqual(b, na.tobytes(order='F'))
# 'A' request
if f == ND_FORTRAN:
@ -2336,7 +2342,7 @@ class TestBufferProtocol(unittest.TestCase):
self.assertEqual(memoryview(y), memoryview(nd))
if numpy_array:
self.assertEqual(b, na.tostring(order='A'))
self.assertEqual(b, na.tobytes(order='A'))
# multi-dimensional, non-contiguous input
nd = ndarray(list(range(12)), shape=[3, 4], flags=ND_WRITABLE|ND_PIL)