1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
use super::*;
/// Default construction for [`HttpResponse`].
impl Default for HttpResponse {
/// Returns the default `HttpResponse`.
///
/// The status code and reason phrase fall back to `HttpStatus::Unknown`,
/// the header map is empty, and the body is empty.
fn default() -> Self {
Self {
version: HttpVersion::default(),
status_code: HttpStatus::Unknown.code(),
reason_phrase: HttpStatus::Unknown.to_string(),
headers: new_response_headers(),
body: Vec::new(),
}
}
}
/// Inherent implementation of [`HttpResponse`].
impl HttpResponse {
/// Construct from raw response bytes (status line + headers + body).
///
/// # Arguments
///
/// - `&[u8]` - The complete raw response bytes, including the status line,
/// the header block, and the body.
pub fn from_bytes(response: &[u8]) -> Self {
if response.is_empty() {
return Self::default();
}
let status_end: usize = find_crlf(response, 0).unwrap_or(response.len());
let status_line: &[u8] = &response[..status_end];
let sl_len: usize = status_line.len();
let mut idx: usize = 0;
while idx < sl_len && (status_line[idx] == SPACE_U8 || status_line[idx] == TAB_U8) {
idx += 1;
}
let v_start: usize = idx;
while idx < sl_len && status_line[idx] != SPACE_U8 && status_line[idx] != TAB_U8 {
idx += 1;
}
let version_bytes: &[u8] = &status_line[v_start..idx];
while idx < sl_len && (status_line[idx] == SPACE_U8 || status_line[idx] == TAB_U8) {
idx += 1;
}
let c_start: usize = idx;
while idx < sl_len && status_line[idx] != SPACE_U8 && status_line[idx] != TAB_U8 {
idx += 1;
}
let code_bytes: &[u8] = &status_line[c_start..idx];
while idx < sl_len && (status_line[idx] == SPACE_U8 || status_line[idx] == TAB_U8) {
idx += 1;
}
let mut r_end: usize = sl_len;
while r_end > idx
&& (status_line[r_end - 1] == SPACE_U8 || status_line[r_end - 1] == TAB_U8)
{
r_end -= 1;
}
let reason_bytes: &[u8] = &status_line[idx..r_end];
let version: HttpVersion = if version_bytes.is_empty() {
HttpVersion::default()
} else if version_bytes == HTTP_VERSION_1_1.as_bytes() {
HttpVersion::Http1_1
} else if version_bytes == HTTP_VERSION_1_0.as_bytes() {
HttpVersion::Http1_0
} else if version_bytes == HTTP_VERSION_2.as_bytes() {
HttpVersion::Http2
} else {
from_utf8(version_bytes)
.ok()
.and_then(|version_str: &str| version_str.parse::<HttpVersion>().ok())
.unwrap_or_default()
};
let status_code: usize = if code_bytes.is_empty() {
HttpStatus::Unknown.code()
} else {
let mut parsed: usize = 0;
let mut valid: bool = true;
for &byte in code_bytes {
if byte.is_ascii_digit() {
if let Some(next) = parsed
.checked_mul(10)
.and_then(|val: usize| val.checked_add((byte - ASCII_ZERO) as usize))
{
parsed = next;
} else {
valid = false;
break;
}
} else {
valid = false;
break;
}
}
if valid {
parsed
} else {
HttpStatus::Unknown.code()
}
};
let reason_phrase: String = if reason_bytes.is_empty() {
HttpStatus::Unknown.to_string()
} else {
let needs_ws_collapse: bool = reason_bytes.windows(2).any(|pair: &[u8]| {
pair[0] == TAB_U8
|| pair[1] == TAB_U8
|| (pair[0] == SPACE_U8 && pair[1] == SPACE_U8)
}) || reason_bytes[0] == TAB_U8;
if !needs_ws_collapse && let Ok(reason_str) = from_utf8(reason_bytes) {
reason_str.to_owned()
} else {
let mut result: String = String::with_capacity(reason_bytes.len());
let mut r_pos: usize = 0;
let mut first_word: bool = true;
while r_pos < reason_bytes.len() {
while r_pos < reason_bytes.len()
&& (reason_bytes[r_pos] == SPACE_U8 || reason_bytes[r_pos] == TAB_U8)
{
r_pos += 1;
}
let w_start: usize = r_pos;
while r_pos < reason_bytes.len()
&& reason_bytes[r_pos] != SPACE_U8
&& reason_bytes[r_pos] != TAB_U8
{
r_pos += 1;
}
if r_pos > w_start {
if !first_word {
result.push(' ');
}
first_word = false;
result.push_str(&String::from_utf8_lossy(&reason_bytes[w_start..r_pos]));
}
}
result
}
};
let mut pos: usize = if status_end < response.len() {
status_end + HTTP_BR_BYTES.len()
} else {
response.len()
};
let mut headers: HashMapXxHash3_64<String, String> =
if pos < response.len() && !response[pos..].starts_with(HTTP_BR_BYTES) {
HashMap::with_capacity_and_hasher(4, BuildHasherDefault::default())
} else {
new_response_headers()
};
let mut body_start: usize = response.len();
while pos < response.len() {
let line_end: usize = find_crlf(response, pos).unwrap_or(response.len());
let line: &[u8] = &response[pos..line_end];
let next_pos: usize = if line_end < response.len() {
line_end + HTTP_BR_BYTES.len()
} else {
response.len()
};
if line.is_empty() {
body_start = next_pos;
break;
}
if let Some(colon_pos) = line.iter().position(|byte: &u8| *byte == COLON_U8)
&& colon_pos > 0
&& colon_pos + 1 < line.len()
{
let key_bytes: &[u8] = &line[..colon_pos];
let value_start: usize = if line[colon_pos + 1] == SPACE_U8 {
colon_pos + 2
} else {
colon_pos + 1
};
let value_bytes: &[u8] = &line[value_start..];
if let (Ok(key_str), Ok(value_str)) = (from_utf8(key_bytes), from_utf8(value_bytes))
{
let key_owned: String = key_str.trim().to_ascii_lowercase();
let val_trimmed: &str = value_str.trim();
if key_owned == SET_COOKIE
&& let Some(existing) = headers.get_mut(SET_COOKIE)
{
existing.push(SET_COOKIE_DELIMITER);
existing.push_str(val_trimmed);
} else {
headers.insert(key_owned, val_trimmed.to_owned());
}
}
}
pos = next_pos;
}
let body: Vec<u8> = if body_start >= response.len() {
Vec::new()
} else {
let body_slice: &[u8] = &response[body_start..];
if find_crlf(body_slice, 0).is_none() {
body_slice.to_vec()
} else {
let mut body_out: Vec<u8> = Vec::with_capacity(body_slice.len());
let mut cursor: usize = 0;
while let Some(crlf_pos) = find_crlf(body_slice, cursor) {
body_out.extend_from_slice(&body_slice[cursor..crlf_pos]);
cursor = crlf_pos + HTTP_BR_BYTES.len();
if cursor < body_slice.len() {
body_out.extend_from_slice(BR_BYTES);
}
}
if cursor < body_slice.len() {
body_out.extend_from_slice(&body_slice[cursor..]);
}
body_out
}
};
HttpResponse {
version,
status_code,
reason_phrase,
headers,
body,
}
}
/// Was the response a 1xx informational status?
///
/// # Returns
///
/// - `bool` - `true` when the status code lies in the `100..200` range.
#[inline]
pub fn is_informational(&self) -> bool {
(100..200).contains(&self.get_status_code())
}
/// Was the response a 2xx success?
///
/// # Returns
///
/// - `bool` - `true` when the status code lies in the `200..300` range.
pub fn is_success(&self) -> bool {
(200..300).contains(&self.get_status_code())
}
/// Was the response a 3xx redirect?
///
/// # Returns
///
/// - `bool` - `true` when the status code lies in the `300..400` range.
pub fn is_redirect(&self) -> bool {
(300..400).contains(&self.get_status_code())
}
/// Was the response a 4xx client error?
///
/// # Returns
///
/// - `bool` - `true` when the status code lies in the `400..500` range.
pub fn is_client_error(&self) -> bool {
(400..500).contains(&self.get_status_code())
}
/// Was the response a 5xx server error?
///
/// # Returns
///
/// - `bool` - `true` when the status code lies in the `500..600` range.
pub fn is_server_error(&self) -> bool {
(500..600).contains(&self.get_status_code())
}
/// Look up a single header value (case-insensitive) without heap allocation for short keys.
///
/// # Arguments
///
/// - `K` - The header name to look up, matched case-insensitively.
///
/// # Returns
///
/// - `Option<&str>` - The header value, or `None` when the header is absent.
pub fn get_header<K>(&self, key: K) -> Option<&str>
where
K: AsRef<str>,
{
let raw: &str = key.as_ref();
let bytes: &[u8] = raw.as_bytes();
if !bytes.iter().any(|b: &u8| b.is_ascii_uppercase()) {
return self.get_headers().get(raw).map(String::as_str);
}
if bytes.len() <= RESPONSE_HEADER_STACK_LIMIT {
let mut stack_buf: [MaybeUninit<u8>; RESPONSE_HEADER_STACK_LIMIT] =
[const { MaybeUninit::uninit() }; RESPONSE_HEADER_STACK_LIMIT];
for (idx, &byte) in bytes.iter().enumerate() {
stack_buf[idx].write(byte.to_ascii_lowercase());
}
// SAFETY: Replacing ASCII uppercase bytes with ASCII lowercase preserves UTF-8 validity,
// and `0..bytes.len()` were initialized in the loop above.
let lower: &str = unsafe {
from_utf8_unchecked(slice::from_raw_parts(
stack_buf.as_ptr().cast::<u8>(),
bytes.len(),
))
};
return self.get_headers().get(lower).map(String::as_str);
}
let normalized: String = raw.to_ascii_lowercase();
self.get_headers().get(&normalized).map(String::as_str)
}
/// Get the response body as a UTF-8 string (lossy on invalid bytes).
///
/// # Returns
///
/// - `String` - The owned body text, with invalid byte sequences replaced.
pub fn text(&self) -> String {
String::from_utf8_lossy(self.get_body()).into_owned()
}
/// Get the response body as raw bytes.
///
/// # Returns
///
/// - `&[u8]` - The raw, undecoded body bytes.
pub fn bytes(&self) -> &[u8] {
self.get_body()
}
/// Deserialize the response body from JSON into `T`.
///
/// # Returns
///
/// - `Result<T, serde_json::Error>` - Parsed JSON payload or a deserialization error.
pub fn json<T>(&self) -> Result<T, serde_json::Error>
where
T: DeserializeOwned,
{
from_slice(self.get_body())
}
/// Converts a `4xx` or `5xx` HTTP response into an error while returning `1xx`–`3xx` responses unchanged.
///
/// # Returns
///
/// - `Result<Self, RequestError>` - `Ok(self)` for status codes `< 400`, or `Err(RequestError)` otherwise.
#[inline]
pub fn error_for_status(self) -> Result<Self, RequestError> {
let code: usize = self.get_status_code();
if code >= 400 {
return Err(RequestError::Request(format!(
"HTTP status error: {code} {}",
self.get_reason_phrase()
)));
}
Ok(self)
}
/// Returns the `Content-Type` response header value when present.
///
/// # Returns
///
/// - `Option<&str>` - `Content-Type` header value, if present.
#[inline]
pub fn content_type(&self) -> Option<&str> {
self.get_header(CONTENT_TYPE)
}
/// Returns the parsed decimal `Content-Length` header value when present and valid.
///
/// # Returns
///
/// - `Option<usize>` - Declared byte length, if present and valid.
#[inline]
pub fn content_length(&self) -> Option<usize> {
self.get_header(CONTENT_LENGTH)?
.trim()
.parse::<usize>()
.ok()
}
/// Returns the `Location` response header value when present.
///
/// # Returns
///
/// - `Option<&str>` - Redirect or created-resource `Location` header, if present.
#[inline]
pub fn location(&self) -> Option<&str> {
self.get_header(LOCATION)
}
/// Borrows the response body as a strict UTF-8 `&str` without allocating.
///
/// # Returns
///
/// - `Result<&str, Utf8Error>` - Borrowed UTF-8 body text or decoding error.
#[inline]
pub fn text_strict(&self) -> Result<&str, Utf8Error> {
from_utf8(self.get_body())
}
/// Returns all raw `Set-Cookie` header lines received on this response.
///
/// # Returns
///
/// - `Vec<&str>` - Every individual `Set-Cookie` header value in arrival order.
pub fn set_cookies(&self) -> Vec<&str> {
let Some(raw) = self.get_header(SET_COOKIE) else {
return Vec::new();
};
raw.split(SET_COOKIE_DELIMITER)
.filter(|entry: &&str| !entry.is_empty())
.collect()
}
/// Parses all cookies declared by one or more `Set-Cookie` headers, when present.
///
/// # Returns
///
/// - `Option<HashMapXxHash3_64<String, String>>` - Parsed cookie map, or `None` when `Set-Cookie` is absent.
pub fn try_get_cookies(&self) -> Option<HashMapXxHash3_64<String, String>> {
let header: &str = self.get_header(SET_COOKIE)?;
let mut cookies: HashMapXxHash3_64<String, String> = hash_map_xx_hash3_64();
for line in header.split(SET_COOKIE_DELIMITER) {
if line.is_empty() {
continue;
}
let parsed: CookieBuilder = CookieBuilder::parse(line);
if !parsed.get_name().is_empty() {
cookies.insert(parsed.get_name().clone(), parsed.get_value().clone());
}
}
Some(cookies)
}
/// Decode the body using the headers' Content-Encoding (gzip / deflate /
/// br). Returns a fresh response with the decoded body — the original is
/// untouched. `buffer_size` controls the chunk size for streaming decoders.
///
/// # Arguments
///
/// - `usize` - The chunk size used by the streaming decoders.
///
/// # Returns
///
/// - `HttpResponse` - A new response identical to this one except that its
/// body holds the decoded bytes.
pub fn decode(&self, buffer_size: usize) -> HttpResponse {
let decoded: Vec<u8> = Compress::from(self.get_headers())
.decode(self.get_body(), buffer_size)
.into_owned();
HttpResponse {
version: self.get_version().clone(),
status_code: self.get_status_code(),
reason_phrase: self.get_reason_phrase().clone(),
headers: self.get_headers().clone(),
body: decoded,
}
}
/// Decodes the response body in place when a supported `Content-Encoding` is present.
///
/// Avoids cloning headers, reason phrase, and uncompressed body bytes when no content
/// decoding is required.
///
/// # Arguments
///
/// - `usize` - The chunk size used by the streaming decoders.
#[inline]
pub(crate) fn decode_in_place(&mut self, buffer_size: usize) {
let algo: Compress = Compress::from(self.get_headers());
if algo.is_unknown() {
return;
}
let decoded: Vec<u8> = algo.decode(self.get_body(), buffer_size).into_owned();
let Self { body, .. } = self;
*body = decoded;
}
}