Skip to content

Commit 48f38d6

Browse files
committed
Micro-optimize feed_data() for memoryviews
1 parent def67ef commit 48f38d6

File tree

2 files changed

+29
-8
lines changed

2 files changed

+29
-8
lines changed

httptools/parser/parser.pyx

Lines changed: 23 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,9 @@ from cpython.mem cimport PyMem_Malloc, PyMem_Free
55
from cpython cimport PyObject_GetBuffer, PyBuffer_Release, PyBUF_SIMPLE, \
66
Py_buffer, PyBytes_AsString
77

8+
from .python cimport PyMemoryView_Check, PyMemoryView_GET_BUFFER
9+
10+
811
from .errors import (HttpParserError,
912
HttpParserCallbackError,
1013
HttpParserInvalidStatusError,
@@ -149,17 +152,29 @@ cdef class HttpParser:
149152
cdef:
150153
size_t data_len
151154
size_t nb
155+
Py_buffer *buf
152156

153-
PyObject_GetBuffer(data, &self.py_buf, PyBUF_SIMPLE)
154-
data_len = <size_t>self.py_buf.len
157+
if PyMemoryView_Check(data):
158+
buf = PyMemoryView_GET_BUFFER(data)
159+
data_len = <size_t>buf.len
160+
nb = cparser.http_parser_execute(
161+
self._cparser,
162+
self._csettings,
163+
<char*>buf.buf,
164+
data_len)
165+
166+
else:
167+
buf = &self.py_buf
168+
PyObject_GetBuffer(data, buf, PyBUF_SIMPLE)
169+
data_len = <size_t>buf.len
155170

156-
nb = cparser.http_parser_execute(
157-
self._cparser,
158-
self._csettings,
159-
<char*>self.py_buf.buf,
160-
data_len)
171+
nb = cparser.http_parser_execute(
172+
self._cparser,
173+
self._csettings,
174+
<char*>buf.buf,
175+
data_len)
161176

162-
PyBuffer_Release(&self.py_buf)
177+
PyBuffer_Release(buf)
163178

164179
if self._cparser.http_errno != cparser.HPE_OK:
165180
ex = parser_error_from_errno(

httptools/parser/python.pxd

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
cimport cpython
2+
3+
4+
cdef extern from "Python.h":
5+
cpython.Py_buffer* PyMemoryView_GET_BUFFER(object)
6+
bint PyMemoryView_Check(object)

0 commit comments

Comments
 (0)