From 9b337788cf40634446c7ae703974686440233e7a Mon Sep 17 00:00:00 2001 From: 0x676e67 Date: Sat, 31 Oct 2026 04:07:36 +0000 Subject: [PATCH 1/6] feat(buffer): share memoryview input both ways via bidirectional PyBuffer --- python/wreq/header.py | 4 +- python/wreq/wreq.py | 10 ++- src/buffer.rs | 127 ++++++++++++++++++++++++++++++++--- src/client/body.rs | 11 ++- src/client/body/multipart.rs | 34 +++++++--- src/client/body/stream.rs | 6 +- src/client/resp/ws/msg.rs | 31 ++++++--- src/extractor.rs | 29 +------- src/header.rs | 8 +-- tests/buffer_test.py | 50 ++++++++++++++ 10 files changed, 234 insertions(+), 76 deletions(-) diff --git a/python/wreq/header.py b/python/wreq/header.py index 406e53d2..8a986940 100644 --- a/python/wreq/header.py +++ b/python/wreq/header.py @@ -143,7 +143,9 @@ def remove(self, key: str) -> None: """ ... - def get(self, key: str, default: bytes | None = None) -> memoryview | None: + def get( + self, key: str, default: bytes | bytearray | memoryview | None = None + ) -> memoryview | None: r""" Get the first value for a header name with optional default. diff --git a/python/wreq/wreq.py b/python/wreq/wreq.py index 4662ea41..834dc931 100644 --- a/python/wreq/wreq.py +++ b/python/wreq/wreq.py @@ -153,6 +153,8 @@ def __init__( value: ( str | bytes + | bytearray + | memoryview | Path | Generator[bytes, str, None] | AsyncGenerator[bytes, str] @@ -222,7 +224,7 @@ class Message: """ @staticmethod - def from_binary(like: bytes | Any) -> "Message": + def from_binary(like: bytes | bytearray | memoryview | Any) -> "Message": r""" Creates a new binary message. @@ -244,7 +246,7 @@ def from_text(like: str | Any) -> "Message": ... @staticmethod - def from_ping(data: bytes) -> "Message": + def from_ping(data: bytes | bytearray | memoryview) -> "Message": r""" Creates a new ping message. @@ -255,7 +257,7 @@ def from_ping(data: bytes) -> "Message": ... @staticmethod - def from_pong(data: bytes) -> "Message": + def from_pong(data: bytes | bytearray | memoryview) -> "Message": r""" Creates a new pong message. @@ -979,6 +981,8 @@ class Request(TypedDict): body: NotRequired[ str | bytes + | bytearray + | memoryview | Sequence[Tuple[str, str]] | Tuple[str, str | int | float | bool] | Mapping[str, str | int | float | bool] diff --git a/src/buffer.rs b/src/buffer.rs index 7b3d8231..85b9aae7 100644 --- a/src/buffer.rs +++ b/src/buffer.rs @@ -15,14 +15,27 @@ // specific language governing permissions and limitations // under the License. -use std::os::raw::c_int; +use std::{ops::Range, os::raw::c_int}; use bytes::Bytes; -use pyo3::{exceptions::PyOverflowError, ffi, prelude::*, types::PyMemoryView}; +use pyo3::{ + buffer::PyUntypedBuffer, + exceptions::{PyOverflowError, PyTypeError}, + ffi, intern, + prelude::*, + pybacked::PyBackedBytes, + types::{PyByteArray, PyBytes, PyMemoryView}, +}; use wreq::header::{HeaderCaseName, HeaderName, HeaderValue}; -/// Exposes owned Rust bytes as a read-only Python memoryview without copying. -pub struct PyBuffer(BufferView); +/// Bytes shared with Python in both directions: extracted from `bytes`, `bytearray` or +/// `memoryview` input and returned as a read-only memoryview. +/// +/// Input is shared only when an exact `bytes` or one of our own memoryviews owns it. Mutable +/// exporters and subclasses are copied, so a `Bytes` never aliases writable memory or hides a +/// reference cycle from the GC. +#[derive(Clone)] +pub struct PyBuffer(pub Bytes); /// The exporter behind each memoryview; views keep it, and so its bytes, alive. #[pyclass(frozen)] @@ -30,6 +43,41 @@ struct BufferView(Bytes); // ===== impl PyBuffer ===== +impl PyBuffer { + /// Whether `ob` is a `bytes`, `bytearray` or `memoryview`, so callers can dispatch by type + /// instead of building an error for each failed attempt. + #[inline] + pub fn is_bytes_like(ob: &Bound) -> bool { + ob.is_instance_of::() + || ob.is_instance_of::() + || ob.is_instance_of::() + } +} + +impl FromPyObject<'_, '_> for PyBuffer { + type Error = PyErr; + + fn extract(ob: Borrowed) -> PyResult { + let bytes = if ob.is_exact_instance_of::() || ob.is_instance_of::() { + // Shares an exact bytes and copies a bytearray. + Bytes::from_owner(ob.extract::()?) + } else if let Ok(bytes) = ob.cast::() { + // Subclasses can reference an exported view; Bytes owners are invisible to GC. + Bytes::copy_from_slice(bytes.as_bytes()) + } else if let Ok(view) = ob.cast::() { + view_bytes(&view)? + } else { + // Other exporters, such as numpy numbers or `array('d')`, count as bytes only in a + // memoryview, so `body=` and `from_binary` keep encoding them as JSON. + return Err(PyTypeError::new_err(format!( + "'{}' object is not an instance of 'bytes | bytearray | memoryview'", + ob.get_type().qualname()? + ))); + }; + Ok(Self(bytes)) + } +} + impl<'a> IntoPyObject<'a> for PyBuffer { type Target = PyMemoryView; type Output = Bound<'a, Self::Target>; @@ -37,7 +85,7 @@ impl<'a> IntoPyObject<'a> for PyBuffer { #[inline(always)] fn into_pyobject(self, py: Python<'a>) -> Result { - let buffer = self.0.into_pyobject(py)?; + let buffer = BufferView(self.0).into_pyobject(py)?; PyMemoryView::from(buffer.as_any()) } } @@ -59,7 +107,7 @@ impl From<&Bytes> for PyBuffer { impl From for PyBuffer { #[inline] fn from(value: Bytes) -> Self { - PyBuffer(BufferView(value)) + PyBuffer(value) } } @@ -117,18 +165,51 @@ impl BufferView { } } +/// Shares a view of an exact `bytes` or of our own memoryview, and copies any other view. +fn view_bytes(view: &Bound) -> PyResult { + let obj = view.getattr(intern!(view.py(), "obj"))?; + if let Ok(exporter) = obj.cast::() { + let bytes = &exporter.get().0; + if let Some(range) = view_range(view, bytes) { + return Ok(bytes.slice(range)); + } + } else if let Ok(bytes) = obj.cast_into_exact::() + && let Some(range) = view_range(view, bytes.as_bytes()) + { + return Ok(Bytes::from_owner(PyBackedBytes::from(bytes)).slice(range)); + } + // `bytes()` copies any layout or item format as raw bytes. + let copy = view + .py() + .get_type::() + .call1((view,))? + .cast_into::()?; + Ok(Bytes::from_owner(PyBackedBytes::from(copy))) +} + +/// The range of `data` that a C-contiguous `view` covers, if the view lies within it. +fn view_range(view: &Bound, data: &[u8]) -> Option> { + let buffer = PyUntypedBuffer::get(view.as_any()).ok()?; + if !buffer.is_c_contiguous() { + return None; + } + let start = buffer.buf_ptr().addr().checked_sub(data.as_ptr().addr())?; + let end = start.checked_add(buffer.len_bytes())?; + (end <= data.len()).then_some(start..end) +} + #[cfg(test)] mod tests { use pyo3::{ buffer::PyBuffer as PythonBuffer, - types::{PyBytes, PyString}, + types::{PySlice, PyString}, }; use super::*; - use crate::extractor::{Binary, Text}; + use crate::extractor::Text; #[test] - fn memoryview_shares_owned_bytes() { + fn buffers_share_immutable_bytes() { Python::initialize(); Python::attach(|py| { let bytes = Bytes::from(vec![0, 1, 255]); @@ -140,8 +221,18 @@ mod tests { assert!(buffer.readonly()); assert_eq!(buffer.to_vec(py).unwrap(), [0, 1, 255]); + // Our views come back shared, sliced or not; a strided one is copied. + let input = view.extract::().unwrap(); + assert_eq!(input.0.as_ptr(), ptr); + let tail = view.get_item(PySlice::new(py, 1, 3, 1)).unwrap(); + let input = tail.extract::().unwrap(); + assert_eq!(input.0.as_ptr(), ptr.wrapping_add(1)); + assert_eq!(input.0[..], [1, 255]); + let strided = view.get_item(PySlice::new(py, 0, 3, 2)).unwrap(); + assert_eq!(strided.extract::().unwrap().0[..], [0, 255]); + let binary = PyBytes::new(py, b"builtin bytes"); - let input = binary.extract::().unwrap(); + let input = binary.extract::().unwrap(); assert_eq!(input.0.as_ptr(), binary.as_bytes().as_ptr()); let view = PyBuffer::from(input.0).into_pyobject(py).unwrap(); let buffer = PythonBuffer::::get(view.as_any()).unwrap(); @@ -150,6 +241,22 @@ mod tests { binary.as_bytes().as_ptr() ); + let tail = PyMemoryView::from(binary.as_any()) + .unwrap() + .get_item(PySlice::new(py, 8, 13, 1)) + .unwrap(); + let input = tail.extract::().unwrap(); + assert_eq!(input.0.as_ptr(), binary.as_bytes()[8..].as_ptr()); + + // A bytearray may change after extraction, so its views are copied. + let array = PyByteArray::new(py, b"mutable"); + let input = PyMemoryView::from(array.as_any()) + .unwrap() + .extract::() + .unwrap(); + array.set_item(0, b'M').unwrap(); + assert_eq!(input.0[..], *b"mutable"); + let text = PyString::new(py, "builtin text"); let input = text.extract::().unwrap(); assert_eq!(input.0.as_ptr(), text.to_str().unwrap().as_ptr()); diff --git a/src/client/body.rs b/src/client/body.rs index bde05a09..75ec7508 100644 --- a/src/client/body.rs +++ b/src/client/body.rs @@ -8,21 +8,18 @@ mod stream; use pyo3::{ FromPyObject, PyResult, intern, prelude::*, - types::{PyByteArray, PyBytes, PyDict, PyIterator, PyList, PyString, PyTuple}, + types::{PyDict, PyIterator, PyList, PyString, PyTuple}, }; pub use self::{form::Form, json::Json, stream::PyStream}; -use crate::{ - error::Error, - extractor::{Binary, Text}, -}; +use crate::{buffer::PyBuffer, error::Error, extractor::Text}; /// A `body=` argument, matched by type before trying form, JSON and then a stream. /// Mappings and pair sequences with scalar values are form-encoded and other containers /// JSON-encoded, without the `Content-Type` that `form=` and `json=` set. pub enum Body { Text(Text), - Bytes(Binary), + Bytes(PyBuffer), Form(Form), Json(Json), Stream(PyStream), @@ -37,7 +34,7 @@ impl FromPyObject<'_, '_> for Body { if ob.is_instance_of::() { return ob.extract().map(Body::Text); } - if ob.is_instance_of::() || ob.is_instance_of::() { + if PyBuffer::is_bytes_like(&ob) { return ob.extract().map(Body::Bytes); } if ob.cast::().is_ok() { diff --git a/src/client/body/multipart.rs b/src/client/body/multipart.rs index 6ff8bd06..bcc26fcc 100644 --- a/src/client/body/multipart.rs +++ b/src/client/body/multipart.rs @@ -1,13 +1,13 @@ use std::path::PathBuf; -use pyo3::{prelude::*, types::PyTuple}; +use pyo3::{ + prelude::*, + types::{PyString, PyTuple}, +}; use wreq::{Body, multipart}; use crate::{ - client::body::PyStream, - error::Error, - extractor::{Binary, Text}, - header::HeaderMap, + buffer::PyBuffer, client::body::PyStream, error::Error, extractor::Text, header::HeaderMap, }; /// A multipart form for a request. Its files open when the request is built, on the @@ -17,11 +17,11 @@ pub struct Multipart { pub parts: Vec, } -/// The data for a part value of a multipart form. -#[derive(FromPyObject)] +/// The data for a part value of a multipart form: text, bytes-like data, a file path, or +/// otherwise a stream. pub enum Value { Text(Text), - Bytes(Binary), + Bytes(PyBuffer), File(PathBuf), Stream(PyStream), } @@ -93,6 +93,24 @@ impl FromPyObject<'_, '_> for Multipart { // ===== impl Value ===== +impl FromPyObject<'_, '_> for Value { + type Error = PyErr; + + fn extract(ob: Borrowed) -> PyResult { + // Matched by type, so a path or a stream does not first fail as text and bytes. + if ob.is_instance_of::() { + return ob.extract().map(Value::Text); + } + if PyBuffer::is_bytes_like(&ob) { + return ob.extract().map(Value::Bytes); + } + match ob.extract() { + Ok(path) => Ok(Value::File(path)), + Err(_) => ob.extract().map(Value::Stream), + } + } +} + impl Value { /// Copy a reusable value; `None` for a stream, which can be sent only once. fn try_clone(&self) -> Option { diff --git a/src/client/body/stream.rs b/src/client/body/stream.rs index 8fff96a6..230681c0 100644 --- a/src/client/body/stream.rs +++ b/src/client/body/stream.rs @@ -25,13 +25,13 @@ use pyo3::{ }; use self::{async_gen::AsyncStream, iter::SyncStream}; -use crate::extractor::{Binary, Text}; +use crate::{buffer::PyBuffer, extractor::Text}; type Item = PyResult; -/// A request body chunk: `bytes` or `bytearray` data, or a `str` sent as UTF-8. +/// A request body chunk: `bytes`, `bytearray` or `memoryview` data, or a `str` sent as UTF-8. pub enum PyBytesLike { - Bytes(Binary), + Bytes(PyBuffer), String(Text), } diff --git a/src/client/resp/ws/msg.rs b/src/client/resp/ws/msg.rs index 8d62dc25..afdfe713 100644 --- a/src/client/resp/ws/msg.rs +++ b/src/client/resp/ws/msg.rs @@ -12,17 +12,11 @@ use std::fmt::Debug; use pyo3::{exceptions::PyValueError, prelude::*}; use wreq::ws::message::{self, CloseCode, CloseFrame, Utf8Bytes}; -use crate::{ - buffer::PyBuffer, - client::body::Json, - error::Error, - extractor::{Binary, Text}, -}; +use crate::{buffer::PyBuffer, client::body::Json, error::Error, extractor::Text}; /// An enum representing either a bytes message or a JSON message. -#[derive(FromPyObject)] pub enum BytesLike { - Bytes(Binary), + Bytes(PyBuffer), Json(Json), } @@ -38,6 +32,23 @@ pub enum TextLike { #[pyclass(subclass, str, frozen, from_py_object)] pub struct Message(pub message::Message); +// ===== impl BytesLike ===== + +impl FromPyObject<'_, '_> for BytesLike { + type Error = PyErr; + + fn extract(ob: Borrowed) -> PyResult { + // Checked by type, so a JSON value does not first fail as bytes. + if PyBuffer::is_bytes_like(&ob) { + ob.extract().map(BytesLike::Bytes) + } else { + ob.extract().map(BytesLike::Json) + } + } +} + +// ===== impl Message ===== + #[pymethods] impl Message { /// Returns the message data as a read-only memoryview. @@ -145,14 +156,14 @@ impl Message { /// Creates a new ping message. #[staticmethod] #[pyo3(signature = (data))] - pub fn from_ping(data: Binary) -> Self { + pub fn from_ping(data: PyBuffer) -> Self { Self(message::Message::ping(data.0)) } /// Creates a new pong message. #[staticmethod] #[pyo3(signature = (data))] - pub fn from_pong(data: Binary) -> Self { + pub fn from_pong(data: PyBuffer) -> Self { Self(message::Message::pong(data.0)) } diff --git a/src/extractor.rs b/src/extractor.rs index 3ac60627..2c97ebe3 100644 --- a/src/extractor.rs +++ b/src/extractor.rs @@ -1,43 +1,16 @@ use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; use bytes::Bytes; -use pyo3::{ - FromPyObject, - prelude::*, - pybacked::{PyBackedBytes, PyBackedStr}, - types::{PyBytes, PyString}, -}; +use pyo3::{FromPyObject, prelude::*, pybacked::PyBackedStr, types::PyString}; /// Extracts a foreign type with custom rules, such as an `(IPv4, IPv6)` pair that drops the /// wrong family. pub struct Extractor(pub T); -/// Data of a `bytes` or `bytearray`. Exact `bytes` are shared without copying; subclasses -/// are copied so a cycle through the `Bytes` owner cannot hide from the GC. -#[derive(Clone)] -pub struct Binary(pub Bytes); - /// UTF-8 data of a `str`, shared for an exact `str` and copied for a subclass. #[derive(Clone)] pub struct Text(pub Bytes); -// ===== impl Binary ===== - -impl FromPyObject<'_, '_> for Binary { - type Error = PyErr; - - fn extract(ob: Borrowed) -> PyResult { - let value = ob.extract::()?; - // Subclasses can reference an exported view; Bytes owners are invisible to GC. - let bytes = if ob.is_instance_of::() && !ob.is_exact_instance_of::() { - Bytes::copy_from_slice(value.as_ref()) - } else { - Bytes::from_owner(value) - }; - Ok(Self(bytes)) - } -} - // ===== impl Text ===== impl FromPyObject<'_, '_> for Text { diff --git a/src/header.rs b/src/header.rs index efd1db38..3c8678a1 100644 --- a/src/header.rs +++ b/src/header.rs @@ -5,11 +5,7 @@ use pyo3::{ }; use wreq::header::{self, HeaderName, HeaderValue}; -use crate::{ - buffer::PyBuffer, - error::Error, - extractor::{Binary, Text}, -}; +use crate::{buffer::PyBuffer, error::Error, extractor::Text}; /// An HTTP header map whose names and values are exposed as read-only memoryviews. #[derive(Clone)] @@ -67,7 +63,7 @@ impl HeaderMap { /// is returned. Use `get_all` to get all values associated with a given /// key. Returns `None` if there are no values associated with the key. #[pyo3(signature = (key, default=None))] - fn get(&self, key: PyBackedStr, default: Option) -> Option { + fn get(&self, key: PyBackedStr, default: Option) -> Option { self.0 .get::<&str>(key.as_ref()) .cloned() diff --git a/tests/buffer_test.py b/tests/buffer_test.py index b78f1f30..9ee98dcf 100644 --- a/tests/buffer_test.py +++ b/tests/buffer_test.py @@ -1,3 +1,4 @@ +import array import asyncio import datetime import gc @@ -107,6 +108,11 @@ def original_name(source): cases = [ (Text, "payload", lambda source: Message.from_text(source).data), (Binary, b"payload", lambda source: Message.from_binary(source).binary), + ( + Binary, + b"payload", + lambda source: Message.from_binary(memoryview(source)).binary, + ), (Binary, b"payload", lambda source: Message.from_ping(source).ping), (Binary, b"payload", lambda source: Message.from_pong(source).pong), (Text, "payload", lambda source: HeaderMap({"X-Buffer": source})["X-Buffer"]), @@ -168,6 +174,21 @@ def do_GET(self): self.end_headers() self.wfile.write(b"hello world") + def do_POST(self): + if self.headers.get("Transfer-Encoding") == "chunked": + body = b"" + while size := int(self.rfile.readline(), 16): + body += self.rfile.read(size) + self.rfile.readline() + self.rfile.readline() + else: + body = self.rfile.read(int(self.headers["Content-Length"])) + self.send_response(200) + self.send_header("Connection", "close") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + def log_message(self, *_): pass @@ -185,6 +206,35 @@ def log_message(self, *_): assert not thread.is_alive() +def test_bytes_like_inputs(buffer_http_server): + sources = [ + Message.from_binary(b"").binary[1:-1], + memoryview(b"")[1:-1], + memoryview(bytearray(b"payload")), + memoryview(b"ppaayyllooaadd")[::2], + memoryview(array.array("B", b"payload")), + ] + client = blocking.Client(no_proxy=True, timeout=datetime.timedelta(seconds=3)) + try: + # Other exporters keep their JSON meaning unless wrapped in a memoryview. + numbers = array.array("d", [1.5]) + assert Message.from_binary(numbers).binary == b"[1.5]" + assert client.post(buffer_http_server, body=numbers).bytes() == b"[1.5]" + for source in sources: + assert Message.from_binary(source).binary == b"payload" + assert Message.from_ping(source).ping == b"payload" + assert Message.from_pong(source).pong == b"payload" + assert HeaderMap().get("missing", source) == b"payload" + for body in (source, iter([source])): + response = client.post(buffer_http_server, body=body) + assert response.bytes() == b"payload", source + form = Multipart(Part("field", source)) + response = client.post(buffer_http_server, multipart=form) + assert b"\r\n\r\npayload\r\n" in bytes(response.bytes()), source + finally: + client.close() + + @pytest.mark.asyncio @pytest.mark.parametrize("blocking_api", [False, True]) async def test_response_and_stream_views(buffer_http_server, blocking_api): From 3ccbf051d722c725c3ad99bd1939849b822e4f2e Mon Sep 17 00:00:00 2001 From: 0x676e67 Date: Sat, 31 Oct 2026 09:10:56 +0000 Subject: [PATCH 2/6] perf(buffer): extract bytes-like input in one pass and share empty data without an owner --- src/buffer.rs | 135 +++++++++++++++++++++++++---------- src/client/body.rs | 4 +- src/client/body/multipart.rs | 4 +- src/client/resp/ws/msg.rs | 7 +- tests/buffer_test.py | 4 ++ 5 files changed, 110 insertions(+), 44 deletions(-) diff --git a/src/buffer.rs b/src/buffer.rs index 85b9aae7..ec4b7ebb 100644 --- a/src/buffer.rs +++ b/src/buffer.rs @@ -17,8 +17,9 @@ use std::{ops::Range, os::raw::c_int}; -use bytes::Bytes; +use bytes::{Buf, Bytes}; use pyo3::{ + PyTypeCheck, PyTypeInfo, buffer::PyUntypedBuffer, exceptions::{PyOverflowError, PyTypeError}, ffi, intern, @@ -44,13 +45,22 @@ struct BufferView(Bytes); // ===== impl PyBuffer ===== impl PyBuffer { - /// Whether `ob` is a `bytes`, `bytearray` or `memoryview`, so callers can dispatch by type - /// instead of building an error for each failed attempt. - #[inline] - pub fn is_bytes_like(ob: &Bound) -> bool { - ob.is_instance_of::() - || ob.is_instance_of::() - || ob.is_instance_of::() + /// Extracts `bytes`, `bytearray` or `memoryview` data in one pass over their types, or + /// returns `None` for any other type without building an error, so callers can fall back. + pub fn extract_bytes_like(ob: &Bound) -> Option> { + let bytes = if let Some(bytes) = as_exact::(ob) { + let owner = PyBackedBytes::from(bytes.clone()); + share(0..owner.len(), owner) + } else if let Some(view) = as_exact::(ob) { + return Some(view_bytes(view).map(Self)); + } else if let Some(array) = as_instance::(ob) { + // A bytearray may change after extraction, so it is copied once. + Bytes::from(array.to_vec()) + } else { + // Subclasses can reference an exported view; Bytes owners are invisible to GC. + Bytes::copy_from_slice(as_instance::(ob)?.as_bytes()) + }; + Some(Ok(Self(bytes))) } } @@ -58,23 +68,15 @@ impl FromPyObject<'_, '_> for PyBuffer { type Error = PyErr; fn extract(ob: Borrowed) -> PyResult { - let bytes = if ob.is_exact_instance_of::() || ob.is_instance_of::() { - // Shares an exact bytes and copies a bytearray. - Bytes::from_owner(ob.extract::()?) - } else if let Ok(bytes) = ob.cast::() { - // Subclasses can reference an exported view; Bytes owners are invisible to GC. - Bytes::copy_from_slice(bytes.as_bytes()) - } else if let Ok(view) = ob.cast::() { - view_bytes(&view)? - } else { + match Self::extract_bytes_like(&ob) { + Some(bytes) => bytes, // Other exporters, such as numpy numbers or `array('d')`, count as bytes only in a // memoryview, so `body=` and `from_binary` keep encoding them as JSON. - return Err(PyTypeError::new_err(format!( + None => Err(PyTypeError::new_err(format!( "'{}' object is not an instance of 'bytes | bytearray | memoryview'", ob.get_type().qualname()? - ))); - }; - Ok(Self(bytes)) + ))), + } } } @@ -139,11 +141,11 @@ impl BufferView { /// `view` must be a writable `Py_buffer` supplied by the Python buffer protocol. #[allow(unsafe_code)] unsafe fn __getbuffer__( - slf: PyRef, + slf: &Bound<'_, Self>, view: *mut ffi::Py_buffer, flags: c_int, ) -> PyResult<()> { - let bytes = &slf.0; + let bytes = &slf.get().0; let len = ffi::Py_ssize_t::try_from(bytes.len()) .map_err(|_| PyOverflowError::new_err("buffer length exceeds Python's maximum size"))?; // SAFETY: PyO3 supplies a valid output buffer. FillInfo retains the exporter, @@ -168,15 +170,20 @@ impl BufferView { /// Shares a view of an exact `bytes` or of our own memoryview, and copies any other view. fn view_bytes(view: &Bound) -> PyResult { let obj = view.getattr(intern!(view.py(), "obj"))?; - if let Ok(exporter) = obj.cast::() { + // BufferView allows no subclasses, so an exact test covers it. + if let Some(exporter) = as_exact::(&obj) { let bytes = &exporter.get().0; if let Some(range) = view_range(view, bytes) { + // A counted clone of the exporter's Bytes, whatever its vtable. return Ok(bytes.slice(range)); } - } else if let Ok(bytes) = obj.cast_into_exact::() - && let Some(range) = view_range(view, bytes.as_bytes()) + } else if obj.is_exact_instance_of::() + && let Ok(bytes) = obj.cast_into_exact::() { - return Ok(Bytes::from_owner(PyBackedBytes::from(bytes)).slice(range)); + let owner = PyBackedBytes::from(bytes); + if let Some(range) = view_range(view, &owner) { + return Ok(share(range, owner)); + } } // `bytes()` copies any layout or item format as raw bytes. let copy = view @@ -184,20 +191,59 @@ fn view_bytes(view: &Bound) -> PyResult { .get_type::() .call1((view,))? .cast_into::()?; - Ok(Bytes::from_owner(PyBackedBytes::from(copy))) + let owner = PyBackedBytes::from(copy); + Ok(share(0..owner.len(), owner)) +} + +/// Shares the `range` of the exact `bytes` behind `owner`, which must contain it. Empty data +/// needs no owner, and the owned `Bytes` narrows in place instead of through a counted clone. +#[inline] +fn share(range: Range, owner: PyBackedBytes) -> Bytes { + if range.is_empty() { + return Bytes::new(); + } + let mut bytes = Bytes::from_owner(owner); + bytes.truncate(range.end); + bytes.advance(range.start); + bytes } /// The range of `data` that a C-contiguous `view` covers, if the view lies within it. fn view_range(view: &Bound, data: &[u8]) -> Option> { let buffer = PyUntypedBuffer::get(view.as_any()).ok()?; - if !buffer.is_c_contiguous() { + let contiguous = buffer.is_c_contiguous(); + let (ptr, len) = (buffer.buf_ptr().addr(), buffer.len_bytes()); + // Released while attached, so `Drop` need not attach to the interpreter. + buffer.release(view.py()); + if !contiguous { return None; } - let start = buffer.buf_ptr().addr().checked_sub(data.as_ptr().addr())?; - let end = start.checked_add(buffer.len_bytes())?; + let start = ptr.checked_sub(data.as_ptr().addr())?; + let end = start.checked_add(len)?; (end <= data.len()).then_some(start..end) } +/// `ob` as exactly a `T`; other types return `None` without building a cast error. +#[inline] +fn as_exact<'a, 'py, T: PyTypeInfo>(ob: &'a Bound<'py, PyAny>) -> Option<&'a Bound<'py, T>> { + // The cast repeats the checked type test and cannot fail. + if ob.is_exact_instance_of::() { + ob.cast_exact().ok() + } else { + None + } +} + +/// `ob` as a `T` or a subclass; other types return `None` without building a cast error. +#[inline] +fn as_instance<'a, 'py, T: PyTypeCheck>(ob: &'a Bound<'py, PyAny>) -> Option<&'a Bound<'py, T>> { + if ob.is_instance_of::() { + ob.cast().ok() + } else { + None + } +} + #[cfg(test)] mod tests { use pyo3::{ @@ -241,12 +287,20 @@ mod tests { binary.as_bytes().as_ptr() ); - let tail = PyMemoryView::from(binary.as_any()) - .unwrap() - .get_item(PySlice::new(py, 8, 13, 1)) - .unwrap(); - let input = tail.extract::().unwrap(); + // Views of an exact bytes share it, whole or narrowed; empty data needs no owner. + let view = PyMemoryView::from(binary.as_any()).unwrap(); + let input = view.extract::().unwrap(); + assert_eq!(input.0.as_ptr(), binary.as_bytes().as_ptr()); + assert_eq!(input.0[..], *b"builtin bytes"); + let word = view.get_item(PySlice::new(py, 8, 12, 1)).unwrap(); + let input = word.extract::().unwrap(); assert_eq!(input.0.as_ptr(), binary.as_bytes()[8..].as_ptr()); + assert_eq!(input.0[..], *b"byte"); + let empty = view.get_item(PySlice::new(py, 3, 3, 1)).unwrap(); + let input = empty.extract::().unwrap(); + assert_eq!(input.0.as_ptr(), Bytes::new().as_ptr()); + let input = PyBytes::new(py, b"").extract::().unwrap(); + assert_eq!(input.0.as_ptr(), Bytes::new().as_ptr()); // A bytearray may change after extraction, so its views are copied. let array = PyByteArray::new(py, b"mutable"); @@ -257,6 +311,15 @@ mod tests { array.set_item(0, b'M').unwrap(); assert_eq!(input.0[..], *b"mutable"); + // A bytes subclass can reference an exported view, so it is copied as well. + let module = + PyModule::from_code(py, c"class Sub(bytes): pass", c"sub.py", c"sub").unwrap(); + let sub = module.getattr("Sub").unwrap().call1((&binary,)).unwrap(); + let input = sub.extract::().unwrap(); + let data = sub.cast::().unwrap().as_bytes(); + assert_ne!(input.0.as_ptr(), data.as_ptr()); + assert_eq!(input.0[..], *data); + let text = PyString::new(py, "builtin text"); let input = text.extract::().unwrap(); assert_eq!(input.0.as_ptr(), text.to_str().unwrap().as_ptr()); diff --git a/src/client/body.rs b/src/client/body.rs index 75ec7508..708820ba 100644 --- a/src/client/body.rs +++ b/src/client/body.rs @@ -34,8 +34,8 @@ impl FromPyObject<'_, '_> for Body { if ob.is_instance_of::() { return ob.extract().map(Body::Text); } - if PyBuffer::is_bytes_like(&ob) { - return ob.extract().map(Body::Bytes); + if let Some(bytes) = PyBuffer::extract_bytes_like(&ob) { + return bytes.map(Body::Bytes); } if ob.cast::().is_ok() { return ob.extract().map(Body::Stream); diff --git a/src/client/body/multipart.rs b/src/client/body/multipart.rs index bcc26fcc..3606997f 100644 --- a/src/client/body/multipart.rs +++ b/src/client/body/multipart.rs @@ -101,8 +101,8 @@ impl FromPyObject<'_, '_> for Value { if ob.is_instance_of::() { return ob.extract().map(Value::Text); } - if PyBuffer::is_bytes_like(&ob) { - return ob.extract().map(Value::Bytes); + if let Some(bytes) = PyBuffer::extract_bytes_like(&ob) { + return bytes.map(Value::Bytes); } match ob.extract() { Ok(path) => Ok(Value::File(path)), diff --git a/src/client/resp/ws/msg.rs b/src/client/resp/ws/msg.rs index afdfe713..3a04e299 100644 --- a/src/client/resp/ws/msg.rs +++ b/src/client/resp/ws/msg.rs @@ -39,10 +39,9 @@ impl FromPyObject<'_, '_> for BytesLike { fn extract(ob: Borrowed) -> PyResult { // Checked by type, so a JSON value does not first fail as bytes. - if PyBuffer::is_bytes_like(&ob) { - ob.extract().map(BytesLike::Bytes) - } else { - ob.extract().map(BytesLike::Json) + match PyBuffer::extract_bytes_like(&ob) { + Some(bytes) => bytes.map(BytesLike::Bytes), + None => ob.extract().map(BytesLike::Json), } } } diff --git a/tests/buffer_test.py b/tests/buffer_test.py index 9ee98dcf..f036d9dc 100644 --- a/tests/buffer_test.py +++ b/tests/buffer_test.py @@ -220,6 +220,10 @@ def test_bytes_like_inputs(buffer_http_server): numbers = array.array("d", [1.5]) assert Message.from_binary(numbers).binary == b"[1.5]" assert client.post(buffer_http_server, body=numbers).bytes() == b"[1.5]" + assert Message.from_binary({"a": 1}).binary == b'{"a":1}' + message = r"'dict' object is not an instance of 'bytes \| bytearray \| memoryview'" + with pytest.raises(TypeError, match=message): + Message.from_ping({}) for source in sources: assert Message.from_binary(source).binary == b"payload" assert Message.from_ping(source).ping == b"payload" From 722db46dea9bab77c6ca9ff4ab6a9dee93e0a890 Mon Sep 17 00:00:00 2001 From: 0x676e67 Date: Mon, 2 Nov 2026 12:29:11 +0000 Subject: [PATCH 3/6] feat(buffer): return zero-copy wreq.Bytes for large data and native bytes for short values --- Cargo.lock | 1 + Cargo.toml | 1 + RELEASE.md | 1 + docs/source/api/wreq.md | 6 + docs/source/getting-started/introduction.md | 7 +- docs/source/getting-started/quickstart.md | 39 +- docs/source/guide/basic.md | 23 +- docs/source/guide/blocking.md | 12 +- docs/source/guide/websocket.md | 9 +- docs/source/index.md | 2 +- examples/blocking/stream.py | 6 +- examples/stream.py | 6 +- python/wreq/__init__.py | 5 + python/wreq/blocking.py | 14 +- python/wreq/header.py | 33 +- python/wreq/tls.py | 26 +- python/wreq/wreq.py | 214 +++++- src/buffer.rs | 722 ++++++++++++++++++-- src/client/body/stream.rs | 3 +- src/client/resp/http.rs | 12 +- src/client/resp/stream.rs | 8 +- src/client/resp/ws/msg.rs | 19 +- src/header.rs | 64 +- src/lib.rs | 2 + src/tls.rs | 10 +- src/tls/identity.rs | 12 +- src/tls/store.rs | 14 +- tests/buffer_test.py | 290 ++++++-- tests/response_test.py | 3 +- tests/tls_test.py | 16 +- 30 files changed, 1283 insertions(+), 297 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 1c653627..3586d7e4 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2652,6 +2652,7 @@ dependencies = [ "http-body", "http-body-util", "indexmap", + "memchr", "mimalloc", "pingora-runtime", "pyo3", diff --git a/Cargo.toml b/Cargo.toml index ea83fda9..3dca298c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -44,6 +44,7 @@ serde_json = "1" serde_urlencoded = "0.7.1" indexmap = { version = "2.13.0", features = ["serde"] } bytes = "1.12.1" +memchr = "2.8" http = "1.4.2" http-body = "1.1.0" http-body-util = "0.1.4" diff --git a/RELEASE.md b/RELEASE.md index 8604b96b..7e361d6f 100644 --- a/RELEASE.md +++ b/RELEASE.md @@ -5,6 +5,7 @@ - Unknown keyword arguments now raise `TypeError` when calling async or blocking client constructors, HTTP or WebSocket request methods and functions, `Http1Options`, `Http2Options`, `TlsOptions`, or `Proxy` factories. These arguments were previously ignored. - Set client-only options such as `connect_timeout` and `proxies` on `Client`; passing them to a request now raises `TypeError`. Use `proxy` to select a proxy for one request. - Async request calls check keyword names before returning a coroutine. Values for supported request keywords are still converted on first `await` or entry with `async with`. +- Header names and values, `Message.ping`/`pong` and `TlsInfo.peer_certificate()` return `bytes` again instead of `memoryview`. `Response.bytes()`, stream data frames and `Message.data`/`binary` return the new immutable `wreq.Bytes`, which shares data without copying and compares and hashes like `bytes`. Tell stream frames apart with `isinstance(chunk, HeaderMap)` rather than `isinstance(chunk, memoryview)`, and use `memoryview(data)` for `memoryview` attributes such as `.obj`, `.cast()` or `.tolist()`. `bytes` values have no `.tobytes()` or `.release()`; on `wreq.Bytes`, `release()` and `with` emit `DeprecationWarning`. APIs that accept only `bytes`, `bytearray` or `memoryview` by type, such as asyncio `StreamWriter.write` and transports or `orjson.loads`, reject `wreq.Bytes`; pass `memoryview(data)`, which does not copy. ## [0.11.0](https://github.com/0x676e67/wreq-python/compare/v0.10.2..v0.11.0) - 2026-04-13 diff --git a/docs/source/api/wreq.md b/docs/source/api/wreq.md index 3d157f79..d3befe99 100644 --- a/docs/source/api/wreq.md +++ b/docs/source/api/wreq.md @@ -59,6 +59,12 @@ The main `wreq` module contains core classes and types used throughout the libra options: show_root_heading: true +## Binary Data + +::: wreq.Bytes + options: + show_root_heading: true + ## Network Types ::: wreq.SocketAddr diff --git a/docs/source/getting-started/introduction.md b/docs/source/getting-started/introduction.md index ad2d66f0..d694de1a 100644 --- a/docs/source/getting-started/introduction.md +++ b/docs/source/getting-started/introduction.md @@ -52,9 +52,10 @@ connections, and use context managers to close resources when you're done. - **Streaming and buffers** - Stream request and response bodies, or read a complete body. Rust-backed - binary outputs are read-only `memoryview` objects. Convert to `bytes` when - an API requires that type; the conversion copies the data. + Stream request and response bodies, or read a complete body. Bodies and + stream data are zero-copy `wreq.Bytes` objects, and short values such as + headers are `bytes`. Use `data.tobytes()` when an API requires `bytes`; the + conversion copies the data. [Advanced features](../guide/advanced.md) diff --git a/docs/source/getting-started/quickstart.md b/docs/source/getting-started/quickstart.md index 3e26598a..1ea2fe4b 100644 --- a/docs/source/getting-started/quickstart.md +++ b/docs/source/getting-started/quickstart.md @@ -108,32 +108,35 @@ Finish each read before starting another. For large bodies, see ### Binary data -`bytes()` returns a read-only `memoryview` backed by Rust-owned data. Returning -the view is zero-copy; collecting a complete response can still allocate memory -to join body chunks. +`bytes()` returns an immutable `wreq.Bytes` backed by Rust-owned data. Returning +it is zero-copy; collecting a complete response can still allocate memory to +join body chunks. ```python import hashlib async with client.get("https://httpbin.org/bytes/16") as response: - view = await response.bytes() + data = await response.bytes() -print(view.readonly) # True -print(hashlib.sha256(view).hexdigest()) +print(len(data), data[:4]) +print(hashlib.sha256(data).hexdigest()) ``` -The view remains valid after the response closes. Use it directly with APIs -that accept buffers, such as `file.write(view)` or `hashlib.sha256(view)`. -For text, use `str(view, "utf-8")`; memoryviews have no `.decode()` method. - -Use `bytes(view)` or `view.tobytes()` when an API needs a `bytes` object. Both -copy the data. This includes passing a view back to wreq's binary inputs such -as `body`, `Part`, `Message` constructors or `CertStore`. You can release your -reference early with `view.release()`; other views and slices stay valid. - -The blocking API returns the same type. Stream data frames, binary WebSocket -fields, header names and values, and peer certificates also use read-only -memoryviews that retain their backing data. +The data remains valid after the response closes. Use it directly with APIs +that accept buffers, such as `file.write(data)` or `hashlib.sha256(data)`. It +compares and hashes like `bytes`, and provides read-only `bytes` methods such as +`decode()`, `find()`, `count()` and `startswith()`, plus zero-copy slicing. Passing it back to wreq, for example as a +request `body` or to `Message.from_binary`, does not copy it. + +Use `data.tobytes()` when an API needs a `bytes` object, such as `json.loads` +or code that checks `isinstance(x, bytes)`; it copies the data. APIs that accept +only `bytes`, `bytearray` or `memoryview` by type, such as asyncio transports +and `orjson.loads`, take `memoryview(data)` without copying. + +The blocking API returns the same type, and so do stream data frames and the +`data` and `binary` fields of WebSocket messages. Short values are plain +`bytes`: header names and values, WebSocket ping and pong payloads, and peer +certificates. ## Set headers diff --git a/docs/source/guide/basic.md b/docs/source/guide/basic.md index cf03e13b..bd86b322 100644 --- a/docs/source/guide/basic.md +++ b/docs/source/guide/basic.md @@ -117,18 +117,17 @@ from wreq.header import HeaderMap headers = HeaderMap({"Accept": "application/json"}) headers.append("Accept", "text/html") -print([str(value, "ascii") for value in headers.get_all("accept")]) +print([value.decode("ascii") for value in headers.get_all("accept")]) async with client.get("https://httpbin.org/headers", headers=headers) as response: content_type = response.headers.get("content-type") if content_type is not None: - print(str(content_type, "ascii")) + print(content_type.decode("ascii")) print(await response.json()) ``` Header names are case insensitive. Header names and values returned by -`HeaderMap` are read-only memoryviews; `str(view, encoding)` decodes them -without an intermediate `bytes` copy. +`HeaderMap` are `bytes`. ## Authentication @@ -209,10 +208,10 @@ another. `stream()` only accepts an unread body and transfers it to a streamer; after that, use the streamer to read it. Reading a released body or starting an overlapping read raises `RuntimeError`. -`bytes()` returns a zero-copy, read-only memoryview of the collected Rust -buffer. Collecting the body may allocate to join chunks. Views stay valid after -the response closes; see [binary data](../getting-started/quickstart.md#binary-data) -for decoding, copying and releasing them. +`bytes()` returns a zero-copy `wreq.Bytes` of the collected Rust buffer. +Collecting the body may allocate to join chunks. The data stays valid after the +response closes; see [binary data](../getting-started/quickstart.md#binary-data) +for decoding and copying it. ## Concurrent requests @@ -253,7 +252,7 @@ propagate when a caller cancels your task. ## Streaming responses Read large bodies incrementally with `response.stream()`. Data frames are -read-only memoryviews, and trailing HTTP headers are `HeaderMap` objects. +`wreq.Bytes`, and trailing HTTP headers are `HeaderMap` objects. This complete example counts the bytes without retaining the whole body: ```python @@ -269,10 +268,10 @@ async def main(): response.raise_for_status() async with response.stream() as streamer: async for frame in streamer: - if isinstance(frame, memoryview): - total += len(frame) - elif isinstance(frame, HeaderMap): + if isinstance(frame, HeaderMap): print("Trailers:", frame) + else: + total += len(frame) print("Received bytes:", total) diff --git a/docs/source/guide/blocking.md b/docs/source/guide/blocking.md index 96131f96..3ecd6d72 100644 --- a/docs/source/guide/blocking.md +++ b/docs/source/guide/blocking.md @@ -111,7 +111,7 @@ Closing a client cancels pending requests and rejects new ones with ## Streaming response -`response.bytes()` returns a read-only memoryview of the complete body. To +`response.bytes()` returns a zero-copy `wreq.Bytes` of the complete body. To write a large response incrementally, use a streamer: ```python @@ -124,14 +124,14 @@ with Client() as client: response.raise_for_status() with response.stream() as streamer, open("download.bin", "wb") as output: for frame in streamer: - if isinstance(frame, memoryview): - output.write(frame) - elif isinstance(frame, HeaderMap): + if isinstance(frame, HeaderMap): print("Trailers:", frame) + else: + output.write(frame) ``` -Data views remain valid after the stream closes. `output.write(frame)` accepts -the buffer directly; `bytes(frame)` makes a copy. Only an unread response can +Data frames remain valid after the stream closes. `output.write(frame)` accepts +the buffer directly; `frame.tobytes()` makes a copy. Only an unread response can be streamed. Complete body reads through `text()`, `json()` or `bytes()` are cached and can be repeated sequentially until the response is released. diff --git a/docs/source/guide/websocket.md b/docs/source/guide/websocket.md index 442923e4..cf895760 100644 --- a/docs/source/guide/websocket.md +++ b/docs/source/guide/websocket.md @@ -41,10 +41,11 @@ Use `Message.from_binary(data)` to send binary data. `send_all([...])` sends a sequence of messages in order. To choose the closing status, call `await ws.close(code=1000, reason="Finished")` before leaving the context. -Binary payload access is zero-copy: `Message.data`, `.binary`, `.ping`, and -`.pong` return read-only `memoryview` objects when present. The views remain -valid after the message is deleted or the connection closes. Use `bytes(view)` -when another API requires a `bytes` object; `Message.text` returns a string. +Binary payload access is zero-copy: `Message.data` and `.binary` return +`wreq.Bytes` when present, which stay valid after the message is deleted or the +connection closes. `.ping` and `.pong` return `bytes`, since RFC 6455 limits +control payloads to 125 bytes. Use `data.tobytes()` when another API requires a +`bytes` object; `Message.text` returns a string. ## Receive timeouts diff --git a/docs/source/index.md b/docs/source/index.md index 285d5ab9..87686c92 100644 --- a/docs/source/index.md +++ b/docs/source/index.md @@ -81,7 +81,7 @@ asyncio.run(main()) 02 · PERFORMANCE

High-throughput HTTPS

Rust handles the network I/O. See how wreq compares with other Python clients, then choose the body size and runtime mode that matter to your workload.

View performance results
-03 · STREAMING

Stream uploads and responses

Send an upload in chunks or read a response as it arrives. Response chunks are read-only memoryviews backed by Rust buffers.

Streaming guide
+03 · STREAMING

Stream uploads and responses

Send an upload in chunks or read a response as it arrives. Response chunks are zero-copy wreq.Bytes objects backed by Rust buffers.

Streaming guide
04 · PYTHON

Async and blocking APIs

Use await in async code. For a synchronous script, import Client from wreq.blocking.

Blocking API
diff --git a/examples/blocking/stream.py b/examples/blocking/stream.py index a3bda692..72a8ab69 100644 --- a/examples/blocking/stream.py +++ b/examples/blocking/stream.py @@ -9,10 +9,10 @@ def main(): with wreq.blocking.get("https://httpbin.io/stream/20") as resp: with resp.stream() as streamer: for chunk in streamer: - if isinstance(chunk, memoryview): - sys.stdout.buffer.write(chunk) - else: + if isinstance(chunk, wreq.HeaderMap): print("Trailers:", chunk) + else: + sys.stdout.buffer.write(chunk) time.sleep(0.1) diff --git a/examples/stream.py b/examples/stream.py index 79552d1a..dd16f8b2 100644 --- a/examples/stream.py +++ b/examples/stream.py @@ -7,10 +7,10 @@ async def main(): async with wreq.get("https://httpbin.io/stream/20") as resp: async with resp.stream() as streamer: async for chunk in streamer: - if isinstance(chunk, memoryview): - sys.stdout.buffer.write(chunk) - else: + if isinstance(chunk, wreq.HeaderMap): print("Trailers:", chunk) + else: + sys.stdout.buffer.write(chunk) await asyncio.sleep(0.1) diff --git a/python/wreq/__init__.py b/python/wreq/__init__.py index 9dc0c8d4..40ddd9a0 100644 --- a/python/wreq/__init__.py +++ b/python/wreq/__init__.py @@ -1,5 +1,7 @@ # wreq/__init__.py +from collections.abc import Sequence as _Sequence + from .wreq import * from .cookie import * @@ -14,6 +16,9 @@ from .proxy import * from .runtime import * +# A Sequence like `bytes`; like `memoryview`, it also matches sequence patterns in `match`. +_Sequence.register(Bytes) # pyright: ignore[reportAttributeAccessIssue] + __all__ = ( header.__all__ + cookie.__all__ diff --git a/python/wreq/blocking.py b/python/wreq/blocking.py index f1f454d7..33579e38 100644 --- a/python/wreq/blocking.py +++ b/python/wreq/blocking.py @@ -22,6 +22,7 @@ from .redirect import History from .runtime import Runtime from .tls import TlsInfo +from .wreq import Bytes class Response: @@ -86,7 +87,7 @@ def raise_for_status(self) -> None: def stream(self) -> Streamer: r""" - Stream the body as read-only memoryviews, with HeaderMap frames for trailers. + Stream the body as immutable `Bytes`, with HeaderMap frames for trailers. """ ... @@ -101,11 +102,12 @@ def json(self) -> Any: Get the JSON content of the response. """ - def bytes(self) -> memoryview: + def bytes(self) -> Bytes: r""" - Read the body as a read-only memoryview without copying it into Python bytes. - The view remains valid after the response is closed or deleted. - Use bytes(view) or view.tobytes() for a copy; view.release() releases this view. + Read the body as an immutable `Bytes` without copying it. + The data stays valid after the response is closed or deleted. + Use `data.tobytes()` for a `bytes` copy, or `memoryview(data)` for APIs that accept + only `bytes`, `bytearray` or `memoryview`. """ ... @@ -114,7 +116,7 @@ def close(self) -> None: Discard the retained body and mark its connection as non-reusable. This does not guarantee an immediate socket shutdown or interrupt an active read. Do not close concurrently with a body read. A body transferred to a Streamer - is managed separately; previously returned memoryviews remain valid. + is managed separately; previously returned `Bytes` remain valid. `with` instead releases the body and keeps a fully read connection reusable. """ diff --git a/python/wreq/header.py b/python/wreq/header.py index 8a986940..9e1a53eb 100644 --- a/python/wreq/header.py +++ b/python/wreq/header.py @@ -13,6 +13,8 @@ from typing import Iterator, Tuple +from .wreq import Bytes + __all__ = ["HeaderMap", "OrigHeaderMap"] @@ -28,11 +30,10 @@ class HeaderMap: and provides both dictionary-like access and specialized methods for HTTP header manipulation. - Header names and values are returned as read-only memoryviews. - Each view retains its backing data even if the map is changed or deleted. + Header names and values are returned as `bytes` copies. """ - def __getitem__(self, key: str) -> memoryview | None: + def __getitem__(self, key: str) -> bytes | None: """Get the first value for a header name (case-insensitive).""" ... @@ -52,7 +53,7 @@ def __len__(self) -> int: """Return the total number of header values (not unique names).""" ... - def __iter__(self) -> Iterator[Tuple[memoryview, memoryview]]: + def __iter__(self) -> Iterator[Tuple[bytes, bytes]]: """Iterate all header(name, value) pairs, including duplicates for multiple values.""" ... @@ -144,8 +145,8 @@ def remove(self, key: str) -> None: ... def get( - self, key: str, default: bytes | bytearray | memoryview | None = None - ) -> memoryview | None: + self, key: str, default: bytes | bytearray | memoryview | Bytes | None = None + ) -> bytes | None: r""" Get the first value for a header name with optional default. @@ -158,15 +159,15 @@ def get( default: Value to return if header doesn't exist Returns: - A read-only view of the first header value, or of the default value + The first header value, or the default value, as `bytes` """ ... - def get_all(self, key: str) -> list[memoryview]: + def get_all(self, key: str) -> list[bytes]: r""" Get all values for a header name. - Returns a list of read-only views of all values associated with the header name. + Returns a list of all values associated with the header name. This is useful for headers that can have multiple values, such as Set-Cookie, Accept-Encoding, or custom headers. @@ -174,25 +175,25 @@ def get_all(self, key: str) -> list[memoryview]: key: The header name (case-insensitive) Returns: - A list of read-only header value views + A list of header values as `bytes` """ ... - def values(self) -> list[memoryview]: + def values(self) -> list[bytes]: """ Get all header values. Returns: - A list of read-only header value views. + A list of header values as `bytes`. """ ... - def keys(self) -> list[memoryview]: + def keys(self) -> list[bytes]: """ Get all unique header names. Returns: - A list of read-only header name views. + A list of header names as `bytes`. """ ... @@ -252,7 +253,7 @@ class OrigHeaderMap: The map stores a mapping between the case-insensitive (standard) header name and the original case-sensitive header name as it appeared in the HTTP message. - Iteration returns pairs of read-only memoryviews that retain their backing data. + Iteration returns pairs of `bytes`. Example: If an HTTP message included the following headers: @@ -284,7 +285,7 @@ def __init__( """ ... - def __iter__(self) -> Iterator[Tuple[memoryview, memoryview]]: + def __iter__(self) -> Iterator[Tuple[bytes, bytes]]: """ Returns an iterator over the (standard_name, original_name) pairs. diff --git a/python/wreq/tls.py b/python/wreq/tls.py index b1662cad..d4cfb94e 100644 --- a/python/wreq/tls.py +++ b/python/wreq/tls.py @@ -6,7 +6,11 @@ from enum import Enum, auto from pathlib import Path -from typing import Sequence, NotRequired, TypedDict, Unpack, final +from typing import Sequence, NotRequired, TypeAlias, TypedDict, Unpack, final + +from .wreq import Bytes + +_BytesLike: TypeAlias = "bytes | bytearray | memoryview | Bytes" __all__ = [ "TlsVersion", @@ -134,7 +138,7 @@ class Identity: """ @staticmethod - def from_pkcs12_der(buf: bytes, pass_: str, /) -> "Identity": + def from_pkcs12_der(buf: _BytesLike, pass_: str, /) -> "Identity": """ Parses a DER-formatted PKCS #12 archive, using the specified password to decrypt the key. Pass the archive and password positionally: Identity.from_pkcs12_der(data, password). @@ -151,7 +155,7 @@ def from_pkcs12_der(buf: bytes, pass_: str, /) -> "Identity": ... @staticmethod - def from_pkcs8_pem(buf: bytes, key: bytes) -> "Identity": + def from_pkcs8_pem(buf: _BytesLike, key: _BytesLike) -> "Identity": """ Parses a chain of PEM encoded X509 certificates, with the leaf certificate first. `key` is a PEM encoded PKCS #8 formatted private key for the leaf certificate. @@ -172,7 +176,7 @@ class CertStore: def __init__( self, - der_certs: Sequence[bytes] | None = None, + der_certs: Sequence[_BytesLike] | None = None, pem_certs: Sequence[str] | None = None, default_paths: bool = False, ) -> None: @@ -180,19 +184,19 @@ def __init__( Creates a new CertStore. Args: - der_certs: Optional list of DER-encoded certificates (as bytes). + der_certs: Optional list of DER-encoded certificates (bytes-like). pem_certs: Optional list of PEM-encoded certificates (as str). default_paths: If True, use system default certificate paths. Defaults to False. """ ... @staticmethod - def from_der_certs(certs: Sequence[bytes]) -> "CertStore": + def from_der_certs(certs: Sequence[_BytesLike]) -> "CertStore": """ Creates a CertStore from a collection of DER-encoded certificates. Args: - certs: List of DER-encoded certificates (as bytes). + certs: List of DER-encoded certificates (bytes-like). """ ... @@ -207,12 +211,12 @@ def from_pem_certs(certs: Sequence[str]) -> "CertStore": ... @staticmethod - def from_pem_stack(certs: bytes) -> "CertStore": + def from_pem_stack(certs: _BytesLike) -> "CertStore": """ Creates a CertStore from a PEM-encoded certificate stack. Args: - certs: PEM-encoded certificate stack (as bytes). + certs: PEM-encoded certificate stack (bytes-like). """ ... @@ -460,8 +464,8 @@ class TlsInfo: Information about the established TLS connection. """ - def peer_certificate(self) -> memoryview | None: + def peer_certificate(self) -> bytes | None: """ - Get a read-only memoryview of the peer's DER-encoded leaf certificate. + Get the peer's DER-encoded leaf certificate as `bytes`. """ ... diff --git a/python/wreq/wreq.py b/python/wreq/wreq.py index 834dc931..109096c8 100644 --- a/python/wreq/wreq.py +++ b/python/wreq/wreq.py @@ -12,13 +12,19 @@ Sequence, Mapping, Tuple, + TypeAlias, TypedDict, TypeVar, Unpack, final, + overload, + SupportsIndex, + Iterator, ) from collections.abc import Coroutine +from typing_extensions import Buffer, deprecated + from . import redirect from . import emulation from .cookie import * @@ -32,6 +38,160 @@ from .runtime import Runtime from .tls import * +_BytesLike: TypeAlias = "bytes | bytearray | memoryview | Bytes" + + +@final +class Bytes(Sequence[int], Buffer): + r""" + Immutable binary data returned by wreq without copying. + + It exports a read-only buffer, so `memoryview(data)`, `hashlib`, `bytes.join`, `socket.send` + and `numpy.frombuffer` read it in place. It compares and hashes like `bytes`, so it works as + a `bytes` dictionary key. `data.tobytes()` makes a copy for APIs that require `bytes`, such + as `json.loads` or `isinstance(x, bytes)` checks; `memoryview(data)` suits APIs that accept + only `bytes`, `bytearray` or `memoryview`, such as asyncio transports and `orjson.loads`. + wreq accepts it wherever it accepts `bytes`. + """ + + def __new__(cls, data: Buffer | None = None, /) -> Self: + r""" + Wrap any buffer. `bytes`, a `Bytes` (returned as is) and contiguous memoryviews of either + are shared and keep their whole source alive; other data is copied. Wrap + `view.tobytes()` for a compact copy. + """ + ... + + def __buffer__(self, flags: int, /) -> memoryview: ... + def __len__(self) -> int: ... + @overload + def __getitem__(self, key: SupportsIndex, /) -> int: ... + @overload + def __getitem__(self, key: slice, /) -> "Bytes": ... + def __getitem__(self, key: SupportsIndex | slice, /) -> "int | Bytes": + r""" + An int for an index. A slice shares memory with this data unless it is strided, which + copies. + """ + ... + + def __iter__(self) -> Iterator[int]: ... + def __contains__(self, item: SupportsIndex | Buffer, /) -> bool: # type: ignore[override] + r""" + Whether `item`, a buffer or a byte value, occurs in this data. + """ + ... + + def __eq__(self, other: object, /) -> bool: ... + def __ne__(self, other: object, /) -> bool: ... + def __lt__(self, other: "bytes | Bytes", /) -> bool: ... + def __le__(self, other: "bytes | Bytes", /) -> bool: ... + def __gt__(self, other: "bytes | Bytes", /) -> bool: ... + def __ge__(self, other: "bytes | Bytes", /) -> bool: ... + def __hash__(self) -> int: ... + def __bytes__(self) -> bytes: ... + def __add__(self, other: Buffer, /) -> "Bytes": + r""" + Concatenate with any buffer into a new `Bytes`. + """ + ... + + def __copy__(self) -> Self: ... + def __deepcopy__(self, memo: Any, /) -> Self: ... + def decode(self, encoding: str = "utf-8", errors: str = "strict") -> str: + r""" + Decode into `str`, like `bytes.decode()`. + """ + ... + + def hex(self, sep: str | bytes | None = None, bytes_per_sep: int = 1) -> str: + r""" + Hexadecimal digits for each byte, like `bytes.hex()`. + """ + ... + + def tobytes(self) -> bytes: + r""" + Copy into `bytes`, like `memoryview.tobytes()`; cheaper than `bytes(data)`. + """ + ... + + def find( + self, + sub: SupportsIndex | Buffer, + start: SupportsIndex | None = None, + end: SupportsIndex | None = None, + /, + ) -> int: + r""" + The lowest index of `sub`, a buffer or a byte value, within `[start:end]`, or `-1`. + """ + ... + + def index( + self, + sub: SupportsIndex | Buffer, + start: SupportsIndex | None = None, + end: SupportsIndex | None = None, + /, + ) -> int: + r""" + Like `find()`, but raise `ValueError` when `sub` is not found. + """ + ... + + def count( + self, + sub: SupportsIndex | Buffer, + start: SupportsIndex | None = None, + end: SupportsIndex | None = None, + /, + ) -> int: + r""" + The number of non-overlapping occurrences of `sub` within `[start:end]`. + """ + ... + + def startswith( + self, + prefix: Buffer | tuple[Buffer, ...], + start: SupportsIndex | None = None, + end: SupportsIndex | None = None, + /, + ) -> bool: + r""" + Whether `[start:end]` starts with `prefix` or with any prefix in a tuple. + """ + ... + + def endswith( + self, + suffix: Buffer | tuple[Buffer, ...], + start: SupportsIndex | None = None, + end: SupportsIndex | None = None, + /, + ) -> bool: + r""" + Whether `[start:end]` ends with `suffix` or with any suffix in a tuple. + """ + ... + + @deprecated("Bytes holds no exported view; drop the reference instead") + def release(self) -> None: + r""" + Does nothing and warns; kept for code written against `memoryview`. + """ + ... + + @deprecated("Bytes is not a context manager; use `with memoryview(data) as view:`") + def __enter__(self) -> Self: + r""" + Returns this data and warns; kept for code written against `memoryview`. + """ + ... + + def __exit__(self, *args: object) -> None: ... + @final class Method(Enum): @@ -155,6 +315,7 @@ def __init__( | bytes | bytearray | memoryview + | Bytes | Path | Generator[bytes, str, None] | AsyncGenerator[bytes, str] @@ -185,12 +346,13 @@ class Message: r""" A WebSocket message. - Binary fields return read-only memoryviews that retain their backing data. + `data` and `binary` return immutable `Bytes` that retain their backing data; + `ping` and `pong` return `bytes`, since RFC 6455 limits control payloads to 125 bytes. """ - data: memoryview | None + data: Bytes | None r""" - Returns the data of the message as a read-only memoryview. + Returns the data of the message as an immutable `Bytes`. """ text: str | None @@ -198,17 +360,17 @@ class Message: Returns the text content of the message if it is a text message. """ - binary: memoryview | None + binary: Bytes | None r""" Returns the binary data of the message if it is a binary message. """ - ping: memoryview | None + ping: bytes | None r""" Returns the ping data of the message if it is a ping message. """ - pong: memoryview | None + pong: bytes | None r""" Returns the pong data of the message if it is a pong message. """ @@ -224,7 +386,7 @@ class Message: """ @staticmethod - def from_binary(like: bytes | bytearray | memoryview | Any) -> "Message": + def from_binary(like: bytes | bytearray | memoryview | Bytes | Any) -> "Message": r""" Creates a new binary message. @@ -246,7 +408,7 @@ def from_text(like: str | Any) -> "Message": ... @staticmethod - def from_ping(data: bytes | bytearray | memoryview) -> "Message": + def from_ping(data: bytes | bytearray | memoryview | Bytes) -> "Message": r""" Creates a new ping message. @@ -257,7 +419,7 @@ def from_ping(data: bytes | bytearray | memoryview) -> "Message": ... @staticmethod - def from_pong(data: bytes | bytearray | memoryview) -> "Message": + def from_pong(data: bytes | bytearray | memoryview | Bytes) -> "Message": r""" Creates a new pong message. @@ -285,14 +447,14 @@ def __str__(self) -> str: ... class Streamer: r""" A stream response. - An asynchronous iterator yielding read-only memoryviews or HTTP trailers (HeaderMap) from the response stream. + An asynchronous iterator yielding immutable `Bytes` or HTTP trailers (HeaderMap) from the response stream. Used to stream response content and receive HTTP trailers if present. Implemented in the `stream` method of the `Response` class. Can be used in an asynchronous for loop in Python. - When streaming a response, each iteration yields either a memoryview (for body data) or a HeaderMap (for HTTP trailers, if the server sends them). + When streaming a response, each iteration yields either a `Bytes` (for body data) or a HeaderMap (for HTTP trailers, if the server sends them). This allows you to access HTTP/1.1 or HTTP/2 trailers in addition to the main body. - Data views retain their backing data after the stream is closed. + Data frames stay valid after the stream is closed. A stream on a `CURRENT_THREAD` runtime supports only blocking iteration; its async entry points raise `RuntimeError`. @@ -308,10 +470,10 @@ async def main(): async with wreq.get("https://example.com/stream-with-trailers") as resp: async with resp.stream() as streamer: async for chunk in streamer: - if isinstance(chunk, memoryview): - sys.stdout.buffer.write(chunk) - elif isinstance(chunk, HeaderMap): + if isinstance(chunk, HeaderMap): print("Trailers: ", chunk) + else: + sys.stdout.buffer.write(chunk) await asyncio.sleep(0.1) if __name__ == "__main__": @@ -321,24 +483,24 @@ async def main(): def __iter__(self) -> "Streamer": ... - def __next__(self) -> memoryview | HeaderMap: ... + def __next__(self) -> Bytes | HeaderMap: ... def __enter__(self) -> Self: ... def __exit__(self, _exc_type: Any, _exc_value: Any, _traceback: Any) -> None: r""" - Release the body and end any pending read; returned views stay valid. + Release the body and end any pending read; returned data stays valid. """ def __aiter__(self) -> "Streamer": ... - async def __anext__(self) -> memoryview | HeaderMap: ... + async def __anext__(self) -> Bytes | HeaderMap: ... async def __aenter__(self) -> Self: ... async def __aexit__(self, _exc_type: Any, _exc_value: Any, _traceback: Any) -> None: r""" - Release the body and end any pending read; returned views stay valid. + Release the body and end any pending read; returned data stays valid. """ @@ -426,7 +588,7 @@ def raise_for_status(self) -> None: def stream(self) -> Streamer: r""" - Stream the body as read-only memoryviews, with HeaderMap frames for trailers. + Stream the body as immutable `Bytes`, with HeaderMap frames for trailers. """ ... @@ -441,11 +603,12 @@ async def json(self) -> Any: Get the JSON content of the response. """ - async def bytes(self) -> memoryview: + async def bytes(self) -> Bytes: r""" - Read the body as a read-only memoryview without copying it into Python bytes. - The view remains valid after the response is closed or deleted. - Use bytes(view) or view.tobytes() for a copy; view.release() releases this view. + Read the body as an immutable `Bytes` without copying it. + The data stays valid after the response is closed or deleted. + Use `data.tobytes()` for a `bytes` copy, or `memoryview(data)` for APIs that accept + only `bytes`, `bytearray` or `memoryview`. """ ... @@ -454,7 +617,7 @@ async def close(self) -> None: Discard the retained body and mark its connection as non-reusable. This does not guarantee an immediate socket shutdown or cancel an active read. Cancel and await any body-read task before closing. A body transferred to a - Streamer is managed separately; previously returned memoryviews remain valid. + Streamer is managed separately; previously returned `Bytes` remain valid. `async with` instead releases the body and keeps a fully read connection reusable. """ @@ -983,6 +1146,7 @@ class Request(TypedDict): | bytes | bytearray | memoryview + | Bytes | Sequence[Tuple[str, str]] | Tuple[str, str | int | float | bool] | Mapping[str, str | int | float | bool] diff --git a/src/buffer.rs b/src/buffer.rs index ec4b7ebb..ea8eae33 100644 --- a/src/buffer.rs +++ b/src/buffer.rs @@ -15,42 +15,92 @@ // specific language governing permissions and limitations // under the License. -use std::{ops::Range, os::raw::c_int}; +use std::{ + ffi::CString, + ops::{Deref, Range}, + os::raw::c_int, + sync::atomic::{AtomicIsize, AtomicUsize, Ordering}, +}; use bytes::{Buf, Bytes}; +use memchr::memmem; use pyo3::{ - PyTypeCheck, PyTypeInfo, + IntoPyObjectExt, PyTypeCheck, PyTypeInfo, buffer::PyUntypedBuffer, - exceptions::{PyOverflowError, PyTypeError}, + exceptions::{ + PyDeprecationWarning, PyIndexError, PyMemoryError, PyOverflowError, PyTypeError, + PyValueError, + }, ffi, intern, prelude::*, pybacked::PyBackedBytes, - types::{PyByteArray, PyBytes, PyMemoryView}, + pyclass::CompareOp, + sync::PyOnceLock, + types::{ + PyBool, PyByteArray, PyBytes, PyInt, PyMemoryView, PySlice, PyString, PyTuple, PyType, + slice::PySliceIndices, + }, }; -use wreq::header::{HeaderCaseName, HeaderName, HeaderValue}; -/// Bytes shared with Python in both directions: extracted from `bytes`, `bytearray` or -/// `memoryview` input and returned as a read-only memoryview. +/// Bytes shared with Python in both directions: extracted from `bytes`, `bytearray`, +/// `memoryview` or `wreq.Bytes` input and returned as an immutable `wreq.Bytes`. /// -/// Input is shared only when an exact `bytes` or one of our own memoryviews owns it. Mutable -/// exporters and subclasses are copied, so a `Bytes` never aliases writable memory or hides a -/// reference cycle from the GC. +/// Input is shared only when an exact `bytes`, a `wreq.Bytes` or a memoryview of either owns +/// it. Mutable exporters and subclasses are copied, so a `Bytes` never aliases writable memory +/// or hides a reference cycle from the GC. #[derive(Clone)] pub struct PyBuffer(pub Bytes); -/// The exporter behind each memoryview; views keep it, and so its bytes, alive. -#[pyclass(frozen)] -struct BufferView(Bytes); +/// Immutable binary data shared without copying. It exports a read-only buffer and compares +/// and hashes like `bytes`; `bytes(data)` makes a copy. +// Its owners are exact `bytes` or Rust data, so it cannot hide a reference cycle, and it +// allows no subclasses, so an exact type test finds every instance. +#[pyclass(name = "Bytes", module = "wreq", frozen, sequence, weakref)] +pub struct SharedBytes { + bytes: Bytes, + /// `hash(bytes(self))` once computed, otherwise [`UNHASHED`]. + hash: AtomicIsize, +} + +/// Iterates the ints of a `wreq.Bytes`; threads sharing it each take distinct bytes. +#[pyclass(name = "BytesIterator", module = "wreq", frozen)] +struct BytesIter { + bytes: Bytes, + next: AtomicUsize, +} + +/// A `start` or `end` argument. Ints beyond `isize` clamp, as CPython clamps slice indices. +#[derive(Clone, Copy)] +struct SliceIndex(isize); + +/// Bytes-like data read in place, or extracted when it cannot be. +enum Operand<'a> { + Borrowed(&'a [u8]), + Owned(Bytes), +} + +/// What `find`, `count` and `in` look for: a subsequence or a single byte. +enum Needle<'a> { + Byte(u8), + Seq(Operand<'a>), +} + +/// Python hashes are never `-1`, which marks an uncomputed hash. +const UNHASHED: isize = -1; // ===== impl PyBuffer ===== impl PyBuffer { - /// Extracts `bytes`, `bytearray` or `memoryview` data in one pass over their types, or - /// returns `None` for any other type without building an error, so callers can fall back. + /// Extracts `bytes`, `bytearray`, `memoryview` or `wreq.Bytes` data in one pass over their + /// types, or returns `None` for any other type without building an error, so callers can + /// fall back. pub fn extract_bytes_like(ob: &Bound) -> Option> { let bytes = if let Some(bytes) = as_exact::(ob) { let owner = PyBackedBytes::from(bytes.clone()); share(0..owner.len(), owner) + } else if let Some(shared) = as_exact::(ob) { + // A counted clone, without a round trip through the buffer protocol. + shared.get().bytes.clone() } else if let Some(view) = as_exact::(ob) { return Some(view_bytes(view).map(Self)); } else if let Some(array) = as_instance::(ob) { @@ -73,7 +123,7 @@ impl FromPyObject<'_, '_> for PyBuffer { // Other exporters, such as numpy numbers or `array('d')`, count as bytes only in a // memoryview, so `body=` and `from_binary` keep encoding them as JSON. None => Err(PyTypeError::new_err(format!( - "'{}' object is not an instance of 'bytes | bytearray | memoryview'", + "'{}' object is not an instance of 'bytes | bytearray | memoryview | Bytes'", ob.get_type().qualname()? ))), } @@ -81,14 +131,13 @@ impl FromPyObject<'_, '_> for PyBuffer { } impl<'a> IntoPyObject<'a> for PyBuffer { - type Target = PyMemoryView; + type Target = SharedBytes; type Output = Bound<'a, Self::Target>; type Error = PyErr; #[inline(always)] fn into_pyobject(self, py: Python<'a>) -> Result { - let buffer = BufferView(self.0).into_pyobject(py)?; - PyMemoryView::from(buffer.as_any()) + Bound::new(py, SharedBytes::from(self.0)) } } @@ -113,30 +162,90 @@ impl From for PyBuffer { } } -impl From for PyBuffer { +impl AsRef<[u8]> for PyBuffer { #[inline] - fn from(value: HeaderName) -> Self { - Self::from(Bytes::from_owner(value)) + fn as_ref(&self) -> &[u8] { + &self.0 } } -impl From for PyBuffer { - fn from(value: HeaderCaseName) -> Self { - Self::from(Bytes::from_owner(value)) - } -} +// ===== impl SharedBytes ===== -impl From for PyBuffer { +impl From for SharedBytes { #[inline] - fn from(value: HeaderValue) -> Self { - Self::from(Bytes::from_owner(value)) + fn from(bytes: Bytes) -> Self { + Self { + bytes, + hash: AtomicIsize::new(UNHASHED), + } } } -// ===== impl BufferView ===== +impl SharedBytes { + /// The first index of `sub` within `[start:end]`. + fn position( + &self, + sub: &Bound, + start: Option, + end: Option, + ) -> PyResult> { + // `sub` is checked even when the window is out of range, as `bytes` checks it. + let needle = needle(sub, false)?; + Ok(window(&self.bytes, start, end) + .and_then(|(offset, data)| Some(offset.saturating_add(needle.find(data)?)))) + } + + /// Whether `test` holds within `[start:end]` for one bytes-like `affix` or any item of a + /// tuple of them. + fn test_affix( + &self, + method: &str, + affix: &Bound, + start: Option, + end: Option, + test: fn(&[u8], &[u8]) -> bool, + ) -> PyResult { + // A window out of range matches nothing, though every affix is still checked. + let data = window(&self.bytes, start, end).map(|(_, data)| data); + let matches = |affix: &[u8]| data.is_some_and(|data| test(data, affix)); + let Ok(affixes) = affix.cast::() else { + return match operand(affix) { + Some(affix) => Ok(matches(&affix?)), + None => Err(PyTypeError::new_err(format!( + "{method} first arg must be bytes or a tuple of bytes, not {}", + affix.get_type().qualname()? + ))), + }; + }; + for affix in affixes { + if matches(&operand(&affix).ok_or_else(|| not_bytes_like(&affix))??) { + return Ok(true); + } + } + Ok(false) + } +} #[pymethods] -impl BufferView { +impl SharedBytes { + /// Shares an exact `bytes`, a `Bytes` or a contiguous view of either, keeping its whole + /// source alive, and copies any other buffer; a `Bytes` comes back as the same object. + #[new] + #[pyo3(signature = (data = None, /))] + fn new<'py>(py: Python<'py>, data: Option<&Bound<'py, PyAny>>) -> PyResult> { + let Some(data) = data else { + return Bound::new(py, Self::from(Bytes::new())); + }; + if let Some(shared) = as_exact::(data) { + return Ok(shared.clone()); + } + let bytes = match PyBuffer::extract_bytes_like(data) { + Some(bytes) => bytes?.0, + None => buffer_like(data).ok_or_else(|| not_bytes_like(data))??, + }; + Bound::new(py, Self::from(bytes)) + } + /// # Safety /// `view` must be a writable `Py_buffer` supplied by the Python buffer protocol. #[allow(unsafe_code)] @@ -145,9 +254,8 @@ impl BufferView { view: *mut ffi::Py_buffer, flags: c_int, ) -> PyResult<()> { - let bytes = &slf.get().0; - let len = ffi::Py_ssize_t::try_from(bytes.len()) - .map_err(|_| PyOverflowError::new_err("buffer length exceeds Python's maximum size"))?; + let bytes = &slf.get().bytes; + let len = py_len(bytes)?; // SAFETY: PyO3 supplies a valid output buffer. FillInfo retains the exporter, // which owns immutable Bytes for the lifetime of this read-only buffer. let ret = unsafe { @@ -165,14 +273,413 @@ impl BufferView { } Ok(()) } + + fn __len__(&self) -> usize { + self.bytes.len() + } + + /// An int for an index; a shared `Bytes` for a contiguous slice, a copy for a strided one. + fn __getitem__<'py>( + slf: &Bound<'py, Self>, + key: &Bound<'py, PyAny>, + ) -> PyResult> { + let py = slf.py(); + let bytes = &slf.get().bytes; + let Ok(slice) = key.cast::() else { + let Some(index) = as_index(key)? else { + return Err(PyTypeError::new_err(format!( + "byte indices must be integers or slices, not {}", + key.get_type().qualname()? + ))); + }; + let index = index.extract::().map_err(|err| { + if err.is_instance_of::(py) { + PyIndexError::new_err("cannot fit 'int' into an index-sized integer") + } else { + err + } + })?; + let index = if index < 0 { + bytes.len().checked_sub(index.unsigned_abs()) + } else { + Some(index.unsigned_abs()) + }; + return index + .and_then(|index| bytes.get(index)) + .ok_or_else(|| PyIndexError::new_err("index out of range"))? + .into_bound_py_any(py); + }; + let PySliceIndices { + start, + step, + slicelength, + .. + } = slice.indices(py_len(bytes)?)?; + // `start` is only negative for an empty slice with a negative step. + let start = usize::try_from(start).unwrap_or_default(); + let sliced = if step == 1 { + let end = start.saturating_add(slicelength).min(bytes.len()); + bytes.slice(start.min(end)..end) + } else { + let mut picked = Vec::new(); + picked + .try_reserve_exact(slicelength) + .map_err(|_| PyMemoryError::new_err(()))?; + let step_by = step.unsigned_abs().max(1); + if step > 0 { + let tail = bytes.get(start..).unwrap_or_default(); + picked.extend(tail.iter().step_by(step_by).take(slicelength)); + } else { + let head = bytes.get(..=start).unwrap_or_default(); + if step == -1 { + // Reversing a copied run beats stepping byte by byte. + let run = head.len().saturating_sub(slicelength); + picked.extend_from_slice(head.get(run..).unwrap_or_default()); + picked.reverse(); + } else { + picked.extend(head.iter().rev().step_by(step_by).take(slicelength)); + } + } + Bytes::from(picked) + }; + Bound::new(py, Self::from(sliced)).map(Bound::into_any) + } + + fn __iter__(&self) -> BytesIter { + BytesIter { + bytes: self.bytes.clone(), + next: AtomicUsize::new(0), + } + } + + fn __contains__(&self, item: &Bound) -> PyResult { + Ok(needle(item, true)?.find(&self.bytes).is_some()) + } + + /// The lowest index of `sub` (bytes-like or a byte value) within `[start:end]`, or `-1`. + #[pyo3(signature = (sub, start = None, end = None, /))] + fn find( + &self, + sub: &Bound, + start: Option, + end: Option, + ) -> PyResult { + Ok(self + .position(sub, start, end)? + .and_then(|index| isize::try_from(index).ok()) + .unwrap_or(-1)) + } + + /// Like `find`, but raises `ValueError` when `sub` is not found. + #[pyo3(signature = (sub, start = None, end = None, /))] + fn index( + &self, + sub: &Bound, + start: Option, + end: Option, + ) -> PyResult { + self.position(sub, start, end)? + .ok_or_else(|| PyValueError::new_err("subsection not found")) + } + + /// The number of non-overlapping occurrences of `sub` within `[start:end]`. + #[pyo3(signature = (sub, start = None, end = None, /))] + fn count( + &self, + sub: &Bound, + start: Option, + end: Option, + ) -> PyResult { + let needle = needle(sub, false)?; + Ok(window(&self.bytes, start, end).map_or(0, |(_, data)| needle.count(data))) + } + + /// Compares with `bytes` or `Bytes`; other types reflect, so `bytearray` and `memoryview` + /// compare through their own methods over this buffer. + fn __richcmp__(&self, other: &Bound, op: CompareOp) -> Py { + let py = other.py(); + let other = if let Some(other) = as_exact::(other) { + &other.get().bytes[..] + } else if let Some(other) = as_instance::(other) { + other.as_bytes() + } else { + return py.NotImplemented(); + }; + let ours = &self.bytes[..]; + let result = match op { + CompareOp::Eq => ours == other, + CompareOp::Ne => ours != other, + _ => op.matches(ours.cmp(other)), + }; + PyBool::new(py, result).to_owned().into_any().unbind() + } + + /// Equals `hash(bytes(self))`, so `Bytes` and equal `bytes` are interchangeable keys. + #[allow(unsafe_code)] + fn __hash__(&self, py: Python) -> PyResult { + let hash = self.hash.load(Ordering::Relaxed); + if hash != UNHASHED { + return Ok(hash); + } + let len = py_len(&self.bytes)?; + // SAFETY: the pointer is valid for `len` immutable bytes while `self` is borrowed. Under + // the limited API the shim hashes a temporary `bytes` copy; otherwise it reads in place. + let hash = unsafe { ffi::compat::Py_HashBuffer(self.bytes.as_ptr().cast(), len) }; + if hash == UNHASHED { + return Err(PyErr::fetch(py)); + } + // Racing threads store the same value. + self.hash.store(hash, Ordering::Relaxed); + Ok(hash) + } + + fn __bytes__<'py>(&self, py: Python<'py>) -> PyResult> { + to_bytes(py, &self.bytes) + } + + fn __repr__<'py>(&self, py: Python<'py>) -> PyResult> { + // The copy drops first, and `str.format` raises `MemoryError` where `format!` aborts. + let repr = to_bytes(py, &self.bytes)?.repr()?; + intern!(py, "Bytes({})").call_method1(intern!(py, "format"), (repr,)) + } + + /// Pickles as a `bytes` copy, which unpickling shares again. + fn __reduce__<'py>( + slf: &Bound<'py, Self>, + ) -> PyResult<(Bound<'py, PyType>, (Bound<'py, PyBytes>,))> { + Ok((slf.get_type(), (to_bytes(slf.py(), &slf.get().bytes)?,))) + } + + /// Concatenates with any buffer into a new `Bytes`. + fn __add__<'py>( + slf: &Bound<'py, Self>, + other: &Bound<'py, PyAny>, + ) -> PyResult> { + let py = slf.py(); + let Some(tail) = operand(other) else { + return Ok(py.NotImplemented().into_bound(py)); + }; + let (head, tail) = (&slf.get().bytes, tail?); + let joined = if tail.is_empty() { + head.clone() + } else { + let mut joined = Vec::new(); + head.len() + .checked_add(tail.len()) + .and_then(|len| joined.try_reserve_exact(len).ok()) + .ok_or_else(|| PyMemoryError::new_err(()))?; + joined.extend_from_slice(head); + joined.extend_from_slice(&tail); + Bytes::from(joined) + }; + Bound::new(py, Self::from(joined)).map(Bound::into_any) + } + + #[pyo3(signature = (encoding = "utf-8", errors = "strict"))] + fn decode<'py>( + slf: &Bound<'py, Self>, + encoding: &str, + errors: &str, + ) -> PyResult> { + if errors == "strict" && matches!(encoding, "utf-8" | "utf8" | "UTF-8" | "UTF8") { + // CPython validates UTF-8 once while building the string. + return PyString::from_bytes(slf.py(), &slf.get().bytes); + } + // Other codecs decode this read-only buffer in place. + let encoding = CString::new(encoding)?; + let errors = CString::new(errors)?; + PyString::from_encoded_object(slf.as_any(), Some(&encoding), Some(&errors)) + } + + #[pyo3(signature = (sep = None, bytes_per_sep = 1))] + fn hex<'py>( + slf: &Bound<'py, Self>, + sep: Option<&Bound<'py, PyAny>>, + bytes_per_sep: isize, + ) -> PyResult> { + // `memoryview.hex` reads this buffer in place. + let view = PyMemoryView::from(slf.as_any())?; + let hex = intern!(slf.py(), "hex"); + match sep { + Some(sep) => view.call_method1(hex, (sep, bytes_per_sep)), + None => view.call_method0(hex), + } + } + + /// A `bytes` copy, as `memoryview.tobytes()` returns; cheaper than `bytes(data)`. + fn tobytes<'py>(&self, py: Python<'py>) -> PyResult> { + to_bytes(py, &self.bytes) + } + + #[pyo3(signature = (prefix, start = None, end = None, /))] + fn startswith( + &self, + prefix: &Bound, + start: Option, + end: Option, + ) -> PyResult { + self.test_affix("startswith", prefix, start, end, <[u8]>::starts_with) + } + + #[pyo3(signature = (suffix, start = None, end = None, /))] + fn endswith( + &self, + suffix: &Bound, + start: Option, + end: Option, + ) -> PyResult { + self.test_affix("endswith", suffix, start, end, <[u8]>::ends_with) + } + + /// Immutable, so a copy is the same object. + fn __copy__<'py>(slf: &Bound<'py, Self>) -> Bound<'py, Self> { + slf.clone() + } + + fn __deepcopy__<'py>(slf: &Bound<'py, Self>, _memo: &Bound<'py, PyAny>) -> Bound<'py, Self> { + slf.clone() + } + + /// Kept for code written against `memoryview`; the data is freed when the last reference + /// goes away. + fn release(&self, py: Python) -> PyResult<()> { + PyErr::warn( + py, + &py.get_type::(), + c"Bytes.release() does nothing; drop the reference instead", + 1, + ) + } + + fn __enter__<'py>(slf: &Bound<'py, Self>) -> PyResult> { + let py = slf.py(); + PyErr::warn( + py, + &py.get_type::(), + c"Bytes is not a context manager; use `with memoryview(data) as view:`", + 1, + )?; + Ok(slf.clone()) + } + + #[pyo3(signature = (*_args))] + fn __exit__(&self, _args: &Bound) {} +} + +// ===== impl BytesIter ===== + +#[pymethods] +impl BytesIter { + fn __iter__(slf: PyRef) -> PyRef { + slf + } + + fn __next__(&self) -> Option { + let len = self.bytes.len(); + self.next + .try_update(Ordering::Relaxed, Ordering::Relaxed, |next| { + (next < len).then_some(next + 1) + }) + .ok() + .and_then(|next| self.bytes.get(next).copied()) + } + + fn __length_hint__(&self) -> usize { + self.bytes + .len() + .saturating_sub(self.next.load(Ordering::Relaxed)) + } +} + +// ===== impl SliceIndex ===== + +impl FromPyObject<'_, '_> for SliceIndex { + type Error = PyErr; + + fn extract(ob: Borrowed) -> PyResult { + let Some(index) = as_index(&ob)? else { + return Err(PyTypeError::new_err( + "slice indices must be integers or None or have an __index__ method", + )); + }; + match index.extract::() { + Ok(index) => Ok(Self(index)), + Err(err) if err.is_instance_of::(ob.py()) => { + Ok(Self(if index.lt(0)? { isize::MIN } else { isize::MAX })) + } + Err(err) => Err(err), + } + } +} + +// ===== impl Operand ===== + +impl Deref for Operand<'_> { + type Target = [u8]; + + #[inline] + fn deref(&self) -> &[u8] { + match self { + Operand::Borrowed(data) => data, + Operand::Owned(bytes) => bytes, + } + } +} + +// ===== impl Needle ===== + +impl<'a> From> for Needle<'a> { + /// A one-byte subsequence searches as that byte, without building a substring finder. + fn from(seq: Operand<'a>) -> Self { + if let [byte] = *seq { + return Needle::Byte(byte); + } + Needle::Seq(seq) + } +} + +impl Needle<'_> { + fn find(&self, haystack: &[u8]) -> Option { + match self { + Needle::Byte(byte) => memchr::memchr(*byte, haystack), + Needle::Seq(seq) => memmem::find(haystack, seq), + } + } + + fn count(&self, haystack: &[u8]) -> usize { + match self { + Needle::Byte(byte) => haystack.iter().filter(|&item| item == byte).count(), + Needle::Seq(seq) => memmem::find_iter(haystack, &**seq).count(), + } + } +} + +/// The length of `data` as a `Py_ssize_t`. +#[inline] +fn py_len(data: &[u8]) -> PyResult { + ffi::Py_ssize_t::try_from(data.len()) + .map_err(|_| PyOverflowError::new_err("buffer length exceeds Python's maximum size")) +} + +/// A `bytes` copy of `data` that raises `MemoryError` where `PyBytes::new` would panic. +#[allow(unsafe_code)] +fn to_bytes<'py>(py: Python<'py>, data: &[u8]) -> PyResult> { + let len = py_len(data)?; + // SAFETY: `data` is valid for `len` bytes, which CPython copies; NULL comes with an error. + let copy = unsafe { + Bound::from_owned_ptr_or_err( + py, + ffi::PyBytes_FromStringAndSize(data.as_ptr().cast(), len), + )? + }; + Ok(copy.cast_into_exact()?) } -/// Shares a view of an exact `bytes` or of our own memoryview, and copies any other view. +/// Shares a view of an exact `bytes` or of a `wreq.Bytes`, and copies any other view. fn view_bytes(view: &Bound) -> PyResult { let obj = view.getattr(intern!(view.py(), "obj"))?; - // BufferView allows no subclasses, so an exact test covers it. - if let Some(exporter) = as_exact::(&obj) { - let bytes = &exporter.get().0; + if let Some(exporter) = as_exact::(&obj) { + let bytes = &exporter.get().bytes; if let Some(range) = view_range(view, bytes) { // A counted clone of the exporter's Bytes, whatever its vtable. return Ok(bytes.slice(range)); @@ -223,6 +730,119 @@ fn view_range(view: &Bound, data: &[u8]) -> Option> { (end <= data.len()).then_some(start..end) } +/// `ob` as `bytes`, `bytearray`, `memoryview` or `Bytes` data, read in place where it can be, +/// or `None` for any other type. +fn bytes_like<'a>(ob: &'a Bound) -> Option>> { + if let Some(shared) = as_exact::(ob) { + return Some(Ok(Operand::Borrowed(&shared.get().bytes))); + } + if let Some(bytes) = as_instance::(ob) { + return Some(Ok(Operand::Borrowed(bytes.as_bytes()))); + } + PyBuffer::extract_bytes_like(ob).map(|bytes| bytes.map(|bytes| Operand::Owned(bytes.0))) +} + +/// A raw copy of any other buffer exporter, such as an `array` or numpy data, or `None` for an +/// object without a buffer. +fn buffer_like(ob: &Bound) -> Option> { + match PyMemoryView::from(ob) { + Ok(view) => Some(view_bytes(&view)), + Err(err) if err.is_instance_of::(ob.py()) => None, + Err(err) => Some(Err(err)), + } +} + +/// `ob` as any buffer, as `bytes` methods take their operands. +fn operand<'a>(ob: &'a Bound) -> Option>> { + bytes_like(ob).or_else(|| buffer_like(ob).map(|bytes| bytes.map(Operand::Owned))) +} + +/// The `TypeError` for an operand that exports no buffer. +fn not_bytes_like(ob: &Bound) -> PyErr { + match ob.get_type().qualname() { + Ok(name) => PyTypeError::new_err(format!("a bytes-like object is required, not '{name}'")), + Err(err) => err, + } +} + +/// `sub` as a buffer or a byte value given as an int or `__index__` object. `bytes.__contains__` +/// takes an exporter with `__index__`, such as a numpy int, as a byte (`prefer_byte`); the +/// other methods take its buffer. +fn needle<'a>(sub: &'a Bound, prefer_byte: bool) -> PyResult> { + if let Some(int) = as_instance::(sub) { + return byte(int).map(Needle::Byte); + } + if let Some(seq) = bytes_like(sub) { + return seq.map(Needle::from); + } + if prefer_byte && let Some(int) = as_index(sub)? { + return byte(&int).map(Needle::Byte); + } + if let Some(seq) = buffer_like(sub) { + return seq.map(|bytes| Needle::from(Operand::Owned(bytes))); + } + if prefer_byte { + return Err(not_bytes_like(sub)); + } + match as_index(sub)? { + Some(int) => byte(&int).map(Needle::Byte), + None => Err(PyTypeError::new_err(format!( + "argument should be integer or bytes-like object, not '{}'", + sub.get_type().qualname()? + ))), + } +} + +/// The byte `int` stands for, with the error `bytes` raises outside `range(0, 256)`. +fn byte(int: &Bound) -> PyResult { + int.extract::().map_err(|err| { + if err.is_instance_of::(int.py()) { + PyValueError::new_err("byte must be in range(0, 256)") + } else { + err + } + }) +} + +/// `ob` as an int, through `operator.index` unless it is one, or `None` when its type has no +/// `__index__`. Errors raised by `__index__` propagate. +fn as_index<'py>(ob: &Bound<'py, PyAny>) -> PyResult>> { + static INDEX: PyOnceLock> = PyOnceLock::new(); + if let Some(int) = as_instance::(ob) { + return Ok(Some(int.clone())); + } + let py = ob.py(); + if !ob.get_type().hasattr(intern!(py, "__index__"))? { + return Ok(None); + } + let int = INDEX.import(py, "operator", "index")?.call1((ob,))?; + Ok(Some(int.cast_into::()?)) +} + +/// The `[start:end]` window of `data` and its offset, clamped as `bytes` methods clamp them, or +/// `None` when `start` lies past the end or after `end`. +fn window( + data: &[u8], + start: Option, + end: Option, +) -> Option<(usize, &[u8])> { + let len = data.len(); + let clamp = |SliceIndex(index): SliceIndex| { + if index < 0 { + len.saturating_sub(index.unsigned_abs()) + } else { + index.unsigned_abs().min(len) + } + }; + let start = start.unwrap_or(SliceIndex(0)); + if start.0 > 0 && start.0.unsigned_abs() > len { + return None; + } + let start = clamp(start); + let end = end.map_or(len, clamp); + data.get(start..end).map(|data| (start, data)) +} + /// `ob` as exactly a `T`; other types return `None` without building a cast error. #[inline] fn as_exact<'a, 'py, T: PyTypeInfo>(ob: &'a Bound<'py, PyAny>) -> Option<&'a Bound<'py, T>> { @@ -246,10 +866,7 @@ fn as_instance<'a, 'py, T: PyTypeCheck>(ob: &'a Bound<'py, PyAny>) -> Option<&'a #[cfg(test)] mod tests { - use pyo3::{ - buffer::PyBuffer as PythonBuffer, - types::{PySlice, PyString}, - }; + use pyo3::buffer::PyBuffer as PythonBuffer; use super::*; use crate::extractor::Text; @@ -260,28 +877,31 @@ mod tests { Python::attach(|py| { let bytes = Bytes::from(vec![0, 1, 255]); let ptr = bytes.as_ptr(); - let view = PyBuffer::from(bytes).into_pyobject(py).unwrap(); - let buffer = PythonBuffer::::get(view.as_any()).unwrap(); + let shared = PyBuffer::from(bytes).into_pyobject(py).unwrap(); + let buffer = PythonBuffer::::get(shared.as_any()).unwrap(); assert_eq!(buffer.buf_ptr().cast_const().cast::(), ptr); assert!(buffer.readonly()); assert_eq!(buffer.to_vec(py).unwrap(), [0, 1, 255]); - // Our views come back shared, sliced or not; a strided one is copied. - let input = view.extract::().unwrap(); + // Our Bytes and their views come back shared, sliced or not; a strided one is + // copied. + let input = shared.extract::().unwrap(); assert_eq!(input.0.as_ptr(), ptr); - let tail = view.get_item(PySlice::new(py, 1, 3, 1)).unwrap(); + let view = PyMemoryView::from(shared.as_any()).unwrap(); + assert_eq!(view.extract::().unwrap().0.as_ptr(), ptr); + let tail = shared.get_item(PySlice::new(py, 1, 3, 1)).unwrap(); let input = tail.extract::().unwrap(); assert_eq!(input.0.as_ptr(), ptr.wrapping_add(1)); assert_eq!(input.0[..], [1, 255]); - let strided = view.get_item(PySlice::new(py, 0, 3, 2)).unwrap(); + let strided = shared.get_item(PySlice::new(py, 0, 3, 2)).unwrap(); assert_eq!(strided.extract::().unwrap().0[..], [0, 255]); let binary = PyBytes::new(py, b"builtin bytes"); let input = binary.extract::().unwrap(); assert_eq!(input.0.as_ptr(), binary.as_bytes().as_ptr()); - let view = PyBuffer::from(input.0).into_pyobject(py).unwrap(); - let buffer = PythonBuffer::::get(view.as_any()).unwrap(); + let shared = PyBuffer::from(input.0).into_pyobject(py).unwrap(); + let buffer = PythonBuffer::::get(shared.as_any()).unwrap(); assert_eq!( buffer.buf_ptr().cast_const().cast::(), binary.as_bytes().as_ptr() diff --git a/src/client/body/stream.rs b/src/client/body/stream.rs index 230681c0..060fc58f 100644 --- a/src/client/body/stream.rs +++ b/src/client/body/stream.rs @@ -29,7 +29,8 @@ use crate::{buffer::PyBuffer, extractor::Text}; type Item = PyResult; -/// A request body chunk: `bytes`, `bytearray` or `memoryview` data, or a `str` sent as UTF-8. +/// A request body chunk: `bytes`, `bytearray`, `memoryview` or `wreq.Bytes` data, or a `str` sent +/// as UTF-8. pub enum PyBytesLike { Bytes(PyBuffer), String(Text), diff --git a/src/client/resp/http.rs b/src/client/resp/http.rs index 1796f8e5..173f3e46 100644 --- a/src/client/resp/http.rs +++ b/src/client/resp/http.rs @@ -347,7 +347,7 @@ impl Response { .map_err(Into::into) } - /// Stream read-only memoryviews and any trailing headers from the body. Only an unread + /// Stream immutable `Bytes` and any trailing headers from the body. Only an unread /// body can be streamed; cached bytes stay readable. pub fn stream(&self) -> PyResult { let mut slot = self.slot(); @@ -382,7 +382,7 @@ impl Response { Self::read(slf, "Response.json", 8 * 1024, ResponseExt::json::) } - /// Read the body as a read-only memoryview, retaining its data after the response closes. + /// Read the body as an immutable `Bytes`, retaining its data after the response closes. pub fn bytes(slf: Bound<'_, Self>) -> PyResult> { let py = slf.py(); let slf = slf.unbind(); @@ -404,7 +404,7 @@ impl Response { /// Discard the retained body and mark its connection as non-reusable. /// This does not guarantee an immediate socket shutdown or cancel an active read. /// Cancel and await any body-read task before closing. A body transferred to a - /// Streamer is managed separately; previously returned memoryviews remain valid. + /// Streamer is managed separately; previously returned `Bytes` remain valid. /// `async with` instead releases the body and keeps a fully read connection reusable. pub fn close(slf: Bound<'_, Self>) -> PyResult> { let py = slf.py(); @@ -565,7 +565,7 @@ impl BlockingResponse { self.0.raise_for_status() } - /// Stream read-only memoryviews and any trailing headers from the body. + /// Stream immutable `Bytes` and any trailing headers from the body. pub fn stream(&self) -> PyResult { self.0.stream() } @@ -581,7 +581,7 @@ impl BlockingResponse { self.read(py, ResponseExt::json::) } - /// Read the body as a read-only memoryview, retaining its data after the response closes. + /// Read the body as an immutable `Bytes`, retaining its data after the response closes. pub fn bytes(&self, py: Python) -> PyResult { Runtime::refuse_nested()?; let response = &self.0; @@ -600,7 +600,7 @@ impl BlockingResponse { /// Discard the retained body and mark its connection as non-reusable. /// This does not guarantee an immediate socket shutdown or interrupt an active read. /// Do not close concurrently with a body read. A body transferred to a Streamer - /// is managed separately; previously returned memoryviews remain valid. + /// is managed separately; previously returned `Bytes` remain valid. /// `with` instead releases the body and keeps a fully read connection reusable. pub fn close(&self) { self.0.discard(); diff --git a/src/client/resp/stream.rs b/src/client/resp/stream.rs index 1b1ca12d..903397e3 100644 --- a/src/client/resp/stream.rs +++ b/src/client/resp/stream.rs @@ -31,14 +31,14 @@ use crate::{ runtime::Runtime, }; -/// A response frame exposed as a read-only memoryview or a header map. +/// A response frame exposed as an immutable `Bytes` or a header map. #[derive(IntoPyObject)] pub enum Frame { Bytes(PyBuffer), Trailers(HeaderMap), } -/// A response stream yielding read-only memoryviews and any trailing headers. +/// A response stream yielding immutable `Bytes` and any trailing headers. /// /// Sync and async iteration share [`Streamer::next`]; [`Iteration`] picks the ready frames /// the caller reads and the error that ends iteration. @@ -296,7 +296,7 @@ impl Streamer { slf } - /// Release the body and end any pending read; returned views stay valid. + /// Release the body and end any pending read; returned data stays valid. fn __exit__<'py>( &self, _exc_type: &Bound<'py, PyAny>, @@ -336,7 +336,7 @@ impl Streamer { coroutine::ready("Streamer.__aenter__", slf) } - /// Release the body and end any pending read; returned views stay valid. + /// Release the body and end any pending read; returned data stays valid. fn __aexit__<'py>( &self, py: Python<'py>, diff --git a/src/client/resp/ws/msg.rs b/src/client/resp/ws/msg.rs index 3a04e299..decfc422 100644 --- a/src/client/resp/ws/msg.rs +++ b/src/client/resp/ws/msg.rs @@ -50,7 +50,7 @@ impl FromPyObject<'_, '_> for BytesLike { #[pymethods] impl Message { - /// Returns the message data as a read-only memoryview. + /// Returns the message data as an immutable `Bytes`. #[getter] pub fn data(&self) -> Option { let bytes = match &self.0 { @@ -73,7 +73,7 @@ impl Message { } } - /// Returns a read-only memoryview if this is a binary message. + /// Returns an immutable `Bytes` if this is a binary message. #[getter] pub fn binary(&self) -> Option { if let message::Message::Binary(data) = &self.0 { @@ -83,21 +83,24 @@ impl Message { } } - /// Returns a read-only memoryview if this is a ping message. + /// Returns the payload as `bytes` if this is a ping message. [RFC 6455 §5.5] limits control + /// payloads to 125 bytes, so a copy is cheaper than a shared buffer. + /// + /// [RFC 6455 §5.5]: https://www.rfc-editor.org/rfc/rfc6455#section-5.5 #[getter] - pub fn ping(&self) -> Option { + pub fn ping(&self) -> Option<&[u8]> { if let message::Message::Ping(data) = &self.0 { - Some(PyBuffer::from(data)) + Some(data) } else { None } } - /// Returns a read-only memoryview if this is a pong message. + /// Returns the payload as `bytes` if this is a pong message. #[getter] - pub fn pong(&self) -> Option { + pub fn pong(&self) -> Option<&[u8]> { if let message::Message::Pong(data) = &self.0 { - Some(PyBuffer::from(data)) + Some(data) } else { None } diff --git a/src/header.rs b/src/header.rs index 3c8678a1..408c01b0 100644 --- a/src/header.rs +++ b/src/header.rs @@ -1,18 +1,18 @@ use pyo3::{ prelude::*, pybacked::PyBackedStr, - types::{PyDict, PyIterator, PyList}, + types::{PyBytes, PyDict, PyIterator, PyList}, }; use wreq::header::{self, HeaderName, HeaderValue}; use crate::{buffer::PyBuffer, error::Error, extractor::Text}; -/// An HTTP header map whose names and values are exposed as read-only memoryviews. +/// An HTTP header map whose names and values are exposed as `bytes`. #[derive(Clone)] #[pyclass(subclass, str)] pub struct HeaderMap(pub header::HeaderMap); -/// An HTTP original header map whose iterator exposes read-only memoryviews. +/// An HTTP original header map whose iterator exposes `bytes`. #[derive(Clone)] #[pyclass(subclass, str)] pub struct OrigHeaderMap(pub header::OrigHeaderMap); @@ -57,28 +57,34 @@ impl HeaderMap { HeaderMap(headers) } - /// Returns a read-only memoryview of the value associated with the key. + /// Returns the value associated with the key as `bytes`. /// /// If there are multiple values associated with the key, then the first one /// is returned. Use `get_all` to get all values associated with a given - /// key. Returns `None` if there are no values associated with the key. + /// key. Returns `default`, or `None`, if there are no values associated with the key. #[pyo3(signature = (key, default=None))] - fn get(&self, key: PyBackedStr, default: Option) -> Option { - self.0 - .get::<&str>(key.as_ref()) - .cloned() - .or_else(|| HeaderValue::from_maybe_shared(default?.0).ok()) - .map(PyBuffer::from) + fn get<'py>( + &self, + py: Python<'py>, + key: PyBackedStr, + default: Option, + ) -> Option> { + // Header values are short, so a `bytes` copy is cheaper than a shared buffer. + if let Some(value) = self.0.get::<&str>(key.as_ref()) { + return Some(PyBytes::new(py, value.as_bytes())); + } + HeaderValue::from_maybe_shared(default?.0) + .ok() + .map(|value| PyBytes::new(py, value.as_bytes())) } - /// Returns a list of read-only memoryviews for the values associated with a key. + /// Returns a list of `bytes` for the values associated with a key. #[pyo3(signature = (key))] - fn get_all(&self, key: PyBackedStr) -> Vec { + fn get_all(&self, key: PyBackedStr) -> Vec<&[u8]> { self.0 .get_all::<&str>(key.as_ref()) .iter() - .cloned() - .map(PyBuffer::from) + .map(HeaderValue::as_bytes) .collect() } @@ -116,14 +122,14 @@ impl HeaderMap { self.0.contains_key::<&str>(key.as_ref()) } - /// Returns a list of read-only memoryviews for all keys. - fn keys(&self) -> Vec { - self.0.keys().cloned().map(PyBuffer::from).collect() + /// Returns a list of `bytes` for all keys. + fn keys(&self) -> Vec<&[u8]> { + self.0.keys().map(|name| name.as_str().as_bytes()).collect() } - /// Returns a list of read-only memoryviews for all values. - fn values(&self) -> Vec { - self.0.values().cloned().map(PyBuffer::from).collect() + /// Returns a list of `bytes` for all values. + fn values(&self) -> Vec<&[u8]> { + self.0.values().map(HeaderValue::as_bytes).collect() } /// Returns the number of headers stored in the map. @@ -156,8 +162,8 @@ impl HeaderMap { #[pymethods] impl HeaderMap { - fn __getitem__(&self, key: PyBackedStr) -> Option { - self.get(key, None) + fn __getitem__<'py>(&self, py: Python<'py>, key: PyBackedStr) -> Option> { + self.get(py, key, None) } fn __setitem__(&mut self, key: PyBackedStr, value: Text) { @@ -180,7 +186,7 @@ impl HeaderMap { let items = self .0 .iter() - .map(|(k, v)| (PyBuffer::from(k.clone()), PyBuffer::from(v.clone()))); + .map(|(k, v)| (k.as_str().as_bytes(), v.as_bytes())); let pylist = PyList::new(py, items)?; PyIterator::from_object(&pylist) } @@ -273,12 +279,10 @@ impl OrigHeaderMap { } fn __iter__<'py>(&self, py: Python<'py>) -> PyResult> { - let items = self.0.iter().map(|(name, orig_name)| { - ( - PyBuffer::from(name.clone()), - PyBuffer::from(orig_name.clone()), - ) - }); + let items = self + .0 + .iter() + .map(|(name, orig_name)| (name.as_str().as_bytes(), orig_name.as_ref())); let pylist = PyList::new(py, items)?; PyIterator::from_object(&pylist) } diff --git a/src/lib.rs b/src/lib.rs index 796ab7d6..4380073d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -22,6 +22,7 @@ mod redirect; mod runtime; mod tls; +use buffer::SharedBytes; use client::{ BlockingClient, Client, SocketAddr, body::multipart::{Multipart, Part}, @@ -319,6 +320,7 @@ mod blocking { fn wreq(py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> { use r#async::{delete, get, head, options, patch, post, put, request, trace, websocket}; + m.add_class::()?; m.add_class::()?; m.add_class::()?; m.add_class::()?; diff --git a/src/tls.rs b/src/tls.rs index 32b01c81..49d944a8 100644 --- a/src/tls.rs +++ b/src/tls.rs @@ -8,7 +8,6 @@ use wreq::tls::compress::CertificateCompressor; use wreq_util::emulate::compress; pub use self::{identity::Identity, keylog::KeyLog, store::CertStore}; -use crate::buffer::PyBuffer; define_enum!( /// The TLS version. @@ -409,11 +408,8 @@ pub struct TlsInfo(pub wreq::tls::TlsInfo); #[pymethods] impl TlsInfo { - /// Get a read-only memoryview of the peer's DER-encoded leaf certificate. - pub fn peer_certificate(&self) -> Option { - self.0 - .peer_certificate() - .map(ToOwned::to_owned) - .map(PyBuffer::from) + /// Get the peer's DER-encoded leaf certificate as `bytes`. + pub fn peer_certificate(&self) -> Option<&[u8]> { + self.0.peer_certificate() } } diff --git a/src/tls/identity.rs b/src/tls/identity.rs index c5b9ca69..45b9984b 100644 --- a/src/tls/identity.rs +++ b/src/tls/identity.rs @@ -1,10 +1,6 @@ -use pyo3::{ - PyResult, - pybacked::{PyBackedBytes, PyBackedStr}, - pyclass, pymethods, -}; +use pyo3::{PyResult, pybacked::PyBackedStr, pyclass, pymethods}; -use crate::error::Error; +use crate::{buffer::PyBuffer, error::Error}; /// Represents a private key and X509 cert as a client certificate. #[derive(Clone)] @@ -27,7 +23,7 @@ impl Identity { /// ``` #[staticmethod] #[pyo3(signature = (buf, pass))] - pub fn from_pkcs12_der(buf: PyBackedBytes, pass: PyBackedStr) -> PyResult { + pub fn from_pkcs12_der(buf: PyBuffer, pass: PyBackedStr) -> PyResult { wreq::tls::trust::Identity::from_pkcs12_der(buf.as_ref(), pass.as_ref()) .map(Identity) .map_err(Error::Library) @@ -43,7 +39,7 @@ impl Identity { /// A certificate chain here means a series of PEM encoded certificates concatenated together. #[staticmethod] #[pyo3(signature = (buf, key))] - pub fn from_pkcs8_pem(buf: PyBackedBytes, key: PyBackedBytes) -> PyResult { + pub fn from_pkcs8_pem(buf: PyBuffer, key: PyBuffer) -> PyResult { wreq::tls::trust::Identity::from_pkcs8_pem(buf.as_ref(), key.as_ref()) .map(Identity) .map_err(Error::Library) diff --git a/src/tls/store.rs b/src/tls/store.rs index 52cf0692..c90f0b56 100644 --- a/src/tls/store.rs +++ b/src/tls/store.rs @@ -1,10 +1,6 @@ -use pyo3::{ - PyResult, - pybacked::{PyBackedBytes, PyBackedStr}, - pyclass, pymethods, -}; +use pyo3::{PyResult, pybacked::PyBackedStr, pyclass, pymethods}; -use crate::error::Error; +use crate::{buffer::PyBuffer, error::Error}; #[derive(Clone)] #[pyclass(from_py_object)] @@ -16,7 +12,7 @@ impl CertStore { #[new] #[pyo3(signature = (der_certs=None, pem_certs=None, default_paths=false))] pub fn new( - der_certs: Option>, + der_certs: Option>, pem_certs: Option>, default_paths: bool, ) -> PyResult { @@ -47,7 +43,7 @@ impl CertStore { /// Creates a new `CertStore` from a collection of DER-encoded certificates. #[staticmethod] #[pyo3(signature = (certs))] - pub fn from_der_certs(certs: Vec) -> PyResult { + pub fn from_der_certs(certs: Vec) -> PyResult { wreq::tls::trust::CertStore::from_der_certs(&certs) .map(CertStore) .map_err(Error::Library) @@ -67,7 +63,7 @@ impl CertStore { /// Creates a new `CertStore` from a PEM-encoded certificate stack. #[staticmethod] #[pyo3(signature = (certs))] - pub fn from_pem_stack(certs: PyBackedBytes) -> PyResult { + pub fn from_pem_stack(certs: PyBuffer) -> PyResult { wreq::tls::trust::CertStore::from_pem_stack(certs.as_ref()) .map(CertStore) .map_err(Error::Library) diff --git a/tests/buffer_test.py b/tests/buffer_test.py index f036d9dc..06a5aacd 100644 --- a/tests/buffer_test.py +++ b/tests/buffer_test.py @@ -1,7 +1,12 @@ import array import asyncio +import collections.abc +import copy import datetime import gc +import operator +import pickle +import sys import threading import weakref from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer @@ -13,20 +18,44 @@ from wreq.header import HeaderMap, OrigHeaderMap -def assert_readonly_view(view, expected): - assert type(view) is memoryview +def assert_shared_bytes(data, expected): + assert type(data) is wreq.Bytes + view = memoryview(data) assert view.readonly assert view.format == "B" assert view.ndim == 1 - assert view.itemsize == 1 - assert view.shape == (len(expected),) - assert view == expected + assert view.obj is data + assert data == expected + assert expected == data + assert hash(data) == hash(expected) + assert {expected: "value"}[data] == "value" -def test_header_and_message_views(): +def test_header_and_message_values(): headers = HeaderMap({"X-Buffer": "value"}) headers.append("X-Buffer", "other") original = OrigHeaderMap(["X-Buffer"]) + + # Short values are plain bytes copies. + shorts = [ + headers.get("X-Buffer"), + headers["X-Buffer"], + headers.get("missing", b"default"), + headers.get("missing", wreq.Bytes(b"default")), + *headers.get_all("X-Buffer"), + *headers.keys(), + *headers.values(), + *(value for pair in headers for value in pair), + *(value for pair in original for value in pair), + Message.from_ping(b"ping").ping, + Message.from_pong(b"pong").pong, + ] + assert all(type(value) is bytes for value in shorts) + assert shorts[:4] == [b"value", b"value", b"default", b"default"] + assert shorts[-2:] == [b"ping", b"pong"] + assert headers.get("missing") is None + + # Payloads share their data as wreq.Bytes. messages = [ Message.from_text("text"), Message.from_binary(b"binary"), @@ -36,46 +65,184 @@ def test_header_and_message_views(): ] assert messages[0].text == "text" assert type(messages[0].text) is str - round_trip = Message.from_binary(bytes(messages[1].binary)) - assert round_trip.binary == b"binary" - assert headers.get("missing") is None - assert headers.get("missing", b"default") == b"default" - - views = [ - headers.get("X-Buffer"), - headers["X-Buffer"], - headers.get("missing", b"default"), - *headers.get_all("X-Buffer"), - *headers.keys(), - *headers.values(), - *(view for pair in headers for view in pair), - *(view for pair in original for view in pair), - *(message.data for message in messages), - messages[1].binary, - messages[2].ping, - messages[3].pong, - round_trip.binary, - ] - expected = [bytes(view) for view in views] - for view, data in zip(views, expected): - assert_readonly_view(view, data) - assert hash(view) == hash(data) - assert {view: "value"}[data] == "value" + payloads = [*(message.data for message in messages), messages[1].binary] + expected = [b"text", b"binary", b"ping", b"pong", b"", b"binary"] + for data, value in zip(payloads, expected): + assert_shared_bytes(data, value) + assert Message.from_binary(payloads[1]).binary == b"binary" with pytest.raises(TypeError): - views[0][0] = 0 + payloads[1][0] = 0 - headers.clear() - del headers, original, messages, round_trip + del headers, original, messages gc.collect() - for view, data in zip(views, expected): - assert view == data + for data, value in zip(payloads, expected): + assert data == value - parent = views[0] + parent = payloads.pop(1) child = parent[1:] - parent.release() - assert child == b"alue" - child.release() + assert type(child) is wreq.Bytes + with pytest.warns(DeprecationWarning): + parent.release() + del parent + gc.collect() + assert child == b"inary" + + +class Index: + def __init__(self, value): + self.value = value + + def __index__(self): + if isinstance(self.value, Exception): + raise self.value + return self.value + + +class IndexFailure(Exception): + pass + + +def outcome(method, args): + try: + return "ok", method(*args) + except Exception as err: + return "error", type(err) + + +def test_bytes_matches_bytes(): + raw = b"hello world" + data = Message.from_binary(raw).binary + huge = 2**70 + failing = Index(IndexFailure()) + cases = [ + *( + ("__getitem__", key) + for key in (0, -1, 11, -12, huge, Index(1), failing, 1.0, "0") + ), + *( + ("__getitem__", slice(*args)) + for args in [ + (6, None), + (None, None, 2), + (None, None, -1), + (8, 2, -1), + (2, 8, -1), + (None, None, -3), + (huge, None), + ] + ), + *( + ("__contains__", item) + for item in (b"wor", 104, b"xyz", 256, -1, huge, "w") + ), + *( + ("__contains__", item) + for item in (bytearray(b"lo"), memoryview(b"lo"), array.array("B", b"lo")) + ), + ("find", b"o"), + ("find", b"o", 5), + ("find", 111, 5, 7), + ("find", b"", 11), + ("find", b"", 12), + ("find", b"", 2, 1), + ("find", b"l", -huge, huge), + ("find", b"l", Index(3)), + ("find", b"l", failing), + ("find", b"o", 1.0), + ("find", "x", 12), + ("find", 256, 20), + ("find", array.array("B", b"wor")), + ("index", b"wor"), + ("index", b"z"), + ("index", b"o", 5, 6), + ("count", b"l"), + ("count", 108), + ("count", b""), + ("count", b"", 5, 4), + ("count", b"", 12), + ("count", b"l", 3, huge), + ("count", "l"), + ("startswith", b"hello"), + ("startswith", (b"x", b"he")), + ("startswith", b"world", 6), + ("startswith", b"", 11), + ("startswith", b"", 12), + ("startswith", b"", 2, 1), + ("startswith", b"h", -huge), + ("startswith", memoryview(b"he")), + ("startswith", "x"), + ("startswith", ("x",)), + ("startswith", "x", 20), + ("endswith", b"hell", 0, 4), + ("endswith", b"", 5, 4), + ("endswith", array.array("B", b"ld")), + ("hex",), + ("hex", ":", 2), + ("decode",), + ("decode", "latin-1"), + *( + ("__add__", tail) + for tail in (b"!", b"", bytearray(b"!"), array.array("B", b"!")) + ), + ] + for method, *args in cases: + expected = outcome(getattr(raw, method), args) + assert outcome(getattr(data, method), args) == expected, (method, args) + + # wreq follows CPython, whose bytes takes `__index__` needles; PyPy's rejects them. + assert Index(104) in data + assert data.find(Index(119)) == 6 + for result in (data[6:], data[::2], data[::-1], data + b"", data + b"!"): + assert type(result) is wreq.Bytes + assert b">" + data == b">hello world" + with pytest.raises(TypeError): + data + 1 + assert wreq.Bytes(b"aaaa").count(b"aa") == 2 + assert wreq.Bytes(b"\xffab").decode("utf-8", "replace") == "\ufffdab" + with pytest.raises(UnicodeDecodeError): + wreq.Bytes(b"\xff").decode() + + +def test_bytes_api(): + data = Message.from_binary(b"hello world").binary + assert wreq.Bytes(data) is data + assert wreq.Bytes() == b"" + assert wreq.Bytes(bytearray(b"ab")) == b"ab" + numbers = array.array("d", [1.5]) + assert wreq.Bytes(numbers) == bytes(numbers) + for invalid in (5, "text", [1]): + with pytest.raises(TypeError): + wreq.Bytes(invalid) + + assert len(data) == 11 + assert list(data[:3]) == [104, 101, 108] + assert list(reversed(data[:3])) == [108, 101, 104] + items = iter(data) + next(items) + assert operator.length_hint(items) == 10 + assert isinstance(data, collections.abc.Sequence) + if hasattr(collections.abc, "Buffer"): + assert isinstance(data, collections.abc.Buffer) + assert sorted([b"z", data, b"a"]) == [b"a", b"hello world", b"z"] + # Other types reflect, so bytearray and memoryview compare by content. + assert data == bytearray(b"hello world") and data == memoryview(b"hello world") + assert data != bytearray(b"x") and data < bytearray(b"z") + assert data != "hello world" + assert hash(wreq.Bytes()) == hash(b"") + assert type(data.tobytes()) is bytes + assert data.tobytes() == bytes(data) == b"hello world" + assert repr(data) == "Bytes(b'hello world')" + + assert copy.copy(data) is data + assert copy.deepcopy(data) is data + restored = pickle.loads(pickle.dumps(data)) + assert type(restored) is wreq.Bytes + assert restored == data + assert weakref.ref(data)() is data + with pytest.warns(DeprecationWarning): + with data as same: + assert same is data def test_subclass_input_cycles_are_collected(): @@ -108,11 +275,6 @@ def original_name(source): cases = [ (Text, "payload", lambda source: Message.from_text(source).data), (Binary, b"payload", lambda source: Message.from_binary(source).binary), - ( - Binary, - b"payload", - lambda source: Message.from_binary(memoryview(source)).binary, - ), (Binary, b"payload", lambda source: Message.from_ping(source).ping), (Binary, b"payload", lambda source: Message.from_pong(source).pong), (Text, "payload", lambda source: HeaderMap({"X-Buffer": source})["X-Buffer"]), @@ -123,13 +285,22 @@ def original_name(source): (Text, "X-Buffer", lambda source: next(iter(OrigHeaderMap([source])))[1]), (Text, "X-Buffer", original_name), ] + # PyPy's cpyext keeps the source of any memoryview passed to an extension alive. + if sys.implementation.name == "cpython": + cases.append( + ( + Binary, + b"payload", + lambda source: Message.from_binary(memoryview(source)).binary, + ) + ) for input_type, payload, make_view in cases: source = input_type(payload) source.marker = Marker() marker = weakref.ref(source.marker) view = make_view(source) expected = payload.encode() if isinstance(payload, str) else payload - assert_readonly_view(view, expected) + assert view == expected source.view = view del source, view collect_garbage() @@ -213,6 +384,7 @@ def test_bytes_like_inputs(buffer_http_server): memoryview(bytearray(b"payload")), memoryview(b"ppaayyllooaadd")[::2], memoryview(array.array("B", b"payload")), + wreq.Bytes(b"payload"), ] client = blocking.Client(no_proxy=True, timeout=datetime.timedelta(seconds=3)) try: @@ -221,7 +393,7 @@ def test_bytes_like_inputs(buffer_http_server): assert Message.from_binary(numbers).binary == b"[1.5]" assert client.post(buffer_http_server, body=numbers).bytes() == b"[1.5]" assert Message.from_binary({"a": 1}).binary == b'{"a":1}' - message = r"'dict' object is not an instance of 'bytes \| bytearray \| memoryview'" + message = r"'dict' object is not an instance of 'bytes \| bytearray \| memoryview \| Bytes'" with pytest.raises(TypeError, match=message): Message.from_ping({}) for source in sources: @@ -264,17 +436,17 @@ async def collect_async(response): response = await call( client.get, f"{buffer_http_server}/body", version=Version.HTTP_11 ) - view = await call(response.bytes) + data = await call(response.bytes) repeated = await call(response.bytes) - assert_readonly_view(view, b"hello world") - assert_readonly_view(repeated, b"hello world") - repeated.release() - child = view[6:] + assert_shared_bytes(data, b"hello world") + assert_shared_bytes(repeated, b"hello world") + child = data[6:] await call(response.close) del response, repeated gc.collect() - assert view == b"hello world" - view.release() + assert data == b"hello world" + del data + gc.collect() assert child == b"world" response = await call( @@ -289,17 +461,13 @@ async def collect_async(response): await call(response.close) del response gc.collect() - data = [frame for frame in frames if isinstance(frame, memoryview)] + data = [frame for frame in frames if not isinstance(frame, HeaderMap)] trailers = [frame for frame in frames if isinstance(frame, HeaderMap)] assert data assert b"".join(data) == b"hello world" assert len(trailers) == 1 - assert_readonly_view(trailers[0]["X-Buffer"], b"complete") + assert trailers[0]["X-Buffer"] == b"complete" for frame in data: - expected = bytes(frame) - assert_readonly_view(frame, expected) - child = frame[:] - frame.release() - assert child == expected + assert_shared_bytes(frame, frame.tobytes()) finally: client.close() diff --git a/tests/response_test.py b/tests/response_test.py index bd89ba4d..7a99dba7 100644 --- a/tests/response_test.py +++ b/tests/response_test.py @@ -128,8 +128,7 @@ async def test_peer_certificate(): async with resp: assert resp.tls_info is not None certificate = resp.tls_info.peer_certificate() - assert type(certificate) is memoryview - assert certificate.readonly + assert type(certificate) is bytes @pytest.mark.asyncio diff --git a/tests/tls_test.py b/tests/tls_test.py index d7878b23..4ce24eb6 100644 --- a/tests/tls_test.py +++ b/tests/tls_test.py @@ -1,3 +1,5 @@ +import ssl + import pytest import wreq from wreq.emulation import Emulation @@ -27,8 +29,7 @@ async def test_badssl_invalid_cert(): peer_der_cert = tls_info.peer_certificate() assert peer_der_cert is not None - assert type(peer_der_cert) is memoryview - assert peer_der_cert.readonly + assert type(peer_der_cert) is bytes assert len(peer_der_cert) > 0 cert_store = CertStore(der_certs=[bytes(peer_der_cert)]) @@ -59,3 +60,14 @@ def test_tls_options_trust_anchors_and_grease_sigalgs(): def test_extension_type_trust_anchors(): opts = TlsOptions(extension_permutation=[ExtensionType.TRUST_ANCHORS]) assert opts is not None + + +def test_cert_store_accepts_bytes_like(): + certs = ssl.create_default_context().get_ca_certs(binary_form=True) + if not certs: + pytest.skip("no CA certificates loaded") + der = certs[0] + pem = ssl.DER_cert_to_PEM_cert(der).encode() + CertStore(der_certs=[wreq.Bytes(der), memoryview(der)]) + CertStore.from_der_certs([wreq.Bytes(der)]) + CertStore.from_pem_stack(wreq.Bytes(pem)) From 223a968d6767eff11db217efa69b7a454bf1c8ce Mon Sep 17 00:00:00 2001 From: 0x676e67 Date: Tue, 3 Nov 2026 13:18:56 +0000 Subject: [PATCH 4/6] fix(buffer): stop PyPy memoryview leaks and accept bytes-like trust anchors --- RELEASE.md | 1 + docs/source/getting-started/quickstart.md | 5 ++- python/wreq/tls.py | 2 +- python/wreq/wreq.py | 8 ++-- src/buffer.rs | 52 ++++++++++++++++------- src/client/body/stream.rs | 16 +++++-- src/header.rs | 10 ++--- src/tls.rs | 11 ++++- tests/buffer_test.py | 13 +++++- tests/tls_test.py | 6 +++ 10 files changed, 89 insertions(+), 35 deletions(-) diff --git a/RELEASE.md b/RELEASE.md index 7e361d6f..b6c86685 100644 --- a/RELEASE.md +++ b/RELEASE.md @@ -6,6 +6,7 @@ - Set client-only options such as `connect_timeout` and `proxies` on `Client`; passing them to a request now raises `TypeError`. Use `proxy` to select a proxy for one request. - Async request calls check keyword names before returning a coroutine. Values for supported request keywords are still converted on first `await` or entry with `async with`. - Header names and values, `Message.ping`/`pong` and `TlsInfo.peer_certificate()` return `bytes` again instead of `memoryview`. `Response.bytes()`, stream data frames and `Message.data`/`binary` return the new immutable `wreq.Bytes`, which shares data without copying and compares and hashes like `bytes`. Tell stream frames apart with `isinstance(chunk, HeaderMap)` rather than `isinstance(chunk, memoryview)`, and use `memoryview(data)` for `memoryview` attributes such as `.obj`, `.cast()` or `.tolist()`. `bytes` values have no `.tobytes()` or `.release()`; on `wreq.Bytes`, `release()` and `with` emit `DeprecationWarning`. APIs that accept only `bytes`, `bytearray` or `memoryview` by type, such as asyncio `StreamWriter.write` and transports or `orjson.loads`, reject `wreq.Bytes`; pass `memoryview(data)`, which does not copy. +- `memoryview` and `wreq.Bytes` values are now accepted wherever `bytes` is, and are sent as raw bytes. `body=` and `Message.from_binary()` previously JSON-encoded a `memoryview` as an array of integers. ## [0.11.0](https://github.com/0x676e67/wreq-python/compare/v0.10.2..v0.11.0) - 2026-04-13 diff --git a/docs/source/getting-started/quickstart.md b/docs/source/getting-started/quickstart.md index 1ea2fe4b..99a840b4 100644 --- a/docs/source/getting-started/quickstart.md +++ b/docs/source/getting-started/quickstart.md @@ -125,8 +125,9 @@ print(hashlib.sha256(data).hexdigest()) The data remains valid after the response closes. Use it directly with APIs that accept buffers, such as `file.write(data)` or `hashlib.sha256(data)`. It compares and hashes like `bytes`, and provides read-only `bytes` methods such as -`decode()`, `find()`, `count()` and `startswith()`, plus zero-copy slicing. Passing it back to wreq, for example as a -request `body` or to `Message.from_binary`, does not copy it. +`decode()`, `find()`, `count()` and `startswith()`, plus zero-copy slicing. +Passing it back to wreq, for example as a request `body` or to +`Message.from_binary`, does not copy it. Use `data.tobytes()` when an API needs a `bytes` object, such as `json.loads` or code that checks `isinstance(x, bytes)`; it copies the data. APIs that accept diff --git a/python/wreq/tls.py b/python/wreq/tls.py index d4cfb94e..e5db58fb 100644 --- a/python/wreq/tls.py +++ b/python/wreq/tls.py @@ -430,7 +430,7 @@ class Params(TypedDict): Whether the `signature_algorithms` extension includes a GREASE value. """ - trust_anchors: NotRequired[bytes] + trust_anchors: NotRequired[_BytesLike] """ Encoded Trust Anchor IDs sent in a TLS 1.3 ClientHello. """ diff --git a/python/wreq/wreq.py b/python/wreq/wreq.py index 109096c8..85d48ea5 100644 --- a/python/wreq/wreq.py +++ b/python/wreq/wreq.py @@ -317,8 +317,8 @@ def __init__( | memoryview | Bytes | Path - | Generator[bytes, str, None] - | AsyncGenerator[bytes, str] + | Generator[_BytesLike | str, str, None] + | AsyncGenerator[_BytesLike | str, str] ), filename: str | None = None, mime: str | None = None, @@ -1151,8 +1151,8 @@ class Request(TypedDict): | Tuple[str, str | int | float | bool] | Mapping[str, str | int | float | bool] | Any - | Generator[bytes, str, None] - | AsyncGenerator[bytes, str] + | Generator[_BytesLike | str, str, None] + | AsyncGenerator[_BytesLike | str, str] ] """ The body to use for the request. diff --git a/src/buffer.rs b/src/buffer.rs index ea8eae33..d91eb9c1 100644 --- a/src/buffer.rs +++ b/src/buffer.rs @@ -122,10 +122,10 @@ impl FromPyObject<'_, '_> for PyBuffer { Some(bytes) => bytes, // Other exporters, such as numpy numbers or `array('d')`, count as bytes only in a // memoryview, so `body=` and `from_binary` keep encoding them as JSON. - None => Err(PyTypeError::new_err(format!( - "'{}' object is not an instance of 'bytes | bytearray | memoryview | Bytes'", - ob.get_type().qualname()? - ))), + None => Err(not_instance_of( + &ob, + "bytes | bytearray | memoryview | Bytes", + )), } } } @@ -493,16 +493,17 @@ impl SharedBytes { #[pyo3(signature = (sep = None, bytes_per_sep = 1))] fn hex<'py>( - slf: &Bound<'py, Self>, + &self, + py: Python<'py>, sep: Option<&Bound<'py, PyAny>>, bytes_per_sep: isize, ) -> PyResult> { - // `memoryview.hex` reads this buffer in place. - let view = PyMemoryView::from(slf.as_any())?; - let hex = intern!(slf.py(), "hex"); + // `bytes.hex` on a copy: PyPy never frees a memoryview made through its C API. + let copy = to_bytes(py, &self.bytes)?; + let hex = intern!(py, "hex"); match sep { - Some(sep) => view.call_method1(hex, (sep, bytes_per_sep)), - None => view.call_method0(hex), + Some(sep) => copy.call_method1(hex, (sep, bytes_per_sep)), + None => copy.call_method0(hex), } } @@ -661,7 +662,8 @@ fn py_len(data: &[u8]) -> PyResult { .map_err(|_| PyOverflowError::new_err("buffer length exceeds Python's maximum size")) } -/// A `bytes` copy of `data` that raises `MemoryError` where `PyBytes::new` would panic. +/// A `bytes` copy of `data` that raises `MemoryError` where `PyBytes::new` would panic. Unlike +/// the safe `PyBytes::new_with`, it writes the data once instead of zero-filling it first. #[allow(unsafe_code)] fn to_bytes<'py>(py: Python<'py>, data: &[u8]) -> PyResult> { let len = py_len(data)?; @@ -744,12 +746,22 @@ fn bytes_like<'a>(ob: &'a Bound) -> Option>> { /// A raw copy of any other buffer exporter, such as an `array` or numpy data, or `None` for an /// object without a buffer. +#[allow(unsafe_code)] fn buffer_like(ob: &Bound) -> Option> { - match PyMemoryView::from(ob) { - Ok(view) => Some(view_bytes(&view)), - Err(err) if err.is_instance_of::(ob.py()) => None, - Err(err) => Some(Err(err)), + let py = ob.py(); + // Probed without a memoryview, which PyPy never frees once made through its C API. + match PyUntypedBuffer::get(ob) { + Ok(buffer) => buffer.release(py), + Err(err) if err.is_instance_of::(py) => return None, + Err(err) => return Some(Err(err)), } + // SAFETY: `ob` is a live object. For a buffer exporter the call returns a new `bytes` holding + // a C-ordered copy of its raw data, or NULL with an error set. + let copy = unsafe { Bound::from_owned_ptr_or_err(py, ffi::PyBytes_FromObject(ob.as_ptr())) }; + Some(copy.and_then(|copy| { + let owner = PyBackedBytes::from(copy.cast_into::()?); + Ok(share(0..owner.len(), owner)) + })) } /// `ob` as any buffer, as `bytes` methods take their operands. @@ -757,6 +769,16 @@ fn operand<'a>(ob: &'a Bound) -> Option>> { bytes_like(ob).or_else(|| buffer_like(ob).map(|bytes| bytes.map(Operand::Owned))) } +/// The `TypeError` for `ob` where only the `expected` types are accepted. +pub fn not_instance_of(ob: &Bound, expected: &str) -> PyErr { + match ob.get_type().qualname() { + Ok(name) => PyTypeError::new_err(format!( + "'{name}' object is not an instance of '{expected}'" + )), + Err(err) => err, + } +} + /// The `TypeError` for an operand that exports no buffer. fn not_bytes_like(ob: &Bound) -> PyErr { match ob.get_type().qualname() { diff --git a/src/client/body/stream.rs b/src/client/body/stream.rs index 060fc58f..e9ea5b21 100644 --- a/src/client/body/stream.rs +++ b/src/client/body/stream.rs @@ -25,7 +25,10 @@ use pyo3::{ }; use self::{async_gen::AsyncStream, iter::SyncStream}; -use crate::{buffer::PyBuffer, extractor::Text}; +use crate::{ + buffer::{PyBuffer, not_instance_of}, + extractor::Text, +}; type Item = PyResult; @@ -48,9 +51,14 @@ impl FromPyObject<'_, '_> for PyBytesLike { fn extract(ob: Borrowed) -> PyResult { // Checked by type, so a str chunk does not first fail as bytes. if ob.is_instance_of::() { - ob.extract().map(PyBytesLike::String) - } else { - ob.extract().map(PyBytesLike::Bytes) + return ob.extract().map(PyBytesLike::String); + } + match PyBuffer::extract_bytes_like(&ob) { + Some(bytes) => bytes.map(PyBytesLike::Bytes), + None => Err(not_instance_of( + &ob, + "str | bytes | bytearray | memoryview | Bytes", + )), } } } diff --git a/src/header.rs b/src/header.rs index 408c01b0..7aa64753 100644 --- a/src/header.rs +++ b/src/header.rs @@ -70,12 +70,10 @@ impl HeaderMap { default: Option, ) -> Option> { // Header values are short, so a `bytes` copy is cheaper than a shared buffer. - if let Some(value) = self.0.get::<&str>(key.as_ref()) { - return Some(PyBytes::new(py, value.as_bytes())); - } - HeaderValue::from_maybe_shared(default?.0) - .ok() - .map(|value| PyBytes::new(py, value.as_bytes())) + let value = self.0.get::<&str>(key.as_ref()).map(HeaderValue::as_bytes); + value + .or(default.as_ref().map(AsRef::as_ref)) + .map(|value| PyBytes::new(py, value)) } /// Returns a list of `bytes` for the values associated with a key. diff --git a/src/tls.rs b/src/tls.rs index 49d944a8..1ea7d140 100644 --- a/src/tls.rs +++ b/src/tls.rs @@ -8,6 +8,7 @@ use wreq::tls::compress::CertificateCompressor; use wreq_util::emulate::compress; pub use self::{identity::Identity, keylog::KeyLog, store::CertStore}; +use crate::buffer::PyBuffer; define_enum!( /// The TLS version. @@ -220,7 +221,7 @@ struct Builder { grease_sigalgs_enabled: Option, /// Encoded Trust Anchor IDs sent in a TLS 1.3 ClientHello. - trust_anchors: Option>, + trust_anchors: Option, } /// TLS connection configuration options. @@ -394,7 +395,13 @@ impl TlsOptions { params.grease_sigalgs_enabled, grease_sigalgs_enabled ); - apply_option!(set_if_some, builder, params.trust_anchors, trust_anchors); + apply_option!( + set_if_some_map, + builder, + params.trust_anchors, + trust_anchors, + |ids: PyBuffer| ids.0.to_vec() + ); } Self(builder.build()) diff --git a/tests/buffer_test.py b/tests/buffer_test.py index 06a5aacd..a7fd7fcf 100644 --- a/tests/buffer_test.py +++ b/tests/buffer_test.py @@ -54,6 +54,8 @@ def test_header_and_message_values(): assert shorts[:4] == [b"value", b"value", b"default", b"default"] assert shorts[-2:] == [b"ping", b"pong"] assert headers.get("missing") is None + # A default is returned as given, even if it is not a valid header value. + assert headers.get("missing", b"bad\nvalue") == b"bad\nvalue" # Payloads share their data as wreq.Bytes. messages = [ @@ -348,9 +350,14 @@ def do_GET(self): def do_POST(self): if self.headers.get("Transfer-Encoding") == "chunked": body = b"" - while size := int(self.rfile.readline(), 16): + while line := self.rfile.readline(): + if not (size := int(line, 16)): + break body += self.rfile.read(size) self.rfile.readline() + else: + # The client closed the connection mid-body. + return self.rfile.readline() else: body = self.rfile.read(int(self.headers["Content-Length"])) @@ -407,6 +414,10 @@ def test_bytes_like_inputs(buffer_http_server): form = Multipart(Part("field", source)) response = client.post(buffer_http_server, multipart=form) assert b"\r\n\r\npayload\r\n" in bytes(response.bytes()), source + # Stream chunks may also be str, which the error names. + message = r"'int' object is not an instance of 'str \| bytes \| bytearray" + with pytest.raises(wreq.RequestError, match=message): + client.post(buffer_http_server, body=iter([1])) finally: client.close() diff --git a/tests/tls_test.py b/tests/tls_test.py index 4ce24eb6..08eeac7e 100644 --- a/tests/tls_test.py +++ b/tests/tls_test.py @@ -71,3 +71,9 @@ def test_cert_store_accepts_bytes_like(): CertStore(der_certs=[wreq.Bytes(der), memoryview(der)]) CertStore.from_der_certs([wreq.Bytes(der)]) CertStore.from_pem_stack(wreq.Bytes(pem)) + + +def test_trust_anchors_accept_bytes_like(): + # Any buffer is taken as raw bytes, not as a sequence of items. + for ids in (wreq.Bytes(b"\x01\x02"), memoryview(b"\x01\x02\x03\x04").cast("I")): + assert TlsOptions(trust_anchors=ids) is not None From 8ed6ee753397163bfb189f115d2d6be00ca50e10 Mon Sep 17 00:00:00 2001 From: 0x676e67 Date: Tue, 3 Nov 2026 14:30:20 +0000 Subject: [PATCH 5/6] fix(buffer): compare Bytes with bytearray directly for PyPy 8 --- src/buffer.rs | 10 ++++++++-- tests/buffer_test.py | 3 ++- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/src/buffer.rs b/src/buffer.rs index d91eb9c1..76573277 100644 --- a/src/buffer.rs +++ b/src/buffer.rs @@ -394,14 +394,20 @@ impl SharedBytes { Ok(window(&self.bytes, start, end).map_or(0, |(_, data)| needle.count(data))) } - /// Compares with `bytes` or `Bytes`; other types reflect, so `bytearray` and `memoryview` - /// compare through their own methods over this buffer. + /// Compares with `bytes`, `bytearray` or `Bytes`; other types reflect, so a `memoryview` + /// compares through its own method over this buffer. fn __richcmp__(&self, other: &Bound, op: CompareOp) -> Py { let py = other.py(); + let copy; let other = if let Some(other) = as_exact::(other) { &other.get().bytes[..] } else if let Some(other) = as_instance::(other) { other.as_bytes() + } else if let Some(array) = as_instance::(other) { + // Compared here, since PyPy's bytearray does not read extension buffers. A copy + // keeps the bytearray from being resized under the comparison. + copy = array.to_vec(); + © } else { return py.NotImplemented(); }; diff --git a/tests/buffer_test.py b/tests/buffer_test.py index a7fd7fcf..1d53b9db 100644 --- a/tests/buffer_test.py +++ b/tests/buffer_test.py @@ -227,8 +227,9 @@ def test_bytes_api(): if hasattr(collections.abc, "Buffer"): assert isinstance(data, collections.abc.Buffer) assert sorted([b"z", data, b"a"]) == [b"a", b"hello world", b"z"] - # Other types reflect, so bytearray and memoryview compare by content. + # bytearray compares here and memoryview through its own method, both by content. assert data == bytearray(b"hello world") and data == memoryview(b"hello world") + assert bytearray(b"hello world") == data and memoryview(b"hello world") == data assert data != bytearray(b"x") and data < bytearray(b"z") assert data != "hello world" assert hash(wreq.Bytes()) == hash(b"") From 6b85aae29e61439e4d523740b7ee1109c20e844e Mon Sep 17 00:00:00 2001 From: 0x676e67 Date: Thu, 5 Nov 2026 10:00:10 +0000 Subject: [PATCH 6/6] docs(buffer): fix streaming links and add a wreq.Bytes example --- docs/source/getting-started/introduction.md | 4 +++- docs/source/guide/advanced.md | 5 ++-- docs/source/guide/basic.md | 5 ++-- docs/source/guide/redirect-errors.md | 2 +- docs/source/index.md | 2 +- examples/bytes.py | 26 +++++++++++++++++++++ 6 files changed, 37 insertions(+), 7 deletions(-) create mode 100644 examples/bytes.py diff --git a/docs/source/getting-started/introduction.md b/docs/source/getting-started/introduction.md index d694de1a..ccb2dad5 100644 --- a/docs/source/getting-started/introduction.md +++ b/docs/source/getting-started/introduction.md @@ -57,7 +57,9 @@ connections, and use context managers to close resources when you're done. headers are `bytes`. Use `data.tobytes()` when an API requires `bytes`; the conversion copies the data. - [Advanced features](../guide/advanced.md) + [Streaming responses](../guide/basic.md#streaming-responses) · + [Uploads](../guide/advanced.md#streaming-request-bodies) · + [Binary data](quickstart.md#binary-data) - **Runtime configuration** diff --git a/docs/source/guide/advanced.md b/docs/source/guide/advanced.md index c1a815c2..57c2fad0 100644 --- a/docs/source/guide/advanced.md +++ b/docs/source/guide/advanced.md @@ -1,12 +1,13 @@ # Advanced features Use streaming uploads for data produced incrementally, and multipart forms for -named fields and files. Response streaming is covered in [basic usage](basic.md). +named fields and files. Response streaming is covered in +[basic usage](basic.md#streaming-responses). ## Streaming request bodies Pass a synchronous iterator or an async generator to `body`. Each item must -be a supported body chunk, such as `bytes` or `str`: +be `str` or bytes-like data, such as `bytes` or `wreq.Bytes`: ```python import asyncio diff --git a/docs/source/guide/basic.md b/docs/source/guide/basic.md index bd86b322..d357c50b 100644 --- a/docs/source/guide/basic.md +++ b/docs/source/guide/basic.md @@ -82,8 +82,9 @@ keywords are converted when the coroutine is first awaited or entered with ## Request bodies Use `json` for JSON, `form` for URL-encoded fields, and `body` for raw text or -bytes. `json` and `form` set their content type automatically. Set it explicitly -for a raw body when the server needs it. Choose one body argument per request. +bytes-like data (`bytes`, `bytearray`, `memoryview` or `wreq.Bytes`). `json` and +`form` set their content type automatically. Set it explicitly for a raw body +when the server needs it. Choose one body argument per request. ```python async with client.post( diff --git a/docs/source/guide/redirect-errors.md b/docs/source/guide/redirect-errors.md index 1ae03843..8014d493 100644 --- a/docs/source/guide/redirect-errors.md +++ b/docs/source/guide/redirect-errors.md @@ -26,7 +26,7 @@ async def main(): print(response.status) location = response.headers.get("location") if location is not None: - print("Location:", bytes(location).decode()) + print("Location:", location.decode()) await response.bytes() diff --git a/docs/source/index.md b/docs/source/index.md index 87686c92..058d4183 100644 --- a/docs/source/index.md +++ b/docs/source/index.md @@ -81,7 +81,7 @@ asyncio.run(main()) 02 · PERFORMANCE

High-throughput HTTPS

Rust handles the network I/O. See how wreq compares with other Python clients, then choose the body size and runtime mode that matter to your workload.

View performance results
-03 · STREAMING

Stream uploads and responses

Send an upload in chunks or read a response as it arrives. Response chunks are zero-copy wreq.Bytes objects backed by Rust buffers.

Streaming guide
+03 · STREAMING

Stream uploads and responses

Send an upload in chunks or read a response as it arrives. Response chunks are zero-copy wreq.Bytes objects backed by Rust buffers.

Streaming guide
04 · PYTHON

Async and blocking APIs

Use await in async code. For a synchronous script, import Client from wreq.blocking.

Blocking API
diff --git a/examples/bytes.py b/examples/bytes.py new file mode 100644 index 00000000..774c3bbb --- /dev/null +++ b/examples/bytes.py @@ -0,0 +1,26 @@ +import asyncio +import hashlib +import json + +import wreq + + +async def main(): + async with wreq.Client() as client: + async with client.get("https://httpbin.io/json") as resp: + # An immutable wreq.Bytes that shares the body without copying. + data = await resp.bytes() + + # Buffer APIs read it in place, and slices share it too. + print(hashlib.sha256(data).hexdigest(), data[:16]) + + # json.loads() takes only str, bytes or bytearray. + print(json.loads(data.decode())["slideshow"]["title"]) + + # Passing it back as a request body does not copy it. + async with client.post("https://httpbin.io/anything", body=data) as resp: + print(resp.status) + + +if __name__ == "__main__": + asyncio.run(main())