Skip to content

Commit 9423f5d

Browse files
authored
[3.6] bpo-27340: Use memoryview in SSLSocket.sendall() (GH-3384) (#3434)
* 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]>. (cherry picked from commit 888bbdc)
1 parent 6c99b65 commit 9423f5d

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

@@ -2882,7 +2886,13 @@ def _recvfrom_into():
28822886
s.send(data)
28832887
buffer = bytearray(len(data))
28842888
self.assertEqual(s.read(-1, buffer), len(data))
2885-
self.assertEqual(buffer, data)
2889+
self.assertEqual(buffer, data) # sendall accepts bytes-like objects
2890+
2891+
if ctypes is not None:
2892+
ubyte = ctypes.c_ubyte * len(data)
2893+
byteslike = ubyte.from_buffer_copy(data)
2894+
s.sendall(byteslike)
2895+
self.assertEqual(s.read(), data)
28862896

28872897
# Make sure sendmsg et al are disallowed to avoid
28882898
# inadvertent disclosure of data and/or corruption
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)