From f12c06251627f04ef70b905056105ae49e46ea46 Mon Sep 17 00:00:00 2001 From: Leo Nash Date: Wed, 28 Jan 2026 00:17:18 +0000 Subject: [PATCH 1/2] [bitreq] Check utf-8 while parsing JSON responses While deserializing, `serde_json::from_slice` validates utf-8 as needed. So instead of making two passes on the response body, one to validate utf-8, and another to deserialize the object, we let `serde_json::from_slice` check utf-8 as needed during deserialization. Making a single pass over large response bodies reduces the number of cache misses, and hence decreases the cycles taken to fully deserialize such responses. `Response::json` now returns `Error::SerdeJsonError` instead of `Error::InvalidUtf8InBody` if invalid utf-8 is found during deserialization. For this error case, the `Error::SerdeJsonError` inner type `serde_json::error::Error` is of category `serde_json::error::Category::Syntax`. Other JSON syntax errors are also assigned to this category. We accept this loss of information given the performance gain described above. --- bitreq/src/response.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bitreq/src/response.rs b/bitreq/src/response.rs index eaf254f04..b234de107 100644 --- a/bitreq/src/response.rs +++ b/bitreq/src/response.rs @@ -248,7 +248,7 @@ impl Response { where T: serde::de::Deserialize<'a>, { - match serde_json::from_str(self.as_str()?) { + match serde_json::from_slice(self.as_bytes()) { Ok(json) => Ok(json), Err(err) => Err(Error::SerdeJsonError(err)), } From 2c3bbf21a47132b4292e13093e8f6068db679dff Mon Sep 17 00:00:00 2001 From: Leo Nash Date: Wed, 28 Jan 2026 03:54:48 +0000 Subject: [PATCH 2/2] [bitreq] Serialize `Request` body into `Vec` We avoid creating a `String` only to immediately convert it back to its inner `Vec`. This also mirrors the `serde_json::from_slice` call made when parsing a `Response` body as JSON. --- bitreq/src/request.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bitreq/src/request.rs b/bitreq/src/request.rs index 7f9b5d530..2f1755782 100644 --- a/bitreq/src/request.rs +++ b/bitreq/src/request.rs @@ -190,7 +190,7 @@ impl Request { pub fn with_json(mut self, body: &T) -> Result { self.headers .insert("Content-Type".to_string(), "application/json; charset=UTF-8".to_string()); - match serde_json::to_string(&body) { + match serde_json::to_vec(&body) { Ok(json) => Ok(self.with_body(json)), Err(err) => Err(Error::SerdeJsonError(err)), }