[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 <christian@python.org>

* Cast view to bytes, fix typo

Signed-off-by: Christian Heimes <christian@python.org>.
(cherry picked from commit 888bbdc192)
This commit is contained in:
Christian Heimes 2017-09-07 16:59:17 -07:00 committed by GitHub
parent 6c99b652f7
commit 9423f5d688
3 changed files with 19 additions and 5 deletions

View file

@ -959,10 +959,11 @@ class SSLSocket(socket):
raise ValueError( raise ValueError(
"non-zero flags not allowed in calls to sendall() on %s" % "non-zero flags not allowed in calls to sendall() on %s" %
self.__class__) self.__class__)
amount = len(data)
count = 0 count = 0
while (count < amount): with memoryview(data) as view, view.cast("B") as byte_view:
v = self.send(data[count:]) amount = len(byte_view)
while count < amount:
v = self.send(byte_view[count:])
count += v count += v
else: else:
return socket.sendall(self, data, flags) return socket.sendall(self, data, flags)

View file

@ -18,6 +18,10 @@ import asyncore
import weakref import weakref
import platform import platform
import functools import functools
try:
import ctypes
except ImportError:
ctypes = None
ssl = support.import_module("ssl") ssl = support.import_module("ssl")
@ -2882,7 +2886,13 @@ if _have_threads:
s.send(data) s.send(data)
buffer = bytearray(len(data)) buffer = bytearray(len(data))
self.assertEqual(s.read(-1, buffer), len(data)) self.assertEqual(s.read(-1, buffer), len(data))
self.assertEqual(buffer, data) self.assertEqual(buffer, data) # sendall accepts bytes-like objects
if ctypes is not None:
ubyte = ctypes.c_ubyte * len(data)
byteslike = ubyte.from_buffer_copy(data)
s.sendall(byteslike)
self.assertEqual(s.read(), data)
# Make sure sendmsg et al are disallowed to avoid # Make sure sendmsg et al are disallowed to avoid
# inadvertent disclosure of data and/or corruption # inadvertent disclosure of data and/or corruption

View file

@ -0,0 +1,3 @@
SSLSocket.sendall() now uses memoryview to create slices of data. This fixes
support for all bytes-like object. It is also more efficient and avoids
costly copies.