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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
use super::*;
/// Implements the `std::error::Error` trait for `ResponseError`.
/// This allows `ResponseError` to be treated as a standard Rust error type.
impl Error for ResponseError {}
/// Converts an I/O error to a `ResponseError`.
///
/// Maps I/O errors to `Send` variant with the error message.
impl From<io::Error> for ResponseError {
/// Converts an I/O error to a `ResponseError`.
///
/// # Arguments
///
/// - `io::Error` - The I/O error to convert.
///
/// # Returns
///
/// - `ResponseError` - The corresponding response error as `Send`.
#[inline(always)]
fn from(error: io::Error) -> Self {
ResponseError::Send(error.to_string())
}
}
/// Implements the `Display` trait for `ResponseError`.
/// This allows `ResponseError` variants to be formatted into human-readable strings.
impl Display for ResponseError {
/// Formats the `ResponseError` variant into a human-readable string.
///
/// # Arguments
///
/// - `&mut Formatter<'_>` - The formatter used for writing the formatted string.
///
/// # Returns
///
/// A `fmt::Result` indicating whether the formatting was successful.
#[inline(always)]
fn fmt(&self, data: &mut Formatter<'_>) -> fmt::Result {
match self {
Self::NotFoundStream => {
write!(data, "Not found stream")
}
Self::ConnectionClosed => {
write!(data, "Connection has been closed")
}
Self::Terminated => {
write!(data, "Current processing has been terminated")
}
Self::Send(error) => write!(data, "Send error{COLON_SPACE}{error}"),
Self::FlushError(error) => write!(data, "Flush error{COLON_SPACE}{error}"),
Self::Unknown => write!(data, "Unknown error"),
}
}
}
/// Provides a default value for `Response`.
///
/// Returns a new `Response` instance with all fields initialized to their default values.
impl Default for Response {
/// Builds the default `Response` with all fields set to their defaults.
#[inline(always)]
fn default() -> Self {
Self {
version: HttpVersion::Http1_1,
status_code: HttpStatus::Ok.code(),
reason_phrase: OK.to_owned(),
headers: hash_map_xx_hash3_64(),
body: Vec::new(),
}
}
}
/// Inherent implementation of [`Response`].
impl Response {
/// Sets the response reason phrase while reusing the existing string capacity.
///
/// # Arguments
///
/// - `impl AsRef<str>` - The reason phrase text.
///
/// # Returns
///
/// - `&mut Self` - A mutable reference to self for chaining.
#[inline(always)]
pub fn set_reason_phrase(&mut self, val: impl AsRef<str>) -> &mut Self {
let text: &str = val.as_ref();
if !Self::is_valid_header_value(text) {
return self;
}
self.reason_phrase.clear();
self.reason_phrase.push_str(text);
self
}
/// Sets the response body while reusing the existing byte vector capacity.
///
/// # Arguments
///
/// - `impl AsRef<[u8]>` - The response body bytes.
///
/// # Returns
///
/// - `&mut Self` - A mutable reference to self for chaining.
#[inline(always)]
pub fn set_body(&mut self, val: impl AsRef<[u8]>) -> &mut Self {
let bytes: &[u8] = val.as_ref();
self.body.clear();
self.body.extend_from_slice(bytes);
self
}
/// Pushes a header with a key and value as_ref the response bytes.
///
/// # Arguments
///
/// - `&mut Vec<u8>` - A mutable reference to the bytes where the header will be added.
/// - `&str` - The header key as a string slice (`&str`).
/// - `&str` - The header value as a string slice (`&str`).
#[inline(always)]
fn push_header(response_bytes: &mut Vec<u8>, key: &str, value: &str) {
response_bytes.extend_from_slice(key.as_bytes());
response_bytes.extend_from_slice(COLON.as_bytes());
response_bytes.extend_from_slice(value.as_bytes());
response_bytes.extend_from_slice(HTTP_BR.as_bytes());
}
/// Tries to retrieve the value of a response header by its key.
///
/// # Arguments
///
/// - `K` - The header's key, which must implement `AsRef<str>`.
///
/// # Returns
///
/// - `Option<VecDeque<String>>` - The optional header values.
#[inline(always)]
pub fn try_get_header<K>(&self, key: K) -> Option<VecDeque<String>>
where
K: AsRef<str>,
{
self.headers.get(key.as_ref()).cloned()
}
/// Retrieves the value of a response header by its key.
///
/// # Arguments
///
/// - `K` - The header's key, which must implement `AsRef<str>`.
///
/// # Returns
///
/// - `VecDeque<String>` - The optional header values.
///
/// # Panics
///
/// This function will panic if the header key is not found.
#[inline(always)]
pub fn get_header<K>(&self, key: K) -> VecDeque<String>
where
K: AsRef<str>,
{
self.try_get_header(key).unwrap()
}
/// Tries to retrieve the first value of a response header by its key.
///
/// # Arguments
///
/// - `K` - The header's key, which must implement `AsRef<str>`.
///
/// # Returns
///
/// - `Option<String>` - The first header value if exists.
#[inline(always)]
pub fn try_get_header_front<K>(&self, key: K) -> Option<String>
where
K: AsRef<str>,
{
self.headers
.get(key.as_ref())
.and_then(|data: &VecDeque<String>| data.front().cloned())
}
/// Retrieves the first value of a response header by its key.
///
/// # Arguments
///
/// - `K` - The header's key, which must implement `AsRef<str>`.
///
/// # Returns
///
/// - `String` - The first header value if exists.
///
/// # Panics
///
/// This function will panic if the header key is not found.
#[inline(always)]
pub fn get_header_front<K>(&self, key: K) -> String
where
K: AsRef<str>,
{
self.try_get_header_front(key).unwrap()
}
/// Tries to retrieve the last value of a response header by its key.
///
/// # Arguments
///
/// - `K` - The header's key, which must implement `AsRef<str>`.
///
/// # Returns
///
/// - `Option<String>` - The last header value if exists.
#[inline(always)]
pub fn try_get_header_back<K>(&self, key: K) -> Option<String>
where
K: AsRef<str>,
{
self.headers
.get(key.as_ref())
.and_then(|data: &VecDeque<String>| data.back().cloned())
}
/// Retrieves the last value of a response header by its key.
///
/// # Arguments
///
/// - `K` - The header's key, which must implement `AsRef<str>`.
///
/// # Returns
///
/// - `String` - The last header value if exists.
///
/// # Panics
///
/// This function will panic if the header key is not found.
#[inline(always)]
pub fn get_header_back<K>(&self, key: K) -> String
where
K: AsRef<str>,
{
self.try_get_header_back(key).unwrap()
}
/// Checks if a header exists in the response.
///
/// # Arguments
///
/// - `K` - The header key to check, which must implement `AsRef<str>`.
///
/// # Returns
///
/// - `bool` - Whether the header exists.
#[inline(always)]
pub fn has_header<K>(&self, key: K) -> bool
where
K: AsRef<str>,
{
self.get_headers().contains_key(key.as_ref())
}
/// Checks if a header contains a specific value.
///
/// # Arguments
///
/// - `K` - The header key to check, which must implement `AsRef<str>`.
/// - `V` - The value to search for, which must implement `AsRef<str>`.
///
/// # Returns
///
/// - `bool` - Whether the header contains the value.
#[inline(always)]
pub fn has_header_value<K, V>(&self, key: K, value: V) -> bool
where
K: AsRef<str>,
V: AsRef<str>,
{
if let Some(values) = self.get_headers().get(key.as_ref()) {
let target: &str = value.as_ref();
values.iter().any(|data: &String| data == target)
} else {
false
}
}
/// Gets the number of headers in the response.
///
/// # Returns
///
/// - `usize` - The count of unique header keys.
#[inline(always)]
pub fn get_headers_size(&self) -> usize {
self.headers.len()
}
/// Tries to get the number of values for a specific header key.
///
/// # Arguments
///
/// - `K` - The header key to count, which must implement `AsRef<str>`.
///
/// # Returns
///
/// - `Option<usize>` - The count of values for the header.
#[inline(always)]
pub fn try_get_header_size<K>(&self, key: K) -> Option<usize>
where
K: AsRef<str>,
{
self.headers
.get(key.as_ref())
.map(|data: &VecDeque<String>| data.len())
}
/// Gets the number of values for a specific header key.
///
/// # Arguments
///
/// - `K` - The header key to count, which must implement `AsRef<str>`.
///
/// # Returns
///
/// - `usize` - The count of values for the header.
///
/// # Panics
///
/// This function will panic if the header key is not found.
#[inline(always)]
pub fn get_header_size<K>(&self, key: K) -> usize
where
K: AsRef<str>,
{
self.try_get_header_size(key).unwrap()
}
/// Gets the total number of header values in the response.
///
/// This counts all values across all headers, so a header with multiple values
/// will contribute more than one to the total count.
///
/// # Returns
///
/// - `usize` - The total count of all header values.
#[inline(always)]
pub fn get_headers_values_size(&self) -> usize {
self.headers
.values()
.map(|data: &VecDeque<String>| data.len())
.sum()
}
/// Retrieves the body content of the response as a UTF-8 encoded string.
///
/// This method uses `String::from_utf8_lossy` to convert the byte slice returned by `self.get_body()` as_ref a string.
/// If the byte slice contains invalid UTF-8 sequences, they will be replaced with the Unicode replacement character ().
///
/// # Returns
///
/// - `String` - The body content as a string.
#[inline(always)]
pub fn get_body_string(&self) -> String {
String::from_utf8_lossy(self.get_body()).into_owned()
}
/// Deserializes the body content of the response as_ref a specified type `T`.
///
/// This method first retrieves the body content as a byte slice using `self.get_body()`.
/// It then attempts to deserialize the byte slice as_ref the specified type `T` using `json_from_slice`.
///
/// The target type `T` is a type parameter of this method and must implement `DeserializeOwned`.
///
/// # Returns
///
/// - `Result<T, serde_json::Error>` - The deserialization result.
pub fn try_get_body_json<T>(&self) -> Result<T, serde_json::Error>
where
T: DeserializeOwned,
{
from_slice(self.get_body())
}
/// Deserializes the body content of the response as_ref a specified type `T`.
///
/// This method first retrieves the body content as a byte slice using `self.get_body()`.
/// It then attempts to deserialize the byte slice as_ref the specified type `T` using `json_from_slice`.
///
/// The target type `T` is a type parameter of this method and must implement `DeserializeOwned`.
///
/// # Returns
///
/// - `T` - The deserialized body content.
///
/// # Panics
///
/// This function will panic if the deserialization fails.
pub fn get_body_json<T>(&self) -> T
where
T: DeserializeOwned,
{
self.try_get_body_json().unwrap()
}
/// Validates whether a response header name is a non-empty RFC 9110 token.
///
/// # Arguments
///
/// - `&str` - The header key to inspect.
///
/// # Returns
///
/// - `bool` - `true` if every byte is a valid HTTP token character.
#[inline(always)]
fn is_valid_header_name(key: &str) -> bool {
!key.is_empty()
&& key
.bytes()
.all(|byte: u8| HTTP_HEADER_TOKEN_TABLE[byte as usize])
}
/// Validates whether a response header value or reason phrase contains no control bytes.
///
/// # Arguments
///
/// - `&str` - The header value or reason phrase to inspect.
///
/// # Returns
///
/// - `bool` - `true` if every byte is allowed inside an HTTP field value.
#[inline(always)]
fn is_valid_header_value(value: &str) -> bool {
let bytes: &[u8] = value.as_bytes();
let len: usize = bytes.len();
if len < 8 {
return bytes
.iter()
.all(|byte: &u8| HTTP_HEADER_VALUE_VALID_TABLE[*byte as usize]);
}
validate_header_value_swar(bytes).is_some()
}
/// Validates whether an HTTP version token contains no whitespace or control bytes.
///
/// # Arguments
///
/// - `&str` - The HTTP version text to inspect.
///
/// # Returns
///
/// - `bool` - `true` if the version token is safe to emit on the status line.
#[inline(always)]
fn is_valid_http_version(version: &str) -> bool {
!version.is_empty()
&& version
.bytes()
.all(|byte: u8| byte > SPACE_U8 && byte < HTTP_HEADER_DELETE)
}
/// Determines whether the header should be skipped during setting.
///
/// # Arguments
///
/// - `&str` - The header key to inspect.
///
/// # Returns
///
/// - `bool` - `true` if the header is invalid or framing-controlled, `false` otherwise.
#[inline(always)]
fn should_skip_header(&self, key: &str) -> bool {
!Self::is_valid_header_name(key) || key.eq_ignore_ascii_case(CONTENT_LENGTH)
}
/// Sets a header in the response, replacing any existing values.
///
/// This function replaces all existing values for a header with a single new value.
///
/// # Arguments
///
/// - `K` - The header key, which must implement `AsRef<str>`.
/// - `V` - The header value, which must implement `AsRef<String>`.
///
/// # Returns
///
/// - `&mut Self` - A mutable reference to self for chaining.
#[inline(always)]
fn set_header_without_check<K, V>(&mut self, key: K, value: V) -> &mut Self
where
K: AsRef<str>,
V: AsRef<str>,
{
let key: &str = key.as_ref();
let value: &str = value.as_ref();
if !self.get_headers().is_empty()
&& let Some(values) = self.get_mut_headers().get_mut(key)
{
values.truncate(1);
if let Some(slot) = values.front_mut() {
slot.clear();
slot.push_str(value);
} else {
values.push_back(value.to_owned());
}
return self;
}
// A recycled entry carries the buffers of the name and of the value,
// so a response that sets the same headers over and over stops
// allocating for them.
let (mut name, mut values): (String, VecDeque<String>) =
take_header_entry().unwrap_or_else(|| (String::new(), VecDeque::new()));
name.clear();
name.push_str(key);
// A recycled entry may carry the values of a header that was sent
// more than once. Those values belong to that header, so only the
// first one is kept and the rest are dropped.
while values.len() > 1 {
values.pop_back();
}
if values.is_empty() {
values.push_back(String::new());
}
if let Some(slot) = values.front_mut() {
slot.clear();
slot.push_str(value.as_ref());
}
self.get_mut_headers().insert(name, values);
self
}
/// Sets a header in the response, replacing any existing values.
///
/// This function replaces all existing values for a header with a single new value.
///
/// # Arguments
///
/// - `K` - The header key, which must implement `AsRef<str>`.
/// - `V` - The header value, which must implement `AsRef<String>`.
///
/// # Returns
///
/// - `&mut Self` - A mutable reference to self for chaining.
#[inline(always)]
pub fn set_header<K, V>(&mut self, key: K, value: V) -> &mut Self
where
K: AsRef<str>,
V: AsRef<str>,
{
let key: &str = key.as_ref();
let value: &str = value.as_ref();
if self.should_skip_header(key) || !Self::is_valid_header_value(value) {
return self;
}
self.set_header_without_check(key, value)
}
/// Sets multiple response headers in one batched thread-local pool borrow.
///
/// Applies the exact same validation as [`Response::set_header`] while amortizing
/// pool access and skipping duplicate probes when `self.headers` starts empty.
///
/// # Arguments
///
/// - `&[(K, V)]` - Slice of `(key, value)` header pairs to set.
///
/// # Returns
///
/// - `&mut Self` - A mutable reference to self for chaining.
#[inline]
pub fn set_headers_batch<K, V>(&mut self, pairs: &[(K, V)]) -> &mut Self
where
K: AsRef<str>,
V: AsRef<str>,
{
if pairs.is_empty() {
return self;
}
let headers: &mut ResponseHeaders = self.get_mut_headers();
let was_empty: bool = headers.is_empty();
if was_empty {
headers.reserve(pairs.len());
}
HEADER_ENTRY_POOL.with(|pool: &RefCell<Vec<(String, VecDeque<String>)>>| {
let mut pool: RefMut<'_, Vec<(String, VecDeque<String>)>> = pool.borrow_mut();
for (raw_key, raw_value) in pairs {
let key: &str = raw_key.as_ref();
let value: &str = raw_value.as_ref();
if !Self::is_valid_header_name(key)
|| key.eq_ignore_ascii_case(CONTENT_LENGTH)
|| !Self::is_valid_header_value(value)
{
continue;
}
if !was_empty && let Some(values) = headers.get_mut(key) {
values.truncate(1);
if let Some(slot) = values.front_mut() {
slot.clear();
slot.push_str(value);
} else {
values.push_back(value.to_owned());
}
continue;
}
let (mut name, mut values): (String, VecDeque<String>) = pool
.pop()
.unwrap_or_else(|| (String::new(), VecDeque::new()));
name.clear();
name.push_str(key);
if values.len() == 1 {
values[0].clear();
values[0].push_str(value);
} else {
while values.len() > 1 {
values.pop_back();
}
if let Some(slot) = values.front_mut() {
slot.clear();
slot.push_str(value);
} else {
values.push_back(value.to_owned());
}
}
headers.insert(name, values);
}
});
self
}
/// Adds a header to the response.
///
/// This function appends a value to the response headers.
/// If the header already exists, the new value will be added to the existing values.
///
/// # Arguments
///
/// - `K` - The header key, which must implement `AsRef<str>`.
/// - `V` - The header value, which must implement `AsRef<String>`.
///
/// # Returns
///
/// - `&mut Self` - A mutable reference to self for chaining.
#[inline(always)]
pub fn add_header<K, V>(&mut self, key: K, value: V) -> &mut Self
where
K: AsRef<str>,
V: AsRef<str>,
{
let key_ref: &str = key.as_ref();
let value_ref: &str = value.as_ref();
if self.should_skip_header(key_ref) || !Self::is_valid_header_value(value_ref) {
return self;
}
if let Some(existing) = self.get_mut_headers().get_mut(key_ref) {
existing.push_back(value_ref.to_owned());
return self;
}
let (mut name, mut values): (String, VecDeque<String>) =
take_header_entry().unwrap_or_else(|| (String::new(), VecDeque::new()));
name.clear();
name.push_str(key_ref);
while values.len() > 1 {
values.pop_back();
}
if let Some(slot) = values.front_mut() {
slot.clear();
slot.push_str(value_ref);
} else {
values.push_back(value_ref.to_owned());
}
self.get_mut_headers().insert(name, values);
self
}
/// Removes a header from the response.
///
/// This function removes all values for the specified header key.
///
/// # Arguments
///
/// - `K` - The header key to remove, which must implement `AsRef<str>`.
///
/// # Returns
///
/// - `&mut Self` - A mutable reference to self for chaining.
#[inline(always)]
pub fn remove_header<K>(&mut self, key: K) -> &mut Self
where
K: AsRef<str>,
{
let _: bool = self.get_mut_headers().remove(key.as_ref()).is_some();
self
}
/// Removes a specific value from a header in the response.
///
/// This function removes only the specified value from the header.
/// If the header has multiple values, only the matching value is removed.
/// If this was the last value for the header, the entire header is removed.
///
/// # Arguments
///
/// - `K` - The header key, which must implement `AsRef<str>`.
/// - `V` - The value to remove, which must implement `AsRef<String>`.
///
/// # Returns
///
/// - `&mut Self` - A mutable reference to self for chaining.
#[inline(always)]
pub fn remove_header_value<K, V>(&mut self, key: K, value: V) -> &mut Self
where
K: AsRef<str>,
V: AsRef<str>,
{
let key_ref: &str = key.as_ref();
let value_ref: &str = value.as_ref();
let should_remove: bool = if let Some(values) = self.get_mut_headers().get_mut(key_ref) {
values.retain(|data: &String| data != value_ref);
values.is_empty()
} else {
false
};
if should_remove {
self.get_mut_headers().remove(key_ref);
}
self
}
/// Clears all headers from the response.
///
/// This function removes all headers, leaving the headers map empty.
///
/// # Returns
///
/// - `&mut Self` - A mutable reference to self for chaining.
#[inline(always)]
pub fn clear_headers(&mut self) -> &mut Self {
self.recycle_headers();
self
}
/// Resets the response to its default state while retaining allocated capacity.
///
/// This keeps the header map and body allocations so persistent
/// (keep-alive) connections avoid repeated allocation per request.
///
/// # Returns
///
/// - `&mut Self` - A mutable reference to self for chaining.
#[inline(always)]
pub fn reset(&mut self) -> &mut Self {
let http_status: HttpStatus = HttpStatus::default();
self.set_version(HttpVersion::Http1_1);
self.set_status_code(http_status.code());
let phrase: &'static str = HttpStatus::phrase_ref(http_status.code());
let stored: &mut String = self.get_mut_reason_phrase();
if stored.as_str() != phrase {
stored.clear();
stored.push_str(phrase);
}
self.recycle_headers();
self.get_mut_body().clear();
self
}
/// Hands the header entries to the pool and empties the header map.
///
/// The map ends up empty, exactly as clearing it would, but the name and
/// the value buffers of every header survive in the pool. The next
/// response reuses them instead of allocating new ones.
///
/// # Returns
///
/// - `()` - The headers have been recycled.
fn recycle_headers(&mut self) {
let headers: &mut ResponseHeaders = self.get_mut_headers();
if headers.is_empty() {
return;
}
return_header_entries(headers.drain());
}
/// Tries to parse cookies from the `Set-Cookie` header.
///
/// This method retrieves the last `Set-Cookie` header value and parses it
/// into a collection of key-value pairs representing the cookies.
///
/// # Returns
///
/// - `Option<HashMapXxHash3_64<String, String>>` - The parsed cookies if the `Set-Cookie` header exists, otherwise `None`.
#[inline(always)]
pub fn try_get_cookies(&self) -> Option<HashMapXxHash3_64<String, String>> {
let mut cookies: HashMapXxHash3_64<String, String> = hash_map_xx_hash3_64();
let mut found_header: bool = false;
for (name, values) in self.get_headers() {
if !name.eq_ignore_ascii_case(SET_COOKIE) {
continue;
}
for header_value in values {
found_header = true;
let parsed: CookieBuilder = CookieBuilder::parse(header_value);
if !parsed.get_name().is_empty() {
cookies.insert(parsed.get_name().clone(), parsed.get_value().clone());
}
}
}
found_header.then_some(cookies)
}
/// Parses cookies from the `Set-Cookie` headers.
///
/// This method retrieves all `Set-Cookie` header values and parses each one
/// into a collection of key-value pairs representing the cookies.
///
/// # Returns
///
/// - `HashMapXxHash3_64<String, String>` - The parsed cookies.
///
/// # Panics
///
/// This function will panic if the `Set-Cookie` header is not found.
#[inline(always)]
pub fn get_cookies(&self) -> HashMapXxHash3_64<String, String> {
self.try_get_cookies().unwrap()
}
/// Tries to get a cookie value by its key from `Set-Cookie` headers.
///
/// This method parses the cookies from all `Set-Cookie` headers,
/// then attempts to retrieve the value for the specified key.
///
/// # Arguments
///
/// - `K` - The cookie key, which implements `AsRef<str>`.
///
/// # Returns
///
/// - `Option<String>` - The cookie value if exists.
#[inline(always)]
pub fn try_get_cookie<K>(&self, key: K) -> Option<String>
where
K: AsRef<str>,
{
let key_ref: &str = key.as_ref();
if key_ref.is_empty() || !is_cookie_name_valid(key_ref) {
return None;
}
let mut found: Option<&str> = None;
for (name, values) in self.get_headers() {
if !name.eq_ignore_ascii_case(SET_COOKIE) {
continue;
}
for header_value in values {
let first_part: &str = header_value.split(SEMICOLON).next().unwrap_or(EMPTY_STR);
if let Some((cookie_name, cookie_val)) = first_part.trim().split_once(EQUAL)
&& cookie_name.trim() == key_ref
{
let val: &str = cookie_val.trim();
if !val.bytes().any(is_control_byte) {
found = Some(val);
}
}
}
}
found.map(str::to_owned)
}
/// Gets a cookie value by its key from `Set-Cookie` headers.
///
/// This method parses the cookies from all `Set-Cookie` headers,
/// then retrieves the value for the specified key.
///
/// # Arguments
///
/// - `K` - The cookie key, which implements `AsRef<str>`.
///
/// # Returns
///
/// - `String` - The cookie value.
///
/// # Panics
///
/// This function will panic if the `Set-Cookie` header is not found
/// or the cookie key does not exist.
#[inline(always)]
pub fn get_cookie<K>(&self, key: K) -> String
where
K: AsRef<str>,
{
self.try_get_cookie(key).unwrap()
}
/// Removes framing fields before a header-only response is serialized.
#[cold]
fn clear_framing_headers(&mut self) {
self.get_mut_headers()
.retain(|name: &String, _: &mut VecDeque<String>| {
!name.eq_ignore_ascii_case(CONTENT_LENGTH)
&& !name.eq_ignore_ascii_case(TRANSFER_ENCODING)
});
}
/// Builds the full HTTP response as a byte vector.
///
/// This method constructs the complete HTTP response, including the status line,
/// headers, and body. It handles content encoding, content type, connection
/// management, and content length.
/// Informational, 204, 205, and 304 responses never serialize the body.
/// A 205 response declares a zero length; the other bodyless statuses
/// omit framing headers. For 304, the body cannot establish the length
/// of the selected representation.
///
/// # Returns
///
/// - `Vec<u8>` - The complete HTTP response bytes.
#[inline]
pub fn build(&mut self) -> Vec<u8> {
let mut out: Vec<u8> = Vec::new();
Self::build_wire_into::<true, true>(self, &mut out);
out
}
/// Appends the full HTTP response wire bytes directly into `out`.
///
/// Unlike [`Response::build`], this avoids allocating a new byte vector and
/// skips mutating default framing headers back into `self.headers`, making
/// repeated keep-alive serialization zero-allocation when `out` is reused.
///
/// # Arguments
///
/// - `&mut Vec<u8>` - Destination byte buffer to append wire bytes to.
#[inline]
pub fn build_into(&mut self, out: &mut Vec<u8>) {
Self::build_wire_into::<true, false>(self, out);
}
/// Builds an HTTP response to `HEAD` without serializing or compressing its body.
///
/// Set the body to the matching `GET` representation if its length is known.
/// An empty buffer, an event stream, or a body that would be compressed does
/// not establish that length, so the generated response omits it.
///
/// # Returns
///
/// - `Vec<u8>` - The status line and headers ending at the header terminator.
#[must_use]
pub fn build_head(&mut self) -> Vec<u8> {
let mut out: Vec<u8> = Vec::new();
Self::build_wire_into::<false, true>(self, &mut out);
out
}
/// Appends the header-only `HEAD` response wire bytes directly into `out`.
///
/// # Arguments
///
/// - `&mut Vec<u8>` - Destination byte buffer to append wire bytes to.
#[inline]
pub fn build_head_into(&mut self, out: &mut Vec<u8>) {
Self::build_wire_into::<false, false>(self, out);
}
/// Serializes either a full response or the header-only response to `HEAD` into `out`.
///
/// # Arguments
///
/// - `&mut Vec<u8>` - Destination wire buffer.
fn build_wire_into<const INCLUDE_BODY: bool, const POPULATE_HEADERS: bool>(
&mut self,
out: &mut Vec<u8>,
) {
let status_code: usize = self.get_status_code();
let is_default_ok: bool =
status_code == HttpStatus::Ok.code() && self.get_reason_phrase().as_str() == OK;
if !is_default_ok
&& (self.get_reason_phrase().is_empty()
|| self.get_reason_phrase().as_str() == OK
|| !Self::is_valid_header_value(self.get_reason_phrase()))
{
// The phrase is written into the existing buffer rather than
// replaced, so a response that announces the same status over and
// over stops allocating for it.
let phrase: &'static str = HttpStatus::phrase_ref(status_code);
if self.get_reason_phrase().as_str() != phrase {
let stored: &mut String = self.get_mut_reason_phrase();
stored.clear();
stored.push_str(phrase);
}
}
if INCLUDE_BODY
&& self.get_headers().is_empty()
&& status_code >= HttpStatus::Ok.code()
&& status_code != HttpStatus::NoContent.code()
&& status_code != HttpStatus::ResetContent.code()
&& status_code != HttpStatus::NotModified.code()
{
let content_type: &str = default_content_type();
let body_len: usize = self.get_body().len();
let mut digits: [u8; B_20] = [0; B_20];
let rendered_len: &str = render_length(body_len, &mut digits);
let fast_prefix: Option<&[u8]> = if is_default_ok {
match self.get_version() {
HttpVersion::Http1_1 => Some(FAST_HTTP11_200_CL_PREFIX),
HttpVersion::Http2 => Some(FAST_HTTP2_200_CL_PREFIX),
HttpVersion::Http3 => Some(FAST_HTTP3_200_CL_PREFIX),
_ => None,
}
} else {
None
};
let body_slice: &[u8] = self.get_body().as_slice();
if let Some(prefix) = fast_prefix {
let prefix_len: usize = prefix.len();
let digits_bytes: &[u8] = rendered_len.as_bytes();
let digits_len: usize = digits_bytes.len();
let suffix_len: usize = FAST_DEFAULT_HEADERS_SUFFIX.len();
let total_size: usize = prefix_len + digits_len + suffix_len + body_len;
let base: usize = out.len();
out.reserve(total_size);
// SAFETY: `out` has reserved at least `total_size` spare bytes after `base`;
// we copy four contiguous non-overlapping regions and advance length to `base + total_size`.
unsafe {
let mut dst: *mut u8 = out.as_mut_ptr().add(base);
ptr::copy_nonoverlapping(prefix.as_ptr(), dst, prefix_len);
dst = dst.add(prefix_len);
ptr::copy_nonoverlapping(digits_bytes.as_ptr(), dst, digits_len);
dst = dst.add(digits_len);
ptr::copy_nonoverlapping(FAST_DEFAULT_HEADERS_SUFFIX.as_ptr(), dst, suffix_len);
dst = dst.add(suffix_len);
if body_len > 0 {
ptr::copy_nonoverlapping(body_slice.as_ptr(), dst, body_len);
}
out.set_len(base + total_size);
}
} else {
let raw_version: &str = self.get_version().as_str();
let version_str: &str = if !matches!(self.get_version(), HttpVersion::Unknown(_))
|| Self::is_valid_http_version(raw_version)
{
raw_version
} else {
HTTP_VERSION_1_1
};
let phrase_str: &str = self.get_reason_phrase().as_str();
let mut code_digits: [u8; B_20] = [0; B_20];
let rendered_code: &str = render_length(status_code, &mut code_digits);
let total_size: usize = version_str.len()
+ 1
+ rendered_code.len()
+ 1
+ phrase_str.len()
+ FAST_CL_PREFIX.len()
+ rendered_len.len()
+ FAST_DEFAULT_HEADERS_SUFFIX.len()
+ body_len;
out.reserve(total_size);
out.extend_from_slice(version_str.as_bytes());
out.push(b' ');
out.extend_from_slice(rendered_code.as_bytes());
out.push(b' ');
out.extend_from_slice(phrase_str.as_bytes());
out.extend_from_slice(FAST_CL_PREFIX);
out.extend_from_slice(rendered_len.as_bytes());
out.extend_from_slice(FAST_DEFAULT_HEADERS_SUFFIX);
out.extend_from_slice(body_slice);
}
if POPULATE_HEADERS {
self.populate_default_headers_batch(content_type, rendered_len);
}
return;
}
let mut has_connection: bool = false;
let mut has_content_type: bool = false;
let mut is_event_stream: bool = false;
let mut has_transfer_encoding: bool = false;
let mut has_non_canonical_cl: bool = false;
let mut compress_type: Option<Compress> = None;
let mut existing_headers_bytes: usize = 0;
for (name, values) in self.get_headers() {
if name.len() == 14
&& name != CONTENT_LENGTH
&& name.eq_ignore_ascii_case(CONTENT_LENGTH)
{
has_non_canonical_cl = true;
}
if values.is_empty() {
continue;
}
for header_value in values.iter() {
existing_headers_bytes +=
name.len() + COLON.len() + header_value.len() + HTTP_BR.len();
}
match name.len() {
10 if name.eq_ignore_ascii_case(CONNECTION) => {
has_connection = true;
}
12 if name.eq_ignore_ascii_case(CONTENT_TYPE) => {
has_content_type = true;
if let Some(value) = values.back() {
is_event_stream = value
.split(SEMICOLON)
.next()
.unwrap_or(EMPTY_STR)
.trim()
.eq_ignore_ascii_case(TEXT_EVENT_STREAM);
}
}
16 if name.eq_ignore_ascii_case(CONTENT_ENCODING) => {
compress_type = values
.back()
.map(|value: &String| value.parse::<Compress>().unwrap_or_default());
}
17 if name.eq_ignore_ascii_case(TRANSFER_ENCODING) => {
has_transfer_encoding = true;
}
_ => {}
}
}
let is_bodyless: bool = (100..=199).contains(&status_code)
|| status_code == HttpStatus::NoContent.code()
|| status_code == HttpStatus::ResetContent.code()
|| status_code == HttpStatus::NotModified.code();
let mut compressed_body: Option<Vec<u8>> = None;
let mut emit_content_length: Option<usize> = None;
let mut skip_wire_cl: bool = false;
let mut skip_wire_te: bool = false;
let body: &[u8] = if POPULATE_HEADERS {
if !has_connection {
self.set_header_without_check(CONNECTION, KEEP_ALIVE);
}
match status_code {
100..=199 | 204 | 205 | 304 => {
self.clear_framing_headers();
if status_code == HttpStatus::ResetContent.code() {
self.set_header_without_check(CONTENT_LENGTH, ZERO_STR);
}
&[]
}
_ => {
if !has_content_type {
self.set_header_without_check(CONTENT_TYPE, default_content_type());
}
if INCLUDE_BODY {
if let Some(encoding) = compress_type
&& !encoding.is_unknown()
{
let mut buf: Vec<u8> = take_compress_buffer();
let _: bool = encoding.encode_into(self.get_body(), &mut buf);
compressed_body = Some(buf);
}
if has_transfer_encoding {
self.get_mut_headers().retain(
|name: &String, _: &mut VecDeque<String>| {
!name.eq_ignore_ascii_case(CONTENT_LENGTH)
},
);
} else if !is_event_stream {
if has_non_canonical_cl {
self.get_mut_headers().retain(
|name: &String, _: &mut VecDeque<String>| {
name == CONTENT_LENGTH
|| !name.eq_ignore_ascii_case(CONTENT_LENGTH)
},
);
}
let body_len: usize = compressed_body
.as_ref()
.map_or_else(|| self.get_body().len(), Vec::len);
self.set_wire_content_length(body_len);
}
compressed_body
.as_deref()
.unwrap_or_else(|| self.get_body().as_slice())
} else {
self.clear_framing_headers();
let body_len: usize = self.get_body().len();
if body_len != 0
&& !is_event_stream
&& !compress_type
.is_some_and(|encoding: Compress| !encoding.is_unknown())
{
self.set_wire_content_length(body_len);
}
&[]
}
}
}
} else if is_bodyless {
skip_wire_cl = true;
skip_wire_te = true;
if status_code == HttpStatus::ResetContent.code() {
emit_content_length = Some(0);
}
&[]
} else if INCLUDE_BODY {
if let Some(encoding) = compress_type
&& !encoding.is_unknown()
{
let mut buf: Vec<u8> = take_compress_buffer();
let _: bool = encoding.encode_into(self.get_body(), &mut buf);
compressed_body = Some(buf);
}
if has_transfer_encoding {
skip_wire_cl = true;
} else if !is_event_stream {
let body_len: usize = compressed_body
.as_ref()
.map_or_else(|| self.get_body().len(), Vec::len);
skip_wire_cl = true;
emit_content_length = Some(body_len);
}
compressed_body
.as_deref()
.unwrap_or_else(|| self.get_body().as_slice())
} else {
skip_wire_cl = true;
skip_wire_te = true;
let body_len: usize = self.get_body().len();
if body_len != 0
&& !is_event_stream
&& !compress_type.is_some_and(|encoding: Compress| !encoding.is_unknown())
{
emit_content_length = Some(body_len);
}
&[]
};
let extra_default_bytes: usize = if POPULATE_HEADERS {
FAST_CONNECTION_KEEP_ALIVE_LINE.len()
+ FAST_DEFAULT_CONTENT_TYPE_LINE.len()
+ FAST_CONTENT_LENGTH_PREFIX.len()
+ B_20
+ HTTP_BR.len()
} else {
let mut extra: usize = 0;
if !has_connection {
extra += FAST_CONNECTION_KEEP_ALIVE_LINE.len();
}
if !is_bodyless && !has_content_type {
extra += FAST_DEFAULT_CONTENT_TYPE_LINE.len();
}
if emit_content_length.is_some() {
extra += FAST_CONTENT_LENGTH_PREFIX.len() + B_20 + HTTP_BR.len();
}
extra
};
let head_size: usize = self.get_reason_phrase().len()
+ B_16
+ HTTP_BR.len()
+ existing_headers_bytes
+ extra_default_bytes;
out.reserve(head_size + body.len());
let fast_status_line: Option<&[u8]> = if is_default_ok {
match self.get_version() {
HttpVersion::Http1_1 => Some(FAST_HTTP11_200_LINE),
HttpVersion::Http2 => Some(FAST_HTTP2_200_LINE),
HttpVersion::Http3 => Some(FAST_HTTP3_200_LINE),
_ => None,
}
} else {
None
};
if let Some(status_line) = fast_status_line {
out.extend_from_slice(status_line);
} else {
let raw_version: &str = self.get_version().as_str();
let version_str: &str = if !matches!(self.get_version(), HttpVersion::Unknown(_))
|| Self::is_valid_http_version(raw_version)
{
raw_version
} else {
HTTP_VERSION_1_1
};
out.extend_from_slice(version_str.as_bytes());
out.push(b' ');
let mut code: [u8; B_20] = [0; B_20];
out.extend_from_slice(render_length(status_code, &mut code).as_bytes());
out.push(b' ');
out.extend_from_slice(self.get_reason_phrase().as_bytes());
out.extend_from_slice(HTTP_BR.as_bytes());
}
for (header_key, header_values) in self.get_headers().iter() {
if !POPULATE_HEADERS {
if skip_wire_cl
&& header_key.len() == 14
&& header_key.eq_ignore_ascii_case(CONTENT_LENGTH)
{
continue;
}
if skip_wire_te
&& header_key.len() == 17
&& header_key.eq_ignore_ascii_case(TRANSFER_ENCODING)
{
continue;
}
}
if !Self::is_valid_header_name(header_key) {
continue;
}
for header_value in header_values.iter() {
if Self::is_valid_header_value(header_value) {
Self::push_header(out, header_key, header_value);
}
}
}
if !POPULATE_HEADERS {
if !has_connection {
out.extend_from_slice(FAST_CONNECTION_KEEP_ALIVE_LINE);
}
if !is_bodyless && !has_content_type {
out.extend_from_slice(FAST_DEFAULT_CONTENT_TYPE_LINE);
}
if let Some(body_len) = emit_content_length {
if body_len == 0 {
out.extend_from_slice(FAST_CONTENT_LENGTH_ZERO_LINE);
} else {
let mut cl_digits: [u8; B_20] = [0; B_20];
let rendered: &str = render_length(body_len, &mut cl_digits);
out.extend_from_slice(FAST_CONTENT_LENGTH_PREFIX);
out.extend_from_slice(rendered.as_bytes());
out.extend_from_slice(HTTP_BR.as_bytes());
}
}
}
out.extend_from_slice(HTTP_BR.as_bytes());
out.extend_from_slice(body);
if let Some(buf) = compressed_body {
return_compress_buffer(buf);
}
}
/// Populates the three default wire headers using one thread-local pool lookup.
///
/// # Arguments
///
/// - `&str` - The default content type value.
/// - `&str` - The decimal body length string.
#[inline(always)]
fn populate_default_headers_batch(&mut self, content_type: &str, rendered_len: &str) {
let headers: &mut ResponseHeaders = self.get_mut_headers();
let pairs: [(&str, &str); 3] = [
(CONNECTION, KEEP_ALIVE),
(CONTENT_TYPE, content_type),
(CONTENT_LENGTH, rendered_len),
];
HEADER_ENTRY_POOL.with(|pool: &RefCell<Vec<(String, VecDeque<String>)>>| {
let mut pool: RefMut<'_, Vec<(String, VecDeque<String>)>> = pool.borrow_mut();
for (key, value) in pairs {
let (mut name, mut values): (String, VecDeque<String>) = pool
.pop()
.unwrap_or_else(|| (String::new(), VecDeque::new()));
name.clear();
name.push_str(key);
if values.len() == 1 {
values[0].clear();
values[0].push_str(value);
} else {
while values.len() > 1 {
values.pop_back();
}
if let Some(slot) = values.front_mut() {
slot.clear();
slot.push_str(value);
} else {
values.push_back(value.to_owned());
}
}
headers.insert(name, values);
}
});
}
/// Sets the generated content length using a stack buffer.
///
/// # Arguments
///
/// - `usize` - The selected representation's length in bytes.
#[inline(always)]
fn set_wire_content_length(&mut self, body_len: usize) {
let mut digits: [u8; B_20] = [0; B_20];
let rendered: &str = render_length(body_len, &mut digits);
self.set_header_without_check(CONTENT_LENGTH, rendered);
}
}