Skip to content

Commit 888bbdc

Browse files
authored
bpo-27340: Use memoryview in SSLSocket.sendall() (#3384)
* bpo-27340: Use memoryview in SSLSocket.sendall() SSLSocket.sendall() now uses memoryview to create slices of data. This fix support for all bytes-like object. It is also more efficient and avoids costly copies. Signed-off-by: Christian Heimes <[email protected]> * Cast view to bytes, fix typo Signed-off-by: Christian Heimes <[email protected]>
1 parent 17c9ac9 commit 888bbdc

File tree

3 files changed

+19
-5
lines changed

3 files changed

+19
-5
lines changed

Lib/ssl.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -959,11 +959,12 @@ def sendall(self, data, flags=0):
959959
raise ValueError(
960960
"non-zero flags not allowed in calls to sendall() on %s" %
961961
self.__class__)
962-
amount = len(data)
963962
count = 0
964-
while (count < amount):
965-
v = self.send(data[count:])
966-
count += v
963+
with memoryview(data) as view, view.cast("B") as byte_view:
964+
amount = len(byte_view)
965+
while count < amount:
966+
v = self.send(byte_view[count:])
967+
count += v
967968
else:
968969
return socket.sendall(self, data, flags)
969970

Lib/test/test_ssl.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,10 @@
1818
import weakref
1919
import platform
2020
import functools
21+
try:
22+
import ctypes
23+
except ImportError:
24+
ctypes = None
2125

2226
ssl = support.import_module("ssl")
2327

@@ -2891,14 +2895,20 @@ def _recvfrom_into():
28912895
self.assertEqual(s.read(-1, buffer), len(data))
28922896
self.assertEqual(buffer, data)
28932897

2898+
# sendall accepts bytes-like objects
2899+
if ctypes is not None:
2900+
ubyte = ctypes.c_ubyte * len(data)
2901+
byteslike = ubyte.from_buffer_copy(data)
2902+
s.sendall(byteslike)
2903+
self.assertEqual(s.read(), data)
2904+
28942905
# Make sure sendmsg et al are disallowed to avoid
28952906
# inadvertent disclosure of data and/or corruption
28962907
# of the encrypted data stream
28972908
self.assertRaises(NotImplementedError, s.sendmsg, [b"data"])
28982909
self.assertRaises(NotImplementedError, s.recvmsg, 100)
28992910
self.assertRaises(NotImplementedError,
29002911
s.recvmsg_into, bytearray(100))
2901-
29022912
s.write(b"over\n")
29032913

29042914
self.assertRaises(ValueError, s.recv, -1)
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
SSLSocket.sendall() now uses memoryview to create slices of data. This fixes
2+
support for all bytes-like object. It is also more efficient and avoids
3+
costly copies.

0 commit comments

Comments
 (0)